diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2140970015d099763797d60a98a3a3b6f4b5f219 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/__init__.py @@ -0,0 +1,14 @@ +""" +Module containing private utility functions +=========================================== + +The ``scipy._lib`` namespace is empty (for now). Tests for all +utilities in submodules of ``_lib`` can be run with:: + + from scipy import _lib + _lib.test() + +""" +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..855cea294d0c4eadb3a10fbd42a4f8ca99e384a9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11197c583ae6666087244db278423b46751c239c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api_no_0d.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api_no_0d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2715620a138f7a4a0391e963dccc78eef19c094e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api_no_0d.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eeb0e043d339550d90d2849f27208e09eb600d5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f8d1f07422509730bdcb29863abcb1d2f7008f Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8da6353b782cbecd114250d91d758d6da4f5bd5b Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9570017fe428589050fb6f3cc86cd295107fce1b Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd1ca458d94ce18170f8e9f02da788c41d895934 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc7e55e7071fae4ceeacf5041d80a069cf58118 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a14713944ed3be866ad0481bff7bfa9414e2d27 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26f4775b8a0134ee3138ecec6285ea3a581f168a Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d42910c40a7e9a1e40ca6a55b8044fec11e8c3c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dc92e02f7e711dc9358a2810ce11117b002c84f Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4985d816d19ec58036c83ebf9711e8764c40802 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04d2c2eb10741af630456d43beaace18fde878d2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dec479ce8b3605976a9a6c19ddb6a7a3ac46e22d Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8750ea3f7124a0aca4d358f0e389304ce915c62e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a8a5efab1652bc1b3ea1e160ef09d35457b2237 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a84283aabe40a61957e3c5b5c0feee8ee23f6ece Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py b/venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4094d88c75d93367c481f5c3f603424cd6c13c --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py @@ -0,0 +1,606 @@ +"""Utility functions to use Python Array API compatible libraries. + +For the context about the Array API see: +https://data-apis.org/array-api/latest/purpose_and_scope.html + +The SciPy use case of the Array API is described on the following page: +https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy +""" +import os + +from types import ModuleType +from typing import Any, Literal, TypeAlias + +import numpy as np +import numpy.typing as npt + +from scipy._lib import array_api_compat +from scipy._lib.array_api_compat import ( + is_array_api_obj, + size as xp_size, + numpy as np_compat, + device as xp_device, + is_numpy_namespace as is_numpy, + is_cupy_namespace as is_cupy, + is_torch_namespace as is_torch, + is_jax_namespace as is_jax, + is_array_api_strict_namespace as is_array_api_strict +) + +__all__ = [ + '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal', + 'get_xp_devices', + 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch', + 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for', + 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less', + 'xp_copy', 'xp_copysign', 'xp_device', + 'xp_moveaxis_to_end', 'xp_ravel', 'xp_real', 'xp_sign', 'xp_size', + 'xp_take_along_axis', 'xp_unsupported_param_msg', 'xp_vector_norm', +] + + +# To enable array API and strict array-like input validation +SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False) +# To control the default device - for use in the test suite only +SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu") + +_GLOBAL_CONFIG = { + "SCIPY_ARRAY_API": SCIPY_ARRAY_API, + "SCIPY_DEVICE": SCIPY_DEVICE, +} + + +Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589) +ArrayLike: TypeAlias = Array | npt.ArrayLike + + +def _compliance_scipy(arrays): + """Raise exceptions on known-bad subclasses. + + The following subclasses are not supported and raise and error: + - `numpy.ma.MaskedArray` + - `numpy.matrix` + - NumPy arrays which do not have a boolean or numerical dtype + - Any array-like which is neither array API compatible nor coercible by NumPy + - Any array-like which is coerced by NumPy to an unsupported dtype + """ + for i in range(len(arrays)): + array = arrays[i] + + from scipy.sparse import issparse + # this comes from `_util._asarray_validated` + if issparse(array): + msg = ('Sparse arrays/matrices are not supported by this function. ' + 'Perhaps one of the `scipy.sparse.linalg` functions ' + 'would work instead.') + raise ValueError(msg) + + if isinstance(array, np.ma.MaskedArray): + raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.") + elif isinstance(array, np.matrix): + raise TypeError("Inputs of type `numpy.matrix` are not supported.") + if isinstance(array, np.ndarray | np.generic): + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + raise TypeError(f"An argument has dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported.") + elif not is_array_api_obj(array): + try: + array = np.asanyarray(array) + except TypeError: + raise TypeError("An argument is neither array API compatible nor " + "coercible by NumPy.") + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + message = ( + f"An argument was coerced to an unsupported dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported." + ) + raise TypeError(message) + arrays[i] = array + return arrays + + +def _check_finite(array: Array, xp: ModuleType) -> None: + """Check for NaNs or Infs.""" + msg = "array must not contain infs or NaNs" + try: + if not xp.all(xp.isfinite(array)): + raise ValueError(msg) + except TypeError: + raise ValueError(msg) + + +def array_namespace(*arrays: Array) -> ModuleType: + """Get the array API compatible namespace for the arrays xs. + + Parameters + ---------- + *arrays : sequence of array_like + Arrays used to infer the common namespace. + + Returns + ------- + namespace : module + Common namespace. + + Notes + ----- + Thin wrapper around `array_api_compat.array_namespace`. + + 1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed + dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``. + 2. `_compliance_scipy` raise exceptions on known-bad subclasses. See + its definition for more details. + + When the global switch is False, it defaults to the `numpy` namespace. + In that case, there is no compliance check. This is a convenience to + ease the adoption. Otherwise, arrays must comply with the new rules. + """ + if not _GLOBAL_CONFIG["SCIPY_ARRAY_API"]: + # here we could wrap the namespace if needed + return np_compat + + _arrays = [array for array in arrays if array is not None] + + _arrays = _compliance_scipy(_arrays) + + return array_api_compat.array_namespace(*_arrays) + + +def _asarray( + array: ArrayLike, + dtype: Any = None, + order: Literal['K', 'A', 'C', 'F'] | None = None, + copy: bool | None = None, + *, + xp: ModuleType | None = None, + check_finite: bool = False, + subok: bool = False, + ) -> Array: + """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and + `subok`. + + Memory layout parameter `order` is not exposed in the Array API standard. + `order` is only enforced if the input array implementation + is NumPy based, otherwise `order` is just silently ignored. + + `check_finite` is also not a keyword in the array API standard; included + here for convenience rather than that having to be a separate function + call inside SciPy functions. + + `subok` is included to allow this function to preserve the behaviour of + `np.asanyarray` for NumPy based inputs. + """ + if xp is None: + xp = array_namespace(array) + if is_numpy(xp): + # Use NumPy API to support order + if copy is True: + array = np.array(array, order=order, dtype=dtype, subok=subok) + elif subok: + array = np.asanyarray(array, order=order, dtype=dtype) + else: + array = np.asarray(array, order=order, dtype=dtype) + else: + try: + array = xp.asarray(array, dtype=dtype, copy=copy) + except TypeError: + coerced_xp = array_namespace(xp.asarray(3)) + array = coerced_xp.asarray(array, dtype=dtype, copy=copy) + + if check_finite: + _check_finite(array, xp) + + return array + + +def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array: + """ + Copies an array. + + Parameters + ---------- + x : array + + xp : array_namespace + + Returns + ------- + copy : array + Copied array + + Notes + ----- + This copy function does not offer all the semantics of `np.copy`, i.e. the + `subok` and `order` keywords are not used. + """ + # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg, + # so this uses our other helper `_asarray`. + if xp is None: + xp = array_namespace(x) + + return _asarray(x, copy=True, xp=xp) + + +def _strict_check(actual, desired, xp, *, + check_namespace=True, check_dtype=True, check_shape=True, + check_0d=True): + __tracebackhide__ = True # Hide traceback for py.test + if check_namespace: + _assert_matching_namespace(actual, desired) + + # only NumPy distinguishes between scalars and arrays; we do if check_0d=True. + # do this first so we can then cast to array (and thus use the array API) below. + if is_numpy(xp) and check_0d: + _msg = ("Array-ness does not match:\n Actual: " + f"{type(actual)}\n Desired: {type(desired)}") + assert ((xp.isscalar(actual) and xp.isscalar(desired)) + or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg + + actual = xp.asarray(actual) + desired = xp.asarray(desired) + + if check_dtype: + _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}" + assert actual.dtype == desired.dtype, _msg + + if check_shape: + _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}" + assert actual.shape == desired.shape, _msg + + desired = xp.broadcast_to(desired, actual.shape) + return actual, desired + + +def _assert_matching_namespace(actual, desired): + __tracebackhide__ = True # Hide traceback for py.test + actual = actual if isinstance(actual, tuple) else (actual,) + desired_space = array_namespace(desired) + for arr in actual: + arr_space = array_namespace(arr) + _msg = (f"Namespaces do not match.\n" + f"Actual: {arr_space.__name__}\n" + f"Desired: {desired_space.__name__}") + assert arr_space == desired_space, _msg + + +def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + if xp is None: + xp = array_namespace(actual) + + actual, desired = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg) + elif is_torch(xp): + # PyTorch recommends using `rtol=0, atol=0` like this + # to test for exact equality + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True, + check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_array_equal(actual, desired, err_msg=err_msg) + + +def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True, + check_dtype=True, check_shape=True, check_0d=True, + err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + if xp is None: + xp = array_namespace(actual) + + actual, desired = _strict_check( + actual, desired, xp, + check_namespace=check_namespace, check_dtype=check_dtype, + check_shape=check_shape, check_0d=check_0d + ) + + floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating')) + if rtol is None and floating: + # multiplier of 4 is used as for `np.float64` this puts the default `rtol` + # roughly half way between sqrt(eps) and the default for + # `numpy.testing.assert_allclose`, 1e-7 + rtol = xp.finfo(actual.dtype).eps**0.5 * 4 + elif rtol is None: + rtol = 1e-7 + + if is_cupy(xp): + return xp.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + elif is_torch(xp): + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol, + equal_nan=True, check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + + +def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None): + __tracebackhide__ = True # Hide traceback for py.test + if xp is None: + xp = array_namespace(actual) + + actual, desired = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_less(actual, desired, + err_msg=err_msg, verbose=verbose) + elif is_torch(xp): + if actual.device.type != 'cpu': + actual = actual.cpu() + if desired.device.type != 'cpu': + desired = desired.cpu() + # JAX uses `np.testing` + return np.testing.assert_array_less(actual, desired, + err_msg=err_msg, verbose=verbose) + + +def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def assert_almost_equal(actual, desired, decimal=7, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def xp_unsupported_param_msg(param: Any) -> str: + return f'Providing {param!r} is only supported for numpy arrays.' + + +def is_complex(x: Array, xp: ModuleType) -> bool: + return xp.isdtype(x.dtype, 'complex floating') + + +def get_xp_devices(xp: ModuleType) -> list[str] | list[None]: + """Returns a list of available devices for the given namespace.""" + devices: list[str] = [] + if is_torch(xp): + devices += ['cpu'] + import torch # type: ignore[import] + num_cuda = torch.cuda.device_count() + for i in range(0, num_cuda): + devices += [f'cuda:{i}'] + if torch.backends.mps.is_available(): + devices += ['mps'] + return devices + elif is_cupy(xp): + import cupy # type: ignore[import] + num_cuda = cupy.cuda.runtime.getDeviceCount() + for i in range(0, num_cuda): + devices += [f'cuda:{i}'] + return devices + elif is_jax(xp): + import jax # type: ignore[import] + num_cpu = jax.device_count(backend='cpu') + for i in range(0, num_cpu): + devices += [f'cpu:{i}'] + num_gpu = jax.device_count(backend='gpu') + for i in range(0, num_gpu): + devices += [f'gpu:{i}'] + num_tpu = jax.device_count(backend='tpu') + for i in range(0, num_tpu): + devices += [f'tpu:{i}'] + return devices + + # given namespace is not known to have a list of available devices; + # return `[None]` so that one can use this in tests for `device=None`. + return [None] + + +def scipy_namespace_for(xp: ModuleType) -> ModuleType | None: + """Return the `scipy`-like namespace of a non-NumPy backend + + That is, return the namespace corresponding with backend `xp` that contains + `scipy` sub-namespaces like `linalg` and `special`. If no such namespace + exists, return ``None``. Useful for dispatching. + """ + + if is_cupy(xp): + import cupyx # type: ignore[import-not-found,import-untyped] + return cupyx.scipy + + if is_jax(xp): + import jax # type: ignore[import-not-found] + return jax.scipy + + if is_torch(xp): + return xp + + return None + + +# temporary substitute for xp.moveaxis, which is not yet in all backends +# or covered by array_api_compat. +def xp_moveaxis_to_end( + x: Array, + source: int, + /, *, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(xp) if xp is None else xp + axes = list(range(x.ndim)) + temp = axes.pop(source) + axes = axes + [temp] + return xp.permute_dims(x, axes) + + +# temporary substitute for xp.copysign, which is not yet in all backends +# or covered by array_api_compat. +def xp_copysign(x1: Array, x2: Array, /, *, xp: ModuleType | None = None) -> Array: + # no attempt to account for special cases + xp = array_namespace(x1, x2) if xp is None else xp + abs_x1 = xp.abs(x1) + return xp.where(x2 >= 0, abs_x1, -abs_x1) + + +# partial substitute for xp.sign, which does not cover the NaN special case +# that I need. (https://github.com/data-apis/array-api-compat/issues/136) +def xp_sign(x: Array, /, *, xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + if is_numpy(xp): # only NumPy implements the special cases correctly + return xp.sign(x) + sign = xp.zeros_like(x) + one = xp.asarray(1, dtype=x.dtype) + sign = xp.where(x > 0, one, sign) + sign = xp.where(x < 0, -one, sign) + sign = xp.where(xp.isnan(x), xp.nan*one, sign) + return sign + +# maybe use `scipy.linalg` if/when array API support is added +def xp_vector_norm(x: Array, /, *, + axis: int | tuple[int] | None = None, + keepdims: bool = False, + ord: int | float = 2, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + + if SCIPY_ARRAY_API: + # check for optional `linalg` extension + if hasattr(xp, 'linalg'): + return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord) + else: + if ord != 2: + raise ValueError( + "only the Euclidean norm (`ord=2`) is currently supported in " + "`xp_vector_norm` for backends not implementing the `linalg` " + "extension." + ) + # return (x @ x)**0.5 + # or to get the right behavior with nd, complex arrays + return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5 + else: + # to maintain backwards compatibility + return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims) + + +def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Equivalent of np.ravel written in terms of array API + # Even though it's one line, it comes up so often that it's worth having + # this function for readability + xp = array_namespace(x) if xp is None else xp + return xp.reshape(x, (-1,)) + + +def xp_real(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Convenience wrapper of xp.real that allows non-complex input; + # see data-apis/array-api#824 + xp = array_namespace(x) if xp is None else xp + return xp.real(x) if xp.isdtype(x.dtype, 'complex floating') else x + + +def xp_take_along_axis(arr: Array, + indices: Array, /, *, + axis: int = -1, + xp: ModuleType | None = None) -> Array: + # Dispatcher for np.take_along_axis for backends that support it; + # see data-apis/array-api/pull#816 + xp = array_namespace(arr) if xp is None else xp + if is_torch(xp): + return xp.take_along_dim(arr, indices, dim=axis) + elif is_array_api_strict(xp): + raise NotImplementedError("Array API standard does not define take_along_axis") + else: + return xp.take_along_axis(arr, indices, axis) + + +# utility to broadcast arrays and promote to common dtype +def xp_broadcast_promote(*args, ensure_writeable=False, force_floating=False, xp=None): + xp = array_namespace(*args) if xp is None else xp + + args = [(_asarray(arg, subok=True) if arg is not None else arg) for arg in args] + args_not_none = [arg for arg in args if arg is not None] + + # determine minimum dtype + default_float = xp.asarray(1.).dtype + dtypes = [arg.dtype for arg in args_not_none] + try: # follow library's prefered mixed promotion rules + dtype = xp.result_type(*dtypes) + if force_floating and xp.isdtype(dtype, 'integral'): + # If we were to add `default_float` before checking whether the result + # type is otherwise integral, we risk promotion from lower float. + dtype = xp.result_type(dtype, default_float) + except TypeError: # mixed type promotion isn't defined + float_dtypes = [dtype for dtype in dtypes + if not xp.isdtype(dtype, 'integral')] + if float_dtypes: + dtype = xp.result_type(*float_dtypes, default_float) + elif force_floating: + dtype = default_float + else: + dtype = xp.result_type(*dtypes) + + # determine result shape + shapes = {arg.shape for arg in args_not_none} + try: + shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1 + else args_not_none[0].shape) + except ValueError as e: + message = "Array shapes are incompatible for broadcasting." + raise ValueError(message) from e + + out = [] + for arg in args: + if arg is None: + out.append(arg) + continue + + # broadcast only if needed + # Even if two arguments need broadcasting, this is faster than + # `broadcast_arrays`, especially since we've already determined `shape` + if arg.shape != shape: + kwargs = {'subok': True} if is_numpy(xp) else {} + arg = xp.broadcast_to(arg, shape, **kwargs) + + # convert dtype/copy only if needed + if (arg.dtype != dtype) or ensure_writeable: + arg = xp.astype(arg, dtype, copy=True) + out.append(arg) + + return out + + +def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array: + xp = array_namespace(arr) if xp is None else xp + arr_dtype = arr.dtype + # The standard float dtypes are float32 and float64. + # Convert float32 to complex64, + # and float64 (and non-standard real dtypes) to complex128 + if xp.isdtype(arr_dtype, xp.float32): + arr = xp.astype(arr, xp.complex64) + elif xp.isdtype(arr_dtype, 'real floating'): + arr = xp.astype(arr, xp.complex128) + + return arr + + +def xp_default_dtype(xp): + """Query the namespace-dependent default floating-point dtype. + """ + if is_torch(xp): + # historically, we allow pytorch to keep its default of float32 + return xp.get_default_dtype() + else: + # we default to float64 + return xp.float64 diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py b/venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b6fe1affd172eea620760a20f185f192d37b69 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py @@ -0,0 +1,103 @@ +""" +Extra testing functions that forbid 0d-input, see #21044 + +While the xp_assert_* functions generally aim to follow the conventions of the +underlying `xp` library, NumPy in particular is inconsistent in its handling +of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897. + +For example, this means that the following operations (as of v2.0.1) currently +return scalars, even though a 0d-array would often be more appropriate: + + import numpy as np + np.array(0) * 2 # scalar, not 0d array + - np.array(0) # scalar, not 0d-array + np.sin(np.array(0)) # scalar, not 0d array + np.mean([1, 2, 3]) # scalar, not 0d array + +Libraries like CuPy tend to return a 0d-array in scenarios like those above, +and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality +of the inconsistencies present in NumPy, as well as 20+ years of code on top, +the `xp_assert_*` functions here enforce consistency in the only way that +doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type. + +However, when scalars are not generally the expected NumPy return type, +it remains preferable to use the assert functions from +the `scipy._lib._array_api` module, which have less surprising behaviour. +""" +from scipy._lib._array_api import array_namespace, is_numpy +from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base, + xp_assert_equal as xp_assert_equal_base, + xp_assert_less as xp_assert_less_base) + +__all__: list[str] = [] + + +def _check_scalar(actual, desired, *, xp=None, **kwargs): + __tracebackhide__ = True # Hide traceback for py.test + + if xp is None: + xp = array_namespace(actual) + + # necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape + desired = xp.asarray(desired) + + # Only NumPy distinguishes between scalars and arrays; + # shape check in xp_assert_* is sufficient except for shape == () + if not (is_numpy(xp) and desired.shape == ()): + return + + _msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow " + "the convention of many NumPy functions, returning a scalar when a " + "0d-array would be correct. The specialized `xp_assert_*` functions " + "in the `scipy._lib._array_api_no_0d` module err on the side of " + "caution and do not accept 0d-arrays by default. If the correct " + "result may legitimately be a 0d-array, pass `check_0d=True`, " + "or use the `xp_assert_*` functions from `scipy._lib._array_api`.") + assert xp.isscalar(actual), _msg + + +def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs): + # in contrast to xp_assert_equal_base, this defaults to check_0d=False, + # but will do an extra check in that case, which forbids 0d-arrays for `actual` + __tracebackhide__ = True # Hide traceback for py.test + + # array-ness (check_0d == True) is taken care of by the *_base functions + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs) + + +def xp_assert_close(actual, desired, *, check_0d=False, **kwargs): + # as for xp_assert_equal + __tracebackhide__ = True + + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs) + + +def xp_assert_less(actual, desired, *, check_0d=False, **kwargs): + # as for xp_assert_equal + __tracebackhide__ = True + + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs) + + +def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def assert_almost_equal(actual, desired, decimal=7, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py b/venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..bb562e4348f46dc1137afe3d3ce50f1149c85376 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py @@ -0,0 +1,225 @@ +import sys as _sys +from keyword import iskeyword as _iskeyword + + +def _validate_names(typename, field_names, extra_field_names): + """ + Ensure that all the given names are valid Python identifiers that + do not start with '_'. Also check that there are no duplicates + among field_names + extra_field_names. + """ + for name in [typename] + field_names + extra_field_names: + if not isinstance(name, str): + raise TypeError('typename and all field names must be strings') + if not name.isidentifier(): + raise ValueError('typename and all field names must be valid ' + f'identifiers: {name!r}') + if _iskeyword(name): + raise ValueError('typename and all field names cannot be a ' + f'keyword: {name!r}') + + seen = set() + for name in field_names + extra_field_names: + if name.startswith('_'): + raise ValueError('Field names cannot start with an underscore: ' + f'{name!r}') + if name in seen: + raise ValueError(f'Duplicate field name: {name!r}') + seen.add(name) + + +# Note: This code is adapted from CPython:Lib/collections/__init__.py +def _make_tuple_bunch(typename, field_names, extra_field_names=None, + module=None): + """ + Create a namedtuple-like class with additional attributes. + + This function creates a subclass of tuple that acts like a namedtuple + and that has additional attributes. + + The additional attributes are listed in `extra_field_names`. The + values assigned to these attributes are not part of the tuple. + + The reason this function exists is to allow functions in SciPy + that currently return a tuple or a namedtuple to returned objects + that have additional attributes, while maintaining backwards + compatibility. + + This should only be used to enhance *existing* functions in SciPy. + New functions are free to create objects as return values without + having to maintain backwards compatibility with an old tuple or + namedtuple return value. + + Parameters + ---------- + typename : str + The name of the type. + field_names : list of str + List of names of the values to be stored in the tuple. These names + will also be attributes of instances, so the values in the tuple + can be accessed by indexing or as attributes. At least one name + is required. See the Notes for additional restrictions. + extra_field_names : list of str, optional + List of names of values that will be stored as attributes of the + object. See the notes for additional restrictions. + + Returns + ------- + cls : type + The new class. + + Notes + ----- + There are restrictions on the names that may be used in `field_names` + and `extra_field_names`: + + * The names must be unique--no duplicates allowed. + * The names must be valid Python identifiers, and must not begin with + an underscore. + * The names must not be Python keywords (e.g. 'def', 'and', etc., are + not allowed). + + Examples + -------- + >>> from scipy._lib._bunch import _make_tuple_bunch + + Create a class that acts like a namedtuple with length 2 (with field + names `x` and `y`) that will also have the attributes `w` and `beta`: + + >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta']) + + `Result` is the new class. We call it with keyword arguments to create + a new instance with given values. + + >>> result1 = Result(x=1, y=2, w=99, beta=0.5) + >>> result1 + Result(x=1, y=2, w=99, beta=0.5) + + `result1` acts like a tuple of length 2: + + >>> len(result1) + 2 + >>> result1[:] + (1, 2) + + The values assigned when the instance was created are available as + attributes: + + >>> result1.y + 2 + >>> result1.beta + 0.5 + """ + if len(field_names) == 0: + raise ValueError('field_names must contain at least one name') + + if extra_field_names is None: + extra_field_names = [] + _validate_names(typename, field_names, extra_field_names) + + typename = _sys.intern(str(typename)) + field_names = tuple(map(_sys.intern, field_names)) + extra_field_names = tuple(map(_sys.intern, extra_field_names)) + + all_names = field_names + extra_field_names + arg_list = ', '.join(field_names) + full_list = ', '.join(all_names) + repr_fmt = ''.join(('(', + ', '.join(f'{name}=%({name})r' for name in all_names), + ')')) + tuple_new = tuple.__new__ + _dict, _tuple, _zip = dict, tuple, zip + + # Create all the named tuple methods to be added to the class namespace + + s = f"""\ +def __new__(_cls, {arg_list}, **extra_fields): + return _tuple_new(_cls, ({arg_list},)) + +def __init__(self, {arg_list}, **extra_fields): + for key in self._extra_fields: + if key not in extra_fields: + raise TypeError("missing keyword argument '%s'" % (key,)) + for key, val in extra_fields.items(): + if key not in self._extra_fields: + raise TypeError("unexpected keyword argument '%s'" % (key,)) + self.__dict__[key] = val + +def __setattr__(self, key, val): + if key in {repr(field_names)}: + raise AttributeError("can't set attribute %r of class %r" + % (key, self.__class__.__name__)) + else: + self.__dict__[key] = val +""" + del arg_list + namespace = {'_tuple_new': tuple_new, + '__builtins__': dict(TypeError=TypeError, + AttributeError=AttributeError), + '__name__': f'namedtuple_{typename}'} + exec(s, namespace) + __new__ = namespace['__new__'] + __new__.__doc__ = f'Create new instance of {typename}({full_list})' + __init__ = namespace['__init__'] + __init__.__doc__ = f'Instantiate instance of {typename}({full_list})' + __setattr__ = namespace['__setattr__'] + + def __repr__(self): + 'Return a nicely formatted representation string' + return self.__class__.__name__ + repr_fmt % self._asdict() + + def _asdict(self): + 'Return a new dict which maps field names to their values.' + out = _dict(_zip(self._fields, self)) + out.update(self.__dict__) + return out + + def __getnewargs_ex__(self): + 'Return self as a plain tuple. Used by copy and pickle.' + return _tuple(self), self.__dict__ + + # Modify function metadata to help with introspection and debugging + for method in (__new__, __repr__, _asdict, __getnewargs_ex__): + method.__qualname__ = f'{typename}.{method.__name__}' + + # Build-up the class namespace dictionary + # and use type() to build the result class + class_namespace = { + '__doc__': f'{typename}({full_list})', + '_fields': field_names, + '__new__': __new__, + '__init__': __init__, + '__repr__': __repr__, + '__setattr__': __setattr__, + '_asdict': _asdict, + '_extra_fields': extra_field_names, + '__getnewargs_ex__': __getnewargs_ex__, + } + for index, name in enumerate(field_names): + + def _get(self, index=index): + return self[index] + class_namespace[name] = property(_get) + for name in extra_field_names: + + def _get(self, name=name): + return self.__dict__[name] + class_namespace[name] = property(_get) + + result = type(typename, (tuple,), class_namespace) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the named tuple is created. Bypass this step in environments + # where sys._getframe is not defined (Jython for example) or sys._getframe + # is not defined for arguments greater than 0 (IronPython), or where the + # user has specified a particular module. + if module is None: + try: + module = _sys._getframe(1).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + if module is not None: + result.__module__ = module + __new__.__module__ = module + + return result diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py b/venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..1980d06f5489e6633fb611c35bfb56903bd63e7f --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py @@ -0,0 +1,251 @@ +from . import _ccallback_c + +import ctypes + +PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0] + +ffi = None + +class CData: + pass + +def _import_cffi(): + global ffi, CData + + if ffi is not None: + return + + try: + import cffi + ffi = cffi.FFI() + CData = ffi.CData + except ImportError: + ffi = False + + +class LowLevelCallable(tuple): + """ + Low-level callback function. + + Some functions in SciPy take as arguments callback functions, which + can either be python callables or low-level compiled functions. Using + compiled callback functions can improve performance somewhat by + avoiding wrapping data in Python objects. + + Such low-level functions in SciPy are wrapped in `LowLevelCallable` + objects, which can be constructed from function pointers obtained from + ctypes, cffi, Cython, or contained in Python `PyCapsule` objects. + + .. seealso:: + + Functions accepting low-level callables: + + `scipy.integrate.quad`, `scipy.ndimage.generic_filter`, + `scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform` + + Usage examples: + + :ref:`ndimage-ccallbacks`, :ref:`quad-callbacks` + + Parameters + ---------- + function : {PyCapsule, ctypes function pointer, cffi function pointer} + Low-level callback function. + user_data : {PyCapsule, ctypes void pointer, cffi void pointer} + User data to pass on to the callback function. + signature : str, optional + Signature of the function. If omitted, determined from *function*, + if possible. + + Attributes + ---------- + function + Callback function given. + user_data + User data given. + signature + Signature of the function. + + Methods + ------- + from_cython + Class method for constructing callables from Cython C-exported + functions. + + Notes + ----- + The argument ``function`` can be one of: + + - PyCapsule, whose name contains the C function signature + - ctypes function pointer + - cffi function pointer + + The signature of the low-level callback must match one of those expected + by the routine it is passed to. + + If constructing low-level functions from a PyCapsule, the name of the + capsule must be the corresponding signature, in the format:: + + return_type (arg1_type, arg2_type, ...) + + For example:: + + "void (double)" + "double (double, int *, void *)" + + The context of a PyCapsule passed in as ``function`` is used as ``user_data``, + if an explicit value for ``user_data`` was not given. + + """ + + # Make the class immutable + __slots__ = () + + def __new__(cls, function, user_data=None, signature=None): + # We need to hold a reference to the function & user data, + # to prevent them going out of scope + item = cls._parse_callback(function, user_data, signature) + return tuple.__new__(cls, (item, function, user_data)) + + def __repr__(self): + return f"LowLevelCallable({self.function!r}, {self.user_data!r})" + + @property + def function(self): + return tuple.__getitem__(self, 1) + + @property + def user_data(self): + return tuple.__getitem__(self, 2) + + @property + def signature(self): + return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0)) + + def __getitem__(self, idx): + raise ValueError() + + @classmethod + def from_cython(cls, module, name, user_data=None, signature=None): + """ + Create a low-level callback function from an exported Cython function. + + Parameters + ---------- + module : module + Cython module where the exported function resides + name : str + Name of the exported function + user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional + User data to pass on to the callback function. + signature : str, optional + Signature of the function. If omitted, determined from *function*. + + """ + try: + function = module.__pyx_capi__[name] + except AttributeError as e: + message = "Given module is not a Cython module with __pyx_capi__ attribute" + raise ValueError(message) from e + except KeyError as e: + message = f"No function {name!r} found in __pyx_capi__ of the module" + raise ValueError(message) from e + return cls(function, user_data, signature) + + @classmethod + def _parse_callback(cls, obj, user_data=None, signature=None): + _import_cffi() + + if isinstance(obj, LowLevelCallable): + func = tuple.__getitem__(obj, 0) + elif isinstance(obj, PyCFuncPtr): + func, signature = _get_ctypes_func(obj, signature) + elif isinstance(obj, CData): + func, signature = _get_cffi_func(obj, signature) + elif _ccallback_c.check_capsule(obj): + func = obj + else: + raise ValueError("Given input is not a callable or a " + "low-level callable (pycapsule/ctypes/cffi)") + + if isinstance(user_data, ctypes.c_void_p): + context = _get_ctypes_data(user_data) + elif isinstance(user_data, CData): + context = _get_cffi_data(user_data) + elif user_data is None: + context = 0 + elif _ccallback_c.check_capsule(user_data): + context = user_data + else: + raise ValueError("Given user data is not a valid " + "low-level void* pointer (pycapsule/ctypes/cffi)") + + return _ccallback_c.get_raw_capsule(func, signature, context) + + +# +# ctypes helpers +# + +def _get_ctypes_func(func, signature=None): + # Get function pointer + func_ptr = ctypes.cast(func, ctypes.c_void_p).value + + # Construct function signature + if signature is None: + signature = _typename_from_ctypes(func.restype) + " (" + for j, arg in enumerate(func.argtypes): + if j == 0: + signature += _typename_from_ctypes(arg) + else: + signature += ", " + _typename_from_ctypes(arg) + signature += ")" + + return func_ptr, signature + + +def _typename_from_ctypes(item): + if item is None: + return "void" + elif item is ctypes.c_void_p: + return "void *" + + name = item.__name__ + + pointer_level = 0 + while name.startswith("LP_"): + pointer_level += 1 + name = name[3:] + + if name.startswith('c_'): + name = name[2:] + + if pointer_level > 0: + name += " " + "*"*pointer_level + + return name + + +def _get_ctypes_data(data): + # Get voidp pointer + return ctypes.cast(data, ctypes.c_void_p).value + + +# +# CFFI helpers +# + +def _get_cffi_func(func, signature=None): + # Get function pointer + func_ptr = ffi.cast('uintptr_t', func) + + # Get signature + if signature is None: + signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ') + + return func_ptr, signature + + +def _get_cffi_data(data): + # Get pointer + return ffi.cast('uintptr_t', data) diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py b/venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..683c5c8e518705e710212dafc01363f92a2f947d --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py @@ -0,0 +1,254 @@ +""" +Disjoint set data structure +""" + + +class DisjointSet: + """ Disjoint set data structure for incremental connectivity queries. + + .. versionadded:: 1.6.0 + + Attributes + ---------- + n_subsets : int + The number of subsets. + + Methods + ------- + add + merge + connected + subset + subset_size + subsets + __getitem__ + + Notes + ----- + This class implements the disjoint set [1]_, also known as the *union-find* + or *merge-find* data structure. The *find* operation (implemented in + `__getitem__`) implements the *path halving* variant. The *merge* method + implements the *merge by size* variant. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure + + Examples + -------- + >>> from scipy.cluster.hierarchy import DisjointSet + + Initialize a disjoint set: + + >>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b']) + + Merge some subsets: + + >>> disjoint_set.merge(1, 2) + True + >>> disjoint_set.merge(3, 'a') + True + >>> disjoint_set.merge('a', 'b') + True + >>> disjoint_set.merge('b', 'b') + False + + Find root elements: + + >>> disjoint_set[2] + 1 + >>> disjoint_set['b'] + 3 + + Test connectivity: + + >>> disjoint_set.connected(1, 2) + True + >>> disjoint_set.connected(1, 'b') + False + + List elements in disjoint set: + + >>> list(disjoint_set) + [1, 2, 3, 'a', 'b'] + + Get the subset containing 'a': + + >>> disjoint_set.subset('a') + {'a', 3, 'b'} + + Get the size of the subset containing 'a' (without actually instantiating + the subset): + + >>> disjoint_set.subset_size('a') + 3 + + Get all subsets in the disjoint set: + + >>> disjoint_set.subsets() + [{1, 2}, {'a', 3, 'b'}] + """ + def __init__(self, elements=None): + self.n_subsets = 0 + self._sizes = {} + self._parents = {} + # _nbrs is a circular linked list which links connected elements. + self._nbrs = {} + # _indices tracks the element insertion order in `__iter__`. + self._indices = {} + if elements is not None: + for x in elements: + self.add(x) + + def __iter__(self): + """Returns an iterator of the elements in the disjoint set. + + Elements are ordered by insertion order. + """ + return iter(self._indices) + + def __len__(self): + return len(self._indices) + + def __contains__(self, x): + return x in self._indices + + def __getitem__(self, x): + """Find the root element of `x`. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + root : hashable object + Root element of `x`. + """ + if x not in self._indices: + raise KeyError(x) + + # find by "path halving" + parents = self._parents + while self._indices[x] != self._indices[parents[x]]: + parents[x] = parents[parents[x]] + x = parents[x] + return x + + def add(self, x): + """Add element `x` to disjoint set + """ + if x in self._indices: + return + + self._sizes[x] = 1 + self._parents[x] = x + self._nbrs[x] = x + self._indices[x] = len(self._indices) + self.n_subsets += 1 + + def merge(self, x, y): + """Merge the subsets of `x` and `y`. + + The smaller subset (the child) is merged into the larger subset (the + parent). If the subsets are of equal size, the root element which was + first inserted into the disjoint set is selected as the parent. + + Parameters + ---------- + x, y : hashable object + Elements to merge. + + Returns + ------- + merged : bool + True if `x` and `y` were in disjoint sets, False otherwise. + """ + xr = self[x] + yr = self[y] + if self._indices[xr] == self._indices[yr]: + return False + + sizes = self._sizes + if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]): + xr, yr = yr, xr + self._parents[yr] = xr + self._sizes[xr] += self._sizes[yr] + self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr] + self.n_subsets -= 1 + return True + + def connected(self, x, y): + """Test whether `x` and `y` are in the same subset. + + Parameters + ---------- + x, y : hashable object + Elements to test. + + Returns + ------- + result : bool + True if `x` and `y` are in the same set, False otherwise. + """ + return self._indices[self[x]] == self._indices[self[y]] + + def subset(self, x): + """Get the subset containing `x`. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + result : set + Subset containing `x`. + """ + if x not in self._indices: + raise KeyError(x) + + result = [x] + nxt = self._nbrs[x] + while self._indices[nxt] != self._indices[x]: + result.append(nxt) + nxt = self._nbrs[nxt] + return set(result) + + def subset_size(self, x): + """Get the size of the subset containing `x`. + + Note that this method is faster than ``len(self.subset(x))`` because + the size is directly read off an internal field, without the need to + instantiate the full subset. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + result : int + Size of the subset containing `x`. + """ + return self._sizes[self[x]] + + def subsets(self): + """Get all the subsets in the disjoint set. + + Returns + ------- + result : list + Subsets in the disjoint set. + """ + result = [] + visited = set() + for x in self: + if x not in visited: + xset = self.subset(x) + visited.update(xset) + result.append(xset) + return result diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py b/venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..f345539efe76b9f9439957a78e5ebdc1ec2bf517 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py @@ -0,0 +1,761 @@ +# copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2 +"""Extract reference documentation from the NumPy source tree.""" + +import copy +import inspect +import pydoc +import re +import sys +import textwrap +from collections import namedtuple +from collections.abc import Callable, Mapping +from functools import cached_property +from warnings import warn + + +def strip_blank_lines(l): + "Remove leading and trailing blank lines from a list of lines" + while l and not l[0].strip(): + del l[0] + while l and not l[-1].strip(): + del l[-1] + return l + + +class Reader: + """A line-based string reader.""" + + def __init__(self, data): + """ + Parameters + ---------- + data : str + String with lines separated by '\\n'. + + """ + if isinstance(data, list): + self._str = data + else: + self._str = data.split("\n") # store string as list of lines + + self.reset() + + def __getitem__(self, n): + return self._str[n] + + def reset(self): + self._l = 0 # current line nr + + def read(self): + if not self.eof(): + out = self[self._l] + self._l += 1 + return out + else: + return "" + + def seek_next_non_empty_line(self): + for l in self[self._l :]: + if l.strip(): + break + else: + self._l += 1 + + def eof(self): + return self._l >= len(self._str) + + def read_to_condition(self, condition_func): + start = self._l + for line in self[start:]: + if condition_func(line): + return self[start : self._l] + self._l += 1 + if self.eof(): + return self[start : self._l + 1] + return [] + + def read_to_next_empty_line(self): + self.seek_next_non_empty_line() + + def is_empty(line): + return not line.strip() + + return self.read_to_condition(is_empty) + + def read_to_next_unindented_line(self): + def is_unindented(line): + return line.strip() and (len(line.lstrip()) == len(line)) + + return self.read_to_condition(is_unindented) + + def peek(self, n=0): + if self._l + n < len(self._str): + return self[self._l + n] + else: + return "" + + def is_empty(self): + return not "".join(self._str).strip() + + +class ParseError(Exception): + def __str__(self): + message = self.args[0] + if hasattr(self, "docstring"): + message = f"{message} in {self.docstring!r}" + return message + + +Parameter = namedtuple("Parameter", ["name", "type", "desc"]) + + +class NumpyDocString(Mapping): + """Parses a numpydoc string to an abstract representation + + Instances define a mapping from section title to structured data. + + """ + + sections = { + "Signature": "", + "Summary": [""], + "Extended Summary": [], + "Parameters": [], + "Attributes": [], + "Methods": [], + "Returns": [], + "Yields": [], + "Receives": [], + "Other Parameters": [], + "Raises": [], + "Warns": [], + "Warnings": [], + "See Also": [], + "Notes": [], + "References": "", + "Examples": "", + "index": {}, + } + + def __init__(self, docstring, config=None): + orig_docstring = docstring + docstring = textwrap.dedent(docstring).split("\n") + + self._doc = Reader(docstring) + self._parsed_data = copy.deepcopy(self.sections) + + try: + self._parse() + except ParseError as e: + e.docstring = orig_docstring + raise + + def __getitem__(self, key): + return self._parsed_data[key] + + def __setitem__(self, key, val): + if key not in self._parsed_data: + self._error_location(f"Unknown section {key}", error=False) + else: + self._parsed_data[key] = val + + def __iter__(self): + return iter(self._parsed_data) + + def __len__(self): + return len(self._parsed_data) + + def _is_at_section(self): + self._doc.seek_next_non_empty_line() + + if self._doc.eof(): + return False + + l1 = self._doc.peek().strip() # e.g. Parameters + + if l1.startswith(".. index::"): + return True + + l2 = self._doc.peek(1).strip() # ---------- or ========== + if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1): + snip = "\n".join(self._doc._str[:2]) + "..." + self._error_location( + f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}", + error=False, + ) + return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) + + def _strip(self, doc): + i = 0 + j = 0 + for i, line in enumerate(doc): + if line.strip(): + break + + for j, line in enumerate(doc[::-1]): + if line.strip(): + break + + return doc[i : len(doc) - j] + + def _read_to_next_section(self): + section = self._doc.read_to_next_empty_line() + + while not self._is_at_section() and not self._doc.eof(): + if not self._doc.peek(-1).strip(): # previous line was empty + section += [""] + + section += self._doc.read_to_next_empty_line() + + return section + + def _read_sections(self): + while not self._doc.eof(): + data = self._read_to_next_section() + name = data[0].strip() + + if name.startswith(".."): # index section + yield name, data[1:] + elif len(data) < 2: + yield StopIteration + else: + yield name, self._strip(data[2:]) + + def _parse_param_list(self, content, single_element_is_type=False): + content = dedent_lines(content) + r = Reader(content) + params = [] + while not r.eof(): + header = r.read().strip() + if " : " in header: + arg_name, arg_type = header.split(" : ", maxsplit=1) + else: + # NOTE: param line with single element should never have a + # a " :" before the description line, so this should probably + # warn. + if header.endswith(" :"): + header = header[:-2] + if single_element_is_type: + arg_name, arg_type = "", header + else: + arg_name, arg_type = header, "" + + desc = r.read_to_next_unindented_line() + desc = dedent_lines(desc) + desc = strip_blank_lines(desc) + + params.append(Parameter(arg_name, arg_type, desc)) + + return params + + # See also supports the following formats. + # + # + # SPACE* COLON SPACE+ SPACE* + # ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE* + # ( COMMA SPACE+ )* SPACE* COLON SPACE+ SPACE* + + # is one of + # + # COLON COLON BACKTICK BACKTICK + # where + # is a legal function name, and + # is any nonempty sequence of word characters. + # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` + # is a string describing the function. + + _role = r":(?P(py:)?\w+):" + _funcbacktick = r"`(?P(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" + _funcplain = r"(?P[a-zA-Z0-9_\.-]+)" + _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" + _funcnamenext = _funcname.replace("role", "rolenext") + _funcnamenext = _funcnamenext.replace("name", "namenext") + _description = r"(?P\s*:(\s+(?P\S+.*))?)?\s*$" + _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") + _line_rgx = re.compile( + r"^\s*" + + r"(?P" + + _funcname # group for all function names + + r"(?P([,]\s+" + + _funcnamenext + + r")*)" + + r")" + + r"(?P[,\.])?" # end of "allfuncs" + + _description # Some function lists have a trailing comma (or period) '\s*' + ) + + # Empty elements are replaced with '..' + empty_description = ".." + + def _parse_see_also(self, content): + """ + func_name : Descriptive text + continued text + another_func_name : Descriptive text + func_name1, func_name2, :meth:`func_name`, func_name3 + + """ + + content = dedent_lines(content) + + items = [] + + def parse_item_name(text): + """Match ':role:`name`' or 'name'.""" + m = self._func_rgx.match(text) + if not m: + self._error_location(f"Error parsing See Also entry {line!r}") + role = m.group("role") + name = m.group("name") if role else m.group("name2") + return name, role, m.end() + + rest = [] + for line in content: + if not line.strip(): + continue + + line_match = self._line_rgx.match(line) + description = None + if line_match: + description = line_match.group("desc") + if line_match.group("trailing") and description: + self._error_location( + "Unexpected comma or period after function list at index %d of " + 'line "%s"' % (line_match.end("trailing"), line), + error=False, + ) + if not description and line.startswith(" "): + rest.append(line.strip()) + elif line_match: + funcs = [] + text = line_match.group("allfuncs") + while True: + if not text.strip(): + break + name, role, match_end = parse_item_name(text) + funcs.append((name, role)) + text = text[match_end:].strip() + if text and text[0] == ",": + text = text[1:].strip() + rest = list(filter(None, [description])) + items.append((funcs, rest)) + else: + self._error_location(f"Error parsing See Also entry {line!r}") + return items + + def _parse_index(self, section, content): + """ + .. index:: default + :refguide: something, else, and more + + """ + + def strip_each_in(lst): + return [s.strip() for s in lst] + + out = {} + section = section.split("::") + if len(section) > 1: + out["default"] = strip_each_in(section[1].split(","))[0] + for line in content: + line = line.split(":") + if len(line) > 2: + out[line[1]] = strip_each_in(line[2].split(",")) + return out + + def _parse_summary(self): + """Grab signature (if given) and summary""" + if self._is_at_section(): + return + + # If several signatures present, take the last one + while True: + summary = self._doc.read_to_next_empty_line() + summary_str = " ".join([s.strip() for s in summary]).strip() + compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$") + if compiled.match(summary_str): + self["Signature"] = summary_str + if not self._is_at_section(): + continue + break + + if summary is not None: + self["Summary"] = summary + + if not self._is_at_section(): + self["Extended Summary"] = self._read_to_next_section() + + def _parse(self): + self._doc.reset() + self._parse_summary() + + sections = list(self._read_sections()) + section_names = {section for section, content in sections} + + has_yields = "Yields" in section_names + # We could do more tests, but we are not. Arbitrarily. + if not has_yields and "Receives" in section_names: + msg = "Docstring contains a Receives section but not Yields." + raise ValueError(msg) + + for section, content in sections: + if not section.startswith(".."): + section = (s.capitalize() for s in section.split(" ")) + section = " ".join(section) + if self.get(section): + self._error_location( + "The section %s appears twice in %s" + % (section, "\n".join(self._doc._str)) + ) + + if section in ("Parameters", "Other Parameters", "Attributes", "Methods"): + self[section] = self._parse_param_list(content) + elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"): + self[section] = self._parse_param_list( + content, single_element_is_type=True + ) + elif section.startswith(".. index::"): + self["index"] = self._parse_index(section, content) + elif section == "See Also": + self["See Also"] = self._parse_see_also(content) + else: + self[section] = content + + @property + def _obj(self): + if hasattr(self, "_cls"): + return self._cls + elif hasattr(self, "_f"): + return self._f + return None + + def _error_location(self, msg, error=True): + if self._obj is not None: + # we know where the docs came from: + try: + filename = inspect.getsourcefile(self._obj) + except TypeError: + filename = None + # Make UserWarning more descriptive via object introspection. + # Skip if introspection fails + name = getattr(self._obj, "__name__", None) + if name is None: + name = getattr(getattr(self._obj, "__class__", None), "__name__", None) + if name is not None: + msg += f" in the docstring of {name}" + msg += f" in {filename}." if filename else "" + if error: + raise ValueError(msg) + else: + warn(msg, stacklevel=3) + + # string conversion routines + + def _str_header(self, name, symbol="-"): + return [name, len(name) * symbol] + + def _str_indent(self, doc, indent=4): + return [" " * indent + line for line in doc] + + def _str_signature(self): + if self["Signature"]: + return [self["Signature"].replace("*", r"\*")] + [""] + return [""] + + def _str_summary(self): + if self["Summary"]: + return self["Summary"] + [""] + return [] + + def _str_extended_summary(self): + if self["Extended Summary"]: + return self["Extended Summary"] + [""] + return [] + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_header(name) + for param in self[name]: + parts = [] + if param.name: + parts.append(param.name) + if param.type: + parts.append(param.type) + out += [" : ".join(parts)] + if param.desc and "".join(param.desc).strip(): + out += self._str_indent(param.desc) + out += [""] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += self[name] + out += [""] + return out + + def _str_see_also(self, func_role): + if not self["See Also"]: + return [] + out = [] + out += self._str_header("See Also") + out += [""] + last_had_desc = True + for funcs, desc in self["See Also"]: + assert isinstance(funcs, list) + links = [] + for func, role in funcs: + if role: + link = f":{role}:`{func}`" + elif func_role: + link = f":{func_role}:`{func}`" + else: + link = f"`{func}`_" + links.append(link) + link = ", ".join(links) + out += [link] + if desc: + out += self._str_indent([" ".join(desc)]) + last_had_desc = True + else: + last_had_desc = False + out += self._str_indent([self.empty_description]) + + if last_had_desc: + out += [""] + out += [""] + return out + + def _str_index(self): + idx = self["index"] + out = [] + output_index = False + default_index = idx.get("default", "") + if default_index: + output_index = True + out += [f".. index:: {default_index}"] + for section, references in idx.items(): + if section == "default": + continue + output_index = True + out += [f" :{section}: {', '.join(references)}"] + if output_index: + return out + return "" + + def __str__(self, func_role=""): + out = [] + out += self._str_signature() + out += self._str_summary() + out += self._str_extended_summary() + out += self._str_param_list("Parameters") + for param_list in ("Attributes", "Methods"): + out += self._str_param_list(param_list) + for param_list in ( + "Returns", + "Yields", + "Receives", + "Other Parameters", + "Raises", + "Warns", + ): + out += self._str_param_list(param_list) + out += self._str_section("Warnings") + out += self._str_see_also(func_role) + for s in ("Notes", "References", "Examples"): + out += self._str_section(s) + out += self._str_index() + return "\n".join(out) + + +def dedent_lines(lines): + """Deindent a list of lines maximally""" + return textwrap.dedent("\n".join(lines)).split("\n") + + +class FunctionDoc(NumpyDocString): + def __init__(self, func, role="func", doc=None, config=None): + self._f = func + self._role = role # e.g. "func" or "meth" + + if doc is None: + if func is None: + raise ValueError("No function or docstring given") + doc = inspect.getdoc(func) or "" + if config is None: + config = {} + NumpyDocString.__init__(self, doc, config) + + def get_func(self): + func_name = getattr(self._f, "__name__", self.__class__.__name__) + if inspect.isclass(self._f): + func = getattr(self._f, "__call__", self._f.__init__) + else: + func = self._f + return func, func_name + + def __str__(self): + out = "" + + func, func_name = self.get_func() + + roles = {"func": "function", "meth": "method"} + + if self._role: + if self._role not in roles: + print(f"Warning: invalid role {self._role}") + out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n" + + out += super().__str__(func_role=self._role) + return out + + +class ObjDoc(NumpyDocString): + def __init__(self, obj, doc=None, config=None): + self._f = obj + if config is None: + config = {} + NumpyDocString.__init__(self, doc, config=config) + + +class ClassDoc(NumpyDocString): + extra_public_methods = ["__call__"] + + def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None): + if not inspect.isclass(cls) and cls is not None: + raise ValueError(f"Expected a class or None, but got {cls!r}") + self._cls = cls + + if "sphinx" in sys.modules: + from sphinx.ext.autodoc import ALL + else: + ALL = object() + + if config is None: + config = {} + self.show_inherited_members = config.get("show_inherited_class_members", True) + + if modulename and not modulename.endswith("."): + modulename += "." + self._mod = modulename + + if doc is None: + if cls is None: + raise ValueError("No class or documentation string given") + doc = pydoc.getdoc(cls) + + NumpyDocString.__init__(self, doc) + + _members = config.get("members", []) + if _members is ALL: + _members = None + _exclude = config.get("exclude-members", []) + + if config.get("show_class_members", True) and _exclude is not ALL: + + def splitlines_x(s): + if not s: + return [] + else: + return s.splitlines() + + for field, items in [ + ("Methods", self.methods), + ("Attributes", self.properties), + ]: + if not self[field]: + doc_list = [] + for name in sorted(items): + if name in _exclude or (_members and name not in _members): + continue + try: + doc_item = pydoc.getdoc(getattr(self._cls, name)) + doc_list.append(Parameter(name, "", splitlines_x(doc_item))) + except AttributeError: + pass # method doesn't exist + self[field] = doc_list + + @property + def methods(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + (not name.startswith("_") or name in self.extra_public_methods) + and isinstance(func, Callable) + and self._is_show_member(name) + ) + ] + + @property + def properties(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + not name.startswith("_") + and not self._should_skip_member(name, self._cls) + and ( + func is None + or isinstance(func, (property, cached_property)) + or inspect.isdatadescriptor(func) + ) + and self._is_show_member(name) + ) + ] + + @staticmethod + def _should_skip_member(name, klass): + return ( + # Namedtuples should skip everything in their ._fields as the + # docstrings for each of the members is: "Alias for field number X" + issubclass(klass, tuple) + and hasattr(klass, "_asdict") + and hasattr(klass, "_fields") + and name in klass._fields + ) + + def _is_show_member(self, name): + return ( + # show all class members + self.show_inherited_members + # or class member is not inherited + or name in self._cls.__dict__ + ) + + +def get_doc_object( + obj, + what=None, + doc=None, + config=None, + class_doc=ClassDoc, + func_doc=FunctionDoc, + obj_doc=ObjDoc, +): + if what is None: + if inspect.isclass(obj): + what = "class" + elif inspect.ismodule(obj): + what = "module" + elif isinstance(obj, Callable): + what = "function" + else: + what = "object" + if config is None: + config = {} + + if what == "class": + return class_doc(obj, func_doc=func_doc, doc=doc, config=config) + elif what in ("function", "method"): + return func_doc(obj, doc=doc, config=config) + else: + if doc is None: + doc = pydoc.getdoc(obj) + return obj_doc(obj, doc, config=config) \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py b/venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py new file mode 100644 index 0000000000000000000000000000000000000000..05efe86d31c137e7d780ebc438ec587df4e911dd --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py @@ -0,0 +1,357 @@ +# `_elementwise_iterative_method.py` includes tools for writing functions that +# - are vectorized to work elementwise on arrays, +# - implement non-trivial, iterative algorithms with a callback interface, and +# - return rich objects with iteration count, termination status, etc. +# +# Examples include: +# `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding, +# `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization, +# `scipy.optimize._differentiate._differentiate for numerical differentiation, +# `scipy.optimize._bracket._bracket_root for finding rootfinding brackets, +# `scipy.optimize._bracket._bracket_minimize for finding minimization brackets, +# `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature, +# `scipy.differentiate.derivative` for finite difference based differentiation. + +import math +import numpy as np +from ._util import _RichResult, _call_callback_maybe_halt +from ._array_api import array_namespace, xp_size + +_ESIGNERR = -1 +_ECONVERR = -2 +_EVALUEERR = -3 +_ECALLBACK = -4 +_EINPUTERR = -5 +_ECONVERGED = 0 +_EINPROGRESS = 1 + +def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None): + """Initialize abscissa, function, and args arrays for elementwise function + + Parameters + ---------- + func : callable + An elementwise function with signature + + 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``. + xs : tuple of arrays + Finite real abscissa arrays. Must be broadcastable. + args : tuple, optional + Additional positional arguments to be passed to `func`. + preserve_shape : bool, default:False + When ``preserve_shape=False`` (default), `func` may be passed + arguments of any shape; `_scalar_optimization_loop` is permitted + to reshape and compress arguments at will. When + ``preserve_shape=False``, arguments passed to `func` must have shape + `shape` or ``shape + (n,)``, where ``n`` is any integer. + xp : namespace + Namespace of array arguments in `xs`. + + Returns + ------- + xs, fs, args : tuple of arrays + Broadcasted, writeable, 1D abscissa and function value arrays (or + NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are + `xfat`; the dtype of the `args` are unchanged. + shape : tuple of ints + Original shape of broadcasted arrays. + xfat : NumPy dtype + Result dtype of abscissae, function values, and args determined using + `np.result_type`, except integer types are promoted to `np.float64`. + + Raises + ------ + ValueError + If the result dtype is not that of a real scalar + + Notes + ----- + Useful for initializing the input of SciPy functions that accept + an elementwise callable, abscissae, and arguments; e.g. + `scipy.optimize._chandrupatla`. + """ + nx = len(xs) + xp = array_namespace(*xs) if xp is None else xp + + # Try to preserve `dtype`, but we need to ensure that the arguments are at + # least floats before passing them into the function; integers can overflow + # and cause failure. + # There might be benefit to combining the `xs` into a single array and + # calling `func` once on the combined array. For now, keep them separate. + xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename + xat = xp.result_type(*[xa.dtype for xa in xas]) + xat = xp.asarray(1.).dtype if xp.isdtype(xat, "integral") else xat + xs, args = xas[:nx], xas[nx:] + xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented + fs = [xp.asarray(func(x, *args)) for x in xs] + shape = xs[0].shape + fshape = fs[0].shape + + if preserve_shape: + # bind original shape/func now to avoid late-binding gotcha + def func(x, *args, shape=shape, func=func, **kwargs): + i = (0,)*(len(fshape) - len(shape)) + return func(x[i], *args, **kwargs) + shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK + xs = [xp.broadcast_to(x, shape) for x in xs] + args = [xp.broadcast_to(arg, shape) for arg in args] + + message = ("The shape of the array returned by `func` must be the same as " + "the broadcasted shape of `x` and all other `args`.") + if preserve_shape is not None: # only in tanhsinh for now + message = f"When `preserve_shape=False`, {message.lower()}" + shapes_equal = [f.shape == shape for f in fs] + if not all(shapes_equal): # use Python all to reduce overhead + raise ValueError(message) + + # These algorithms tend to mix the dtypes of the abscissae and function + # values, so figure out what the result will be and convert them all to + # that type from the outset. + xfat = xp.result_type(*([f.dtype for f in fs] + [xat])) + if not complex_ok and not xp.isdtype(xfat, "real floating"): + raise ValueError("Abscissae and function output must be real numbers.") + xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs] + fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs] + + # To ensure that we can do indexing, we'll work with at least 1d arrays, + # but remember the appropriate shape of the output. + xs = [xp.reshape(x, (-1,)) for x in xs] + fs = [xp.reshape(f, (-1,)) for f in fs] + args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args] + return func, xs, fs, args, shape, xfat, xp + + +def _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, preserve_shape=False): + """Main loop of a vectorized scalar optimization algorithm + + Parameters + ---------- + work : _RichResult + All variables that need to be retained between iterations. Must + contain attributes `nit`, `nfev`, and `success`. All arrays are + subject to being "compressed" if `preserve_shape is False`; nest + arrays that should not be compressed inside another object (e.g. + `dict` or `_RichResult`). + callback : callable + User-specified callback function + shape : tuple of ints + The shape of all output arrays + maxiter : + Maximum number of iterations of the algorithm + func : callable + The user-specified callable that is being optimized or solved + args : tuple + Additional positional arguments to be passed to `func`. + dtype : NumPy dtype + The common dtype of all abscissae and function values + pre_func_eval : callable + A function that accepts `work` and returns `x`, the active elements + of `x` at which `func` will be evaluated. May modify attributes + of `work` with any algorithmic steps that need to happen + at the beginning of an iteration, before `func` is evaluated, + post_func_eval : callable + A function that accepts `x`, `func(x)`, and `work`. May modify + attributes of `work` with any algorithmic steps that need to happen + in the middle of an iteration, after `func` is evaluated but before + the termination check. + check_termination : callable + A function that accepts `work` and returns `stop`, a boolean array + indicating which of the active elements have met a termination + condition. + post_termination_check : callable + A function that accepts `work`. May modify `work` with any algorithmic + steps that need to happen after the termination check and before the + end of the iteration. + customize_result : callable + A function that accepts `res` and `shape` and returns `shape`. May + modify `res` (in-place) according to preferences (e.g. rearrange + elements between attributes) and modify `shape` if needed. + res_work_pairs : list of (str, str) + Identifies correspondence between attributes of `res` and attributes + of `work`; i.e., attributes of active elements of `work` will be + copied to the appropriate indices of `res` when appropriate. The order + determines the order in which _RichResult attributes will be + pretty-printed. + preserve_shape : bool, default: False + Whether to compress the attributes of `work` (to avoid unnecessary + computation on elements that have already converged). + + Returns + ------- + res : _RichResult + The final result object + + Notes + ----- + Besides providing structure, this framework provides several important + services for a vectorized optimization algorithm. + + - It handles common tasks involving iteration count, function evaluation + count, a user-specified callback, and associated termination conditions. + - It compresses the attributes of `work` to eliminate unnecessary + computation on elements that have already converged. + + """ + if xp is None: + raise NotImplementedError("Must provide xp.") + + cb_terminate = False + + # Initialize the result object and active element index array + n_elements = math.prod(shape) + active = xp.arange(n_elements) # in-progress element indices + res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs} + res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool) + res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32) + res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32) + res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32) + res = _RichResult(res_dict) + work.args = args + + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + + while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements: + x = pre_func_eval(work) + + if work.args and work.args[0].ndim != x.ndim: + # `x` always starts as 1D. If the SciPy function that uses + # _loop added dimensions to `x`, we need to + # add them to the elements of `args`. + args = [] + for arg in work.args: + n_new_dims = x.ndim - arg.ndim + new_shape = arg.shape + (1,)*n_new_dims + args.append(xp.reshape(arg, new_shape)) + work.args = args + + x_shape = x.shape + if preserve_shape: + x = xp.reshape(x, (shape + (-1,))) + f = func(x, *work.args) + f = xp.asarray(f, dtype=dtype) + if preserve_shape: + x = xp.reshape(x, x_shape) + f = xp.reshape(f, x_shape) + work.nfev += 1 if x.ndim == 1 else x.shape[-1] + + post_func_eval(x, f, work) + + work.nit += 1 + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + break + if xp_size(active) == 0: + break + + post_termination_check(work) + + work.status[:] = _ECALLBACK if cb_terminate else _ECONVERR + return _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + + +def _check_termination(work, res, res_work_pairs, active, check_termination, + preserve_shape, xp): + # Checks termination conditions, updates elements of `res` with + # corresponding elements of `work`, and compresses `work`. + + stop = check_termination(work) + + if xp.any(stop): + # update the active elements of the result object with the active + # elements for which a termination condition has been met + _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp) + + if preserve_shape: + stop = stop[active] + + proceed = ~stop + active = active[proceed] + + if not preserve_shape: + # compress the arrays to avoid unnecessary computation + for key, val in work.items(): + # Need to find a better way than these try/excepts + # Somehow need to keep compressible numerical args separate + if key == 'args': + continue + try: + work[key] = val[proceed] + except (IndexError, TypeError, KeyError): # not a compressible array + work[key] = val + work.args = [arg[proceed] for arg in work.args] + + return active + + +def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp): + # Update `active` indices of the arrays in result object `res` with the + # contents of the scalars and arrays in `update_dict`. When provided, + # `mask` is a boolean array applied both to the arrays in `update_dict` + # that are to be used and to the arrays in `res` that are to be updated. + update_dict = {key1: work[key2] for key1, key2 in res_work_pairs} + update_dict['success'] = work.status == 0 + + if mask is not None: + if preserve_shape: + active_mask = xp.zeros_like(mask) + active_mask[active] = 1 + active_mask = active_mask & mask + for key, val in update_dict.items(): + try: + res[key][active_mask] = val[active_mask] + except (IndexError, TypeError, KeyError): + res[key][active_mask] = val + else: + active_mask = active[mask] + for key, val in update_dict.items(): + try: + res[key][active_mask] = val[mask] + except (IndexError, TypeError, KeyError): + res[key][active_mask] = val + else: + for key, val in update_dict.items(): + if preserve_shape: + try: + val = val[active] + except (IndexError, TypeError, KeyError): + pass + res[key][active] = val + + +def _prepare_result(work, res, res_work_pairs, active, shape, customize_result, + preserve_shape, xp): + # Prepare the result object `res` by creating a copy, copying the latest + # data from work, running the provided result customization function, + # and reshaping the data to the original shapes. + res = res.copy() + _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp) + + shape = customize_result(res, shape) + + for key, val in res.items(): + # this looks like it won't work for xp != np if val is not numeric + temp = xp.reshape(val, shape) + res[key] = temp[()] if temp.ndim == 0 else temp + + res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs] + return _RichResult(**res) diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py b/venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py new file mode 100644 index 0000000000000000000000000000000000000000..506057b48b3f49244e1ed6cd755fad8ad43d8739 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py @@ -0,0 +1,145 @@ +from numpy import arange, newaxis, hstack, prod, array + + +def _central_diff_weights(Np, ndiv=1): + """ + Return weights for an Np-point central derivative. + + Assumes equally-spaced function points. + + If weights are in the vector w, then + derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx) + + Parameters + ---------- + Np : int + Number of points for the central derivative. + ndiv : int, optional + Number of divisions. Default is 1. + + Returns + ------- + w : ndarray + Weights for an Np-point central derivative. Its size is `Np`. + + Notes + ----- + Can be inaccurate for a large number of points. + + Examples + -------- + We can calculate a derivative value of a function. + + >>> def f(x): + ... return 2 * x**2 + 3 + >>> x = 3.0 # derivative point + >>> h = 0.1 # differential step + >>> Np = 3 # point number for central derivative + >>> weights = _central_diff_weights(Np) # weights for first derivative + >>> vals = [f(x + (i - Np/2) * h) for i in range(Np)] + >>> sum(w * v for (w, v) in zip(weights, vals))/h + 11.79999999999998 + + This value is close to the analytical solution: + f'(x) = 4x, so f'(3) = 12 + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Finite_difference + + """ + if Np < ndiv + 1: + raise ValueError( + "Number of points must be at least the derivative order + 1." + ) + if Np % 2 == 0: + raise ValueError("The number of points must be odd.") + from scipy import linalg + + ho = Np >> 1 + x = arange(-ho, ho + 1.0) + x = x[:, newaxis] + X = x**0.0 + for k in range(1, Np): + X = hstack([X, x**k]) + w = prod(arange(1, ndiv + 1), axis=0) * linalg.inv(X)[ndiv] + return w + + +def _derivative(func, x0, dx=1.0, n=1, args=(), order=3): + """ + Find the nth derivative of a function at a point. + + Given a function, use a central difference formula with spacing `dx` to + compute the nth derivative at `x0`. + + Parameters + ---------- + func : function + Input function. + x0 : float + The point at which the nth derivative is found. + dx : float, optional + Spacing. + n : int, optional + Order of the derivative. Default is 1. + args : tuple, optional + Arguments + order : int, optional + Number of points to use, must be odd. + + Notes + ----- + Decreasing the step size too small can result in round-off error. + + Examples + -------- + >>> def f(x): + ... return x**3 + x**2 + >>> _derivative(f, 1.0, dx=1e-6) + 4.9999999999217337 + + """ + if order < n + 1: + raise ValueError( + "'order' (the number of points used to compute the derivative), " + "must be at least the derivative order 'n' + 1." + ) + if order % 2 == 0: + raise ValueError( + "'order' (the number of points used to compute the derivative) " + "must be odd." + ) + # pre-computed for n=1 and 2 and low-order for speed. + if n == 1: + if order == 3: + weights = array([-1, 0, 1]) / 2.0 + elif order == 5: + weights = array([1, -8, 0, 8, -1]) / 12.0 + elif order == 7: + weights = array([-1, 9, -45, 0, 45, -9, 1]) / 60.0 + elif order == 9: + weights = array([3, -32, 168, -672, 0, 672, -168, 32, -3]) / 840.0 + else: + weights = _central_diff_weights(order, 1) + elif n == 2: + if order == 3: + weights = array([1, -2.0, 1]) + elif order == 5: + weights = array([-1, 16, -30, 16, -1]) / 12.0 + elif order == 7: + weights = array([2, -27, 270, -490, 270, -27, 2]) / 180.0 + elif order == 9: + weights = ( + array([-9, 128, -1008, 8064, -14350, 8064, -1008, 128, -9]) + / 5040.0 + ) + else: + weights = _central_diff_weights(order, 2) + else: + weights = _central_diff_weights(order, n) + val = 0.0 + ho = order >> 1 + for k in range(order): + val += weights[k] * func(x0 + (k - ho) * dx, *args) + return val / prod((dx,) * n, axis=0) diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3a443899bde3481ed6c1359eff4ef9696f6c8e4d Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py b/venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..854ae36228614f3eb8849e9f95abf0dd387b5d35 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py @@ -0,0 +1,105 @@ +""" +Module for testing automatic garbage collection of objects + +.. autosummary:: + :toctree: generated/ + + set_gc_state - enable or disable garbage collection + gc_state - context manager for given state of garbage collector + assert_deallocated - context manager to check for circular references on object + +""" +import weakref +import gc + +from contextlib import contextmanager +from platform import python_implementation + +__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated'] + + +IS_PYPY = python_implementation() == 'PyPy' + + +class ReferenceError(AssertionError): + pass + + +def set_gc_state(state): + """ Set status of garbage collector """ + if gc.isenabled() == state: + return + if state: + gc.enable() + else: + gc.disable() + + +@contextmanager +def gc_state(state): + """ Context manager to set state of garbage collector to `state` + + Parameters + ---------- + state : bool + True for gc enabled, False for disabled + + Examples + -------- + >>> with gc_state(False): + ... assert not gc.isenabled() + >>> with gc_state(True): + ... assert gc.isenabled() + """ + orig_state = gc.isenabled() + set_gc_state(state) + yield + set_gc_state(orig_state) + + +@contextmanager +def assert_deallocated(func, *args, **kwargs): + """Context manager to check that object is deallocated + + This is useful for checking that an object can be freed directly by + reference counting, without requiring gc to break reference cycles. + GC is disabled inside the context manager. + + This check is not available on PyPy. + + Parameters + ---------- + func : callable + Callable to create object to check + \\*args : sequence + positional arguments to `func` in order to create object to check + \\*\\*kwargs : dict + keyword arguments to `func` in order to create object to check + + Examples + -------- + >>> class C: pass + >>> with assert_deallocated(C) as c: + ... # do something + ... del c + + >>> class C: + ... def __init__(self): + ... self._circular = self # Make circular reference + >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL + ... # do something + ... del c + Traceback (most recent call last): + ... + ReferenceError: Remaining reference(s) to object + """ + if IS_PYPY: + raise RuntimeError("assert_deallocated is unavailable on PyPy") + + with gc_state(False): + obj = func(*args, **kwargs) + ref = weakref.ref(obj) + yield obj + del obj + if ref() is not None: + raise ReferenceError("Remaining reference(s) to object") diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py b/venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..d546e32a0349461a0aab76bfb4636ebf25227ca0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py @@ -0,0 +1,487 @@ +"""Utility to compare pep440 compatible version strings. + +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. +""" + +# Copyright (c) Donald Stufft and individual contributors. +# All rights reserved. + +# 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. + +# 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 collections +import itertools +import re + + +__all__ = [ + "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN", +] + + +# BEGIN packaging/_structures.py + + +class Infinity: + def __repr__(self): + return "Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return False + + def __le__(self, other): + return False + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return True + + def __ge__(self, other): + return True + + def __neg__(self): + return NegativeInfinity + + +Infinity = Infinity() + + +class NegativeInfinity: + def __repr__(self): + return "-Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return True + + def __le__(self, other): + return True + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return False + + def __ge__(self, other): + return False + + def __neg__(self): + return Infinity + + +# BEGIN packaging/version.py + + +NegativeInfinity = NegativeInfinity() + +_Version = collections.namedtuple( + "_Version", + ["epoch", "release", "dev", "pre", "post", "local"], +) + + +def parse(version): + """ + Parse the given version string and return either a :class:`Version` object + or a :class:`LegacyVersion` object depending on if the given version is + a valid PEP 440 version or a legacy version. + """ + try: + return Version(version) + except InvalidVersion: + return LegacyVersion(version) + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + + def __hash__(self): + return hash(self._key) + + def __lt__(self, other): + return self._compare(other, lambda s, o: s < o) + + def __le__(self, other): + return self._compare(other, lambda s, o: s <= o) + + def __eq__(self, other): + return self._compare(other, lambda s, o: s == o) + + def __ge__(self, other): + return self._compare(other, lambda s, o: s >= o) + + def __gt__(self, other): + return self._compare(other, lambda s, o: s > o) + + def __ne__(self, other): + return self._compare(other, lambda s, o: s != o) + + def _compare(self, other, method): + if not isinstance(other, _BaseVersion): + return NotImplemented + + return method(self._key, other._key) + + +class LegacyVersion(_BaseVersion): + + def __init__(self, version): + self._version = str(version) + self._key = _legacy_cmpkey(self._version) + + def __str__(self): + return self._version + + def __repr__(self): + return f"" + + @property + def public(self): + return self._version + + @property + def base_version(self): + return self._version + + @property + def local(self): + return None + + @property + def is_prerelease(self): + return False + + @property + def is_postrelease(self): + return False + + +_legacy_version_component_re = re.compile( + r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE, +) + +_legacy_version_replacement_map = { + "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", +} + + +def _parse_version_parts(s): + for part in _legacy_version_component_re.split(s): + part = _legacy_version_replacement_map.get(part, part) + + if not part or part == ".": + continue + + if part[:1] in "0123456789": + # pad for numeric comparison + yield part.zfill(8) + else: + yield "*" + part + + # ensure that alpha/beta/candidate are before final + yield "*final" + + +def _legacy_cmpkey(version): + # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch + # greater than or equal to 0. This will effectively put the LegacyVersion, + # which uses the defacto standard originally implemented by setuptools, + # as before all PEP 440 versions. + epoch = -1 + + # This scheme is taken from pkg_resources.parse_version setuptools prior to + # its adoption of the packaging library. + parts = [] + for part in _parse_version_parts(version.lower()): + if part.startswith("*"): + # remove "-" before a prerelease tag + if part < "*final": + while parts and parts[-1] == "*final-": + parts.pop() + + # remove trailing zeros from each series of numeric parts + while parts and parts[-1] == "00000000": + parts.pop() + + parts.append(part) + parts = tuple(parts) + + return epoch, parts + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(
+        r"^\s*" + VERSION_PATTERN + r"\s*$",
+        re.VERBOSE | re.IGNORECASE,
+    )
+
+    def __init__(self, version):
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(
+                match.group("pre_l"),
+                match.group("pre_n"),
+            ),
+            post=_parse_letter_version(
+                match.group("post_l"),
+                match.group("post_n1") or match.group("post_n2"),
+            ),
+            dev=_parse_letter_version(
+                match.group("dev_l"),
+                match.group("dev_n"),
+            ),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self):
+        return f""
+
+    def __str__(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        # Pre-release
+        if self._version.pre is not None:
+            parts.append("".join(str(x) for x in self._version.pre))
+
+        # Post-release
+        if self._version.post is not None:
+            parts.append(f".post{self._version.post[1]}")
+
+        # Development release
+        if self._version.dev is not None:
+            parts.append(f".dev{self._version.dev[1]}")
+
+        # Local version segment
+        if self._version.local is not None:
+            parts.append(
+                "+{}".format(".".join(str(x) for x in self._version.local))
+            )
+
+        return "".join(parts)
+
+    @property
+    def public(self):
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        return "".join(parts)
+
+    @property
+    def local(self):
+        version_string = str(self)
+        if "+" in version_string:
+            return version_string.split("+", 1)[1]
+
+    @property
+    def is_prerelease(self):
+        return bool(self._version.dev or self._version.pre)
+
+    @property
+    def is_postrelease(self):
+        return bool(self._version.post)
+
+
+def _parse_letter_version(letter, number):
+    if letter:
+        # We assume there is an implicit 0 in a pre-release if there is
+        # no numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower-case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume that if we are given a number but not given a letter,
+        # then this is using the implicit post release syntax (e.g., 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+
+_local_version_seperators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local):
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_seperators.split(local)
+        )
+
+
+def _cmpkey(epoch, release, pre, post, dev, local):
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non-zero, then take the rest,
+    # re-reverse it back into the correct order, and make it a tuple and use
+    # that for our sorting key.
+    release = tuple(
+        reversed(list(
+            itertools.dropwhile(
+                lambda x: x == 0,
+                reversed(release),
+            )
+        ))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre-segment, but we _only_ want to do this
+    # if there is no pre- or a post-segment. If we have one of those, then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        pre = -Infinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        pre = Infinity
+
+    # Versions without a post-segment should sort before those with one.
+    if post is None:
+        post = -Infinity
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        dev = Infinity
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        local = -Infinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alphanumeric segments sort before numeric segments
+        # - Alphanumeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        local = tuple(
+            (i, "") if isinstance(i, int) else (-Infinity, i)
+            for i in local
+        )
+
+    return epoch, release, pre, post, dev, local
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..3bd017197577d973e5c77c3c51ad966a015b890b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..34c0e024dcd5924c7287e6ce8105975c4d9ab7f5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..60dc2423372bf2fb24dece8ab51b1f9b7f26d7eb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py b/venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8da7e403dec5de5cb7d9a98d8c69a2c49e377c6a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
@@ -0,0 +1,369 @@
+"""
+Generic test utilities.
+
+"""
+
+import inspect
+import os
+import re
+import shutil
+import subprocess
+import sys
+import sysconfig
+import threading
+from importlib.util import module_from_spec, spec_from_file_location
+
+import numpy as np
+import scipy
+
+try:
+    # Need type: ignore[import-untyped] for mypy >= 1.6
+    import cython  # type: ignore[import-untyped]
+    from Cython.Compiler.Version import (  # type: ignore[import-untyped]
+        version as cython_version,
+    )
+except ImportError:
+    cython = None
+else:
+    from scipy._lib import _pep440
+    required_version = '3.0.8'
+    if _pep440.parse(cython_version) < _pep440.Version(required_version):
+        # too old or wrong cython, skip Cython API tests
+        cython = None
+
+
+__all__ = ['PytestTester', 'check_free_memory', '_TestPythranFunc', 'IS_MUSL']
+
+
+IS_MUSL = False
+# alternate way is
+# from packaging.tags import sys_tags
+#     _tags = list(sys_tags())
+#     if 'musllinux' in _tags[0].platform:
+_v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
+if 'musl' in _v:
+    IS_MUSL = True
+
+
+IS_EDITABLE = 'editable' in scipy.__path__[0]
+
+
+class FPUModeChangeWarning(RuntimeWarning):
+    """Warning about FPU mode change"""
+    pass
+
+
+class PytestTester:
+    """
+    Run tests for this namespace
+
+    ``scipy.test()`` runs tests for all of SciPy, with the default settings.
+    When used from a submodule (e.g., ``scipy.cluster.test()``, only the tests
+    for that namespace are run.
+
+    Parameters
+    ----------
+    label : {'fast', 'full'}, optional
+        Whether to run only the fast tests, or also those marked as slow.
+        Default is 'fast'.
+    verbose : int, optional
+        Test output verbosity. Default is 1.
+    extra_argv : list, optional
+        Arguments to pass through to Pytest.
+    doctests : bool, optional
+        Whether to run doctests or not. Default is False.
+    coverage : bool, optional
+        Whether to run tests with code coverage measurements enabled.
+        Default is False.
+    tests : list of str, optional
+        List of module names to run tests for. By default, uses the module
+        from which the ``test`` function is called.
+    parallel : int, optional
+        Run tests in parallel with pytest-xdist, if number given is larger than
+        1. Default is 1.
+
+    """
+    def __init__(self, module_name):
+        self.module_name = module_name
+
+    def __call__(self, label="fast", verbose=1, extra_argv=None, doctests=False,
+                 coverage=False, tests=None, parallel=None):
+        import pytest
+
+        module = sys.modules[self.module_name]
+        module_path = os.path.abspath(module.__path__[0])
+
+        pytest_args = ['--showlocals', '--tb=short']
+
+        if extra_argv:
+            pytest_args += list(extra_argv)
+
+        if verbose and int(verbose) > 1:
+            pytest_args += ["-" + "v"*(int(verbose)-1)]
+
+        if coverage:
+            pytest_args += ["--cov=" + module_path]
+
+        if label == "fast":
+            pytest_args += ["-m", "not slow"]
+        elif label != "full":
+            pytest_args += ["-m", label]
+
+        if tests is None:
+            tests = [self.module_name]
+
+        if parallel is not None and parallel > 1:
+            if _pytest_has_xdist():
+                pytest_args += ['-n', str(parallel)]
+            else:
+                import warnings
+                warnings.warn('Could not run tests in parallel because '
+                              'pytest-xdist plugin is not available.',
+                              stacklevel=2)
+
+        pytest_args += ['--pyargs'] + list(tests)
+
+        try:
+            code = pytest.main(pytest_args)
+        except SystemExit as exc:
+            code = exc.code
+
+        return (code == 0)
+
+
+class _TestPythranFunc:
+    '''
+    These are situations that can be tested in our pythran tests:
+    - A function with multiple array arguments and then
+      other positional and keyword arguments.
+    - A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
+    Note: list/tuple input is not yet tested!
+
+    `self.arguments`: A dictionary which key is the index of the argument,
+                      value is tuple(array value, all supported dtypes)
+    `self.partialfunc`: A function used to freeze some non-array argument
+                        that of no interests in the original function
+    '''
+    ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
+    ALL_FLOAT = [np.float32, np.float64]
+    ALL_COMPLEX = [np.complex64, np.complex128]
+
+    def setup_method(self):
+        self.arguments = {}
+        self.partialfunc = None
+        self.expected = None
+
+    def get_optional_args(self, func):
+        # get optional arguments with its default value,
+        # used for testing keywords
+        signature = inspect.signature(func)
+        optional_args = {}
+        for k, v in signature.parameters.items():
+            if v.default is not inspect.Parameter.empty:
+                optional_args[k] = v.default
+        return optional_args
+
+    def get_max_dtype_list_length(self):
+        # get the max supported dtypes list length in all arguments
+        max_len = 0
+        for arg_idx in self.arguments:
+            cur_len = len(self.arguments[arg_idx][1])
+            if cur_len > max_len:
+                max_len = cur_len
+        return max_len
+
+    def get_dtype(self, dtype_list, dtype_idx):
+        # get the dtype from dtype_list via index
+        # if the index is out of range, then return the last dtype
+        if dtype_idx > len(dtype_list)-1:
+            return dtype_list[-1]
+        else:
+            return dtype_list[dtype_idx]
+
+    def test_all_dtypes(self):
+        for type_idx in range(self.get_max_dtype_list_length()):
+            args_array = []
+            for arg_idx in self.arguments:
+                new_dtype = self.get_dtype(self.arguments[arg_idx][1],
+                                           type_idx)
+                args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
+            self.pythranfunc(*args_array)
+
+    def test_views(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(self.arguments[arg_idx][0][::-1][::-1])
+        self.pythranfunc(*args_array)
+
+    def test_strided(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(np.repeat(self.arguments[arg_idx][0],
+                                        2, axis=0)[::2])
+        self.pythranfunc(*args_array)
+
+
+def _pytest_has_xdist():
+    """
+    Check if the pytest-xdist plugin is installed, providing parallel tests
+    """
+    # Check xdist exists without importing, otherwise pytests emits warnings
+    from importlib.util import find_spec
+    return find_spec('xdist') is not None
+
+
+def check_free_memory(free_mb):
+    """
+    Check *free_mb* of memory is available, otherwise do pytest.skip
+    """
+    import pytest
+
+    try:
+        mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
+        msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
+            free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
+    except KeyError:
+        mem_free = _get_mem_available()
+        if mem_free is None:
+            pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
+                        "variable to free memory in MB to run the test.")
+        msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
+
+    if mem_free < free_mb * 1e6:
+        pytest.skip(msg)
+
+
+def _parse_size(size_str):
+    suffixes = {'': 1e6,
+                'b': 1.0,
+                'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
+                'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
+                'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
+    m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
+                 size_str,
+                 re.I)
+    if not m or m.group(2) not in suffixes:
+        raise ValueError("Invalid size string")
+
+    return float(m.group(1)) * suffixes[m.group(2)]
+
+
+def _get_mem_available():
+    """
+    Get information about memory available, not counting swap.
+    """
+    try:
+        import psutil
+        return psutil.virtual_memory().available
+    except (ImportError, AttributeError):
+        pass
+
+    if sys.platform.startswith('linux'):
+        info = {}
+        with open('/proc/meminfo') as f:
+            for line in f:
+                p = line.split()
+                info[p[0].strip(':').lower()] = float(p[1]) * 1e3
+
+        if 'memavailable' in info:
+            # Linux >= 3.14
+            return info['memavailable']
+        else:
+            return info['memfree'] + info['cached']
+
+    return None
+
+def _test_cython_extension(tmp_path, srcdir):
+    """
+    Helper function to test building and importing Cython modules that
+    make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
+    """
+    import pytest
+    try:
+        subprocess.check_call(["meson", "--version"])
+    except FileNotFoundError:
+        pytest.skip("No usable 'meson' found")
+
+    # Make safe for being called by multiple threads within one test
+    tmp_path = tmp_path / str(threading.get_ident())
+
+    # build the examples in a temporary directory
+    mod_name = os.path.split(srcdir)[1]
+    shutil.copytree(srcdir, tmp_path / mod_name)
+    build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
+    target_dir = build_dir / 'build'
+    os.makedirs(target_dir, exist_ok=True)
+
+    # Ensure we use the correct Python interpreter even when `meson` is
+    # installed in a different Python environment (see numpy#24956)
+    native_file = str(build_dir / 'interpreter-native-file.ini')
+    with open(native_file, 'w') as f:
+        f.write("[binaries]\n")
+        f.write(f"python = '{sys.executable}'")
+
+    if sys.platform == "win32":
+        subprocess.check_call(["meson", "setup",
+                               "--buildtype=release",
+                               "--native-file", native_file,
+                               "--vsenv", str(build_dir)],
+                              cwd=target_dir,
+                              )
+    else:
+        subprocess.check_call(["meson", "setup",
+                               "--native-file", native_file, str(build_dir)],
+                              cwd=target_dir
+                              )
+    subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
+
+    # import without adding the directory to sys.path
+    suffix = sysconfig.get_config_var('EXT_SUFFIX')
+
+    def load(modname):
+        so = (target_dir / modname).with_suffix(suffix)
+        spec = spec_from_file_location(modname, so)
+        mod = module_from_spec(spec)
+        spec.loader.exec_module(mod)
+        return mod
+
+    # test that the module can be imported
+    return load("extending"), load("extending_cpp")
+
+
+def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
+    """
+    Run a given function concurrently across a given number of threads.
+
+    This is equivalent to using a ThreadPoolExecutor, but using the threading
+    primitives instead. This function ensures that the closure passed by
+    parameter gets called concurrently by setting up a barrier before it gets
+    called before any of the threads.
+
+    Arguments
+    ---------
+    n_workers: int
+        Number of concurrent threads to spawn.
+    fn: callable
+        Function closure to execute concurrently. Its first argument will
+        be the thread id.
+    *args: tuple
+        Variable number of positional arguments to pass to the function.
+    **kwargs: dict
+        Keyword arguments to pass to the function.
+    """
+    barrier = threading.Barrier(n_workers)
+
+    def closure(i, *args, **kwargs):
+        barrier.wait()
+        fn(i, *args, **kwargs)
+
+    workers = []
+    for i in range(0, n_workers):
+        workers.append(threading.Thread(
+            target=closure,
+            args=(i,) + args, kwargs=kwargs))
+
+    for worker in workers:
+        worker.start()
+
+    for worker in workers:
+        worker.join()
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py b/venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..530339ec7075dafdb81e9fa0ff5447952af77497
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py
@@ -0,0 +1,58 @@
+import threading
+
+import scipy._lib.decorator
+
+
+__all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant']
+
+
+class ReentrancyError(RuntimeError):
+    pass
+
+
+class ReentrancyLock:
+    """
+    Threading lock that raises an exception for reentrant calls.
+
+    Calls from different threads are serialized, and nested calls from the
+    same thread result to an error.
+
+    The object can be used as a context manager or to decorate functions
+    via the decorate() method.
+
+    """
+
+    def __init__(self, err_msg):
+        self._rlock = threading.RLock()
+        self._entered = False
+        self._err_msg = err_msg
+
+    def __enter__(self):
+        self._rlock.acquire()
+        if self._entered:
+            self._rlock.release()
+            raise ReentrancyError(self._err_msg)
+        self._entered = True
+
+    def __exit__(self, type, value, traceback):
+        self._entered = False
+        self._rlock.release()
+
+    def decorate(self, func):
+        def caller(func, *a, **kw):
+            with self:
+                return func(*a, **kw)
+        return scipy._lib.decorator.decorate(func, caller)
+
+
+def non_reentrant(err_msg=None):
+    """
+    Decorate a function with a threading lock and prevent reentrant calls.
+    """
+    def decorator(func):
+        msg = err_msg
+        if msg is None:
+            msg = f"{func.__name__} is not re-entrant"
+        lock = ReentrancyLock(msg)
+        return lock.decorate(func)
+    return decorator
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py b/venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f9fd546a9d2ae3e9a20c0684f79eb0b3d61ee92
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py
@@ -0,0 +1,86 @@
+''' Contexts for *with* statement providing temporary directories
+'''
+import os
+from contextlib import contextmanager
+from shutil import rmtree
+from tempfile import mkdtemp
+
+
+@contextmanager
+def tempdir():
+    """Create and return a temporary directory. This has the same
+    behavior as mkdtemp but can be used as a context manager.
+
+    Upon exiting the context, the directory and everything contained
+    in it are removed.
+
+    Examples
+    --------
+    >>> import os
+    >>> with tempdir() as tmpdir:
+    ...     fname = os.path.join(tmpdir, 'example_file.txt')
+    ...     with open(fname, 'wt') as fobj:
+    ...         _ = fobj.write('a string\\n')
+    >>> os.path.exists(tmpdir)
+    False
+    """
+    d = mkdtemp()
+    yield d
+    rmtree(d)
+
+
+@contextmanager
+def in_tempdir():
+    ''' Create, return, and change directory to a temporary directory
+
+    Examples
+    --------
+    >>> import os
+    >>> my_cwd = os.getcwd()
+    >>> with in_tempdir() as tmpdir:
+    ...     _ = open('test.txt', 'wt').write('some text')
+    ...     assert os.path.isfile('test.txt')
+    ...     assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
+    >>> os.path.exists(tmpdir)
+    False
+    >>> os.getcwd() == my_cwd
+    True
+    '''
+    pwd = os.getcwd()
+    d = mkdtemp()
+    os.chdir(d)
+    yield d
+    os.chdir(pwd)
+    rmtree(d)
+
+
+@contextmanager
+def in_dir(dir=None):
+    """ Change directory to given directory for duration of ``with`` block
+
+    Useful when you want to use `in_tempdir` for the final test, but
+    you are still debugging. For example, you may want to do this in the end:
+
+    >>> with in_tempdir() as tmpdir:
+    ...     # do something complicated which might break
+    ...     pass
+
+    But, indeed, the complicated thing does break, and meanwhile, the
+    ``in_tempdir`` context manager wiped out the directory with the
+    temporary files that you wanted for debugging. So, while debugging, you
+    replace with something like:
+
+    >>> with in_dir() as tmpdir: # Use working directory by default
+    ...     # do something complicated which might break
+    ...     pass
+
+    You can then look at the temporary file outputs to debug what is happening,
+    fix, and finally replace ``in_dir`` with ``in_tempdir`` again.
+    """
+    cwd = os.getcwd()
+    if dir is None:
+        yield cwd
+        return
+    os.chdir(dir)
+    yield dir
+    os.chdir(cwd)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5f2b90a026aaecbdc090b3d3234954ab29fce8ae
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2018, Quansight-Labs
+All rights reserved.
+
+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.
+
+* Neither the name of the copyright holder nor the names of its
+  contributors 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.
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91afdcedb180599a41758cdd8c03416cf6c20d76
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py
@@ -0,0 +1,116 @@
+"""
+.. note:
+    If you are looking for overrides for NumPy-specific methods, see the
+    documentation for :obj:`unumpy`. This page explains how to write
+    back-ends and multimethods.
+
+``uarray`` is built around a back-end protocol, and overridable multimethods.
+It is necessary to define multimethods for back-ends to be able to override them.
+See the documentation of :obj:`generate_multimethod` on how to write multimethods.
+
+
+
+Let's start with the simplest:
+
+``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
+separated string consisting of the modules you extend plus the submodule. For
+example, if a submodule ``module2.submodule`` extends ``module1``
+(i.e., it exposes dispatchables marked as types available in ``module1``),
+then the domain string should be ``"module1.module2.submodule"``.
+
+
+For the purpose of this demonstration, we'll be creating an object and setting
+its attributes directly. However, note that you can use a module or your own type
+as a backend as well.
+
+>>> class Backend: pass
+>>> be = Backend()
+>>> be.__ua_domain__ = "ua_examples"
+
+It might be useful at this point to sidetrack to the documentation of
+:obj:`generate_multimethod` to find out how to generate a multimethod
+overridable by :obj:`uarray`. Needless to say, writing a backend and
+creating multimethods are mostly orthogonal activities, and knowing
+one doesn't necessarily require knowledge of the other, although it
+is certainly helpful. We expect core API designers/specifiers to write the
+multimethods, and implementors to override them. But, as is often the case,
+similar people write both.
+
+Without further ado, here's an example multimethod:
+
+>>> import uarray as ua
+>>> from uarray import Dispatchable
+>>> def override_me(a, b):
+...   return Dispatchable(a, int),
+>>> def override_replacer(args, kwargs, dispatchables):
+...     return (dispatchables[0], args[1]), {}
+>>> overridden_me = ua.generate_multimethod(
+...     override_me, override_replacer, "ua_examples"
+... )
+
+Next comes the part about overriding the multimethod. This requires
+the ``__ua_function__`` protocol, and the ``__ua_convert__``
+protocol. The ``__ua_function__`` protocol has the signature
+``(method, args, kwargs)`` where ``method`` is the passed
+multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
+is the list of converted dispatchables passed in.
+
+>>> def __ua_function__(method, args, kwargs):
+...     return method.__name__, args, kwargs
+>>> be.__ua_function__ = __ua_function__
+
+The other protocol of interest is the ``__ua_convert__`` protocol. It has the
+signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
+between the formats should ideally be an ``O(1)`` operation, but it means that
+no memory copying should be involved, only views of the existing data.
+
+>>> def __ua_convert__(dispatchables, coerce):
+...     for d in dispatchables:
+...         if d.type is int:
+...             if coerce and d.coercible:
+...                 yield str(d.value)
+...             else:
+...                 yield d.value
+>>> be.__ua_convert__ = __ua_convert__
+
+Now that we have defined the backend, the next thing to do is to call the multimethod.
+
+>>> with ua.set_backend(be):
+...      overridden_me(1, "2")
+('override_me', (1, '2'), {})
+
+Note that the marked type has no effect on the actual type of the passed object.
+We can also coerce the type of the input.
+
+>>> with ua.set_backend(be, coerce=True):
+...     overridden_me(1, "2")
+...     overridden_me(1.0, "2")
+('override_me', ('1', '2'), {})
+('override_me', ('1.0', '2'), {})
+
+Another feature is that if you remove ``__ua_convert__``, the arguments are not
+converted at all and it's up to the backend to handle that.
+
+>>> del be.__ua_convert__
+>>> with ua.set_backend(be):
+...     overridden_me(1, "2")
+('override_me', (1, '2'), {})
+
+You also have the option to return ``NotImplemented``, in which case processing moves on
+to the next back-end, which in this case, doesn't exist. The same applies to
+``__ua_convert__``.
+
+>>> be.__ua_function__ = lambda *a, **kw: NotImplemented
+>>> with ua.set_backend(be):
+...     overridden_me(1, "2")
+Traceback (most recent call last):
+    ...
+uarray.BackendNotImplementedError: ...
+
+The last possibility is if we don't have ``__ua_convert__``, in which case the job is
+left up to ``__ua_function__``, but putting things back into arrays after conversion
+will not be possible.
+"""
+
+from ._backend import *
+__version__ = '0.8.8.dev0+aa94c5a4.scipy'
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe25db65aa77c4db16617112b4c7bb2e7e15eb0b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..461c501beb5661ac1cd4d4642df7c63e93d05da7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ea71965761ca6916485828ee23d3402bfb1b7d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py
@@ -0,0 +1,707 @@
+import typing
+import types
+import inspect
+import functools
+from . import _uarray
+import copyreg
+import pickle
+import contextlib
+import threading
+
+from ._uarray import (  # type: ignore
+    BackendNotImplementedError,
+    _Function,
+    _SkipBackendContext,
+    _SetBackendContext,
+    _BackendState,
+)
+
+__all__ = [
+    "set_backend",
+    "set_global_backend",
+    "skip_backend",
+    "register_backend",
+    "determine_backend",
+    "determine_backend_multi",
+    "clear_backends",
+    "create_multimethod",
+    "generate_multimethod",
+    "_Function",
+    "BackendNotImplementedError",
+    "Dispatchable",
+    "wrap_single_convertor",
+    "wrap_single_convertor_instance",
+    "all_of_type",
+    "mark_as",
+    "set_state",
+    "get_state",
+    "reset_state",
+    "_BackendState",
+    "_SkipBackendContext",
+    "_SetBackendContext",
+]
+
+ArgumentExtractorType = typing.Callable[..., tuple["Dispatchable", ...]]
+ArgumentReplacerType = typing.Callable[
+    [tuple, dict, tuple], tuple[tuple, dict]
+]
+
+def unpickle_function(mod_name, qname, self_):
+    import importlib
+
+    try:
+        module = importlib.import_module(mod_name)
+        qname = qname.split(".")
+        func = module
+        for q in qname:
+            func = getattr(func, q)
+
+        if self_ is not None:
+            func = types.MethodType(func, self_)
+
+        return func
+    except (ImportError, AttributeError) as e:
+        from pickle import UnpicklingError
+
+        raise UnpicklingError from e
+
+
+def pickle_function(func):
+    mod_name = getattr(func, "__module__", None)
+    qname = getattr(func, "__qualname__", None)
+    self_ = getattr(func, "__self__", None)
+
+    try:
+        test = unpickle_function(mod_name, qname, self_)
+    except pickle.UnpicklingError:
+        test = None
+
+    if test is not func:
+        raise pickle.PicklingError(
+            f"Can't pickle {func}: it's not the same object as {test}"
+        )
+
+    return unpickle_function, (mod_name, qname, self_)
+
+
+def pickle_state(state):
+    return _uarray._BackendState._unpickle, state._pickle()
+
+
+def pickle_set_backend_context(ctx):
+    return _SetBackendContext, ctx._pickle()
+
+
+def pickle_skip_backend_context(ctx):
+    return _SkipBackendContext, ctx._pickle()
+
+
+copyreg.pickle(_Function, pickle_function)
+copyreg.pickle(_uarray._BackendState, pickle_state)
+copyreg.pickle(_SetBackendContext, pickle_set_backend_context)
+copyreg.pickle(_SkipBackendContext, pickle_skip_backend_context)
+
+
+def get_state():
+    """
+    Returns an opaque object containing the current state of all the backends.
+
+    Can be used for synchronization between threads/processes.
+
+    See Also
+    --------
+    set_state
+        Sets the state returned by this function.
+    """
+    return _uarray.get_state()
+
+
+@contextlib.contextmanager
+def reset_state():
+    """
+    Returns a context manager that resets all state once exited.
+
+    See Also
+    --------
+    set_state
+        Context manager that sets the backend state.
+    get_state
+        Gets a state to be set by this context manager.
+    """
+    with set_state(get_state()):
+        yield
+
+
+@contextlib.contextmanager
+def set_state(state):
+    """
+    A context manager that sets the state of the backends to one returned by :obj:`get_state`.
+
+    See Also
+    --------
+    get_state
+        Gets a state to be set by this context manager.
+    """  # noqa: E501
+    old_state = get_state()
+    _uarray.set_state(state)
+    try:
+        yield
+    finally:
+        _uarray.set_state(old_state, True)
+
+
+def create_multimethod(*args, **kwargs):
+    """
+    Creates a decorator for generating multimethods.
+
+    This function creates a decorator that can be used with an argument
+    extractor in order to generate a multimethod. Other than for the
+    argument extractor, all arguments are passed on to
+    :obj:`generate_multimethod`.
+
+    See Also
+    --------
+    generate_multimethod
+        Generates a multimethod.
+    """
+
+    def wrapper(a):
+        return generate_multimethod(a, *args, **kwargs)
+
+    return wrapper
+
+
+def generate_multimethod(
+    argument_extractor: ArgumentExtractorType,
+    argument_replacer: ArgumentReplacerType,
+    domain: str,
+    default: typing.Callable | None = None,
+):
+    """
+    Generates a multimethod.
+
+    Parameters
+    ----------
+    argument_extractor : ArgumentExtractorType
+        A callable which extracts the dispatchable arguments. Extracted arguments
+        should be marked by the :obj:`Dispatchable` class. It has the same signature
+        as the desired multimethod.
+    argument_replacer : ArgumentReplacerType
+        A callable with the signature (args, kwargs, dispatchables), which should also
+        return an (args, kwargs) pair with the dispatchables replaced inside the
+        args/kwargs.
+    domain : str
+        A string value indicating the domain of this multimethod.
+    default: Optional[Callable], optional
+        The default implementation of this multimethod, where ``None`` (the default)
+        specifies there is no default implementation.
+
+    Examples
+    --------
+    In this example, ``a`` is to be dispatched over, so we return it, while marking it
+    as an ``int``.
+    The trailing comma is needed because the args have to be returned as an iterable.
+
+    >>> def override_me(a, b):
+    ...   return Dispatchable(a, int),
+
+    Next, we define the argument replacer that replaces the dispatchables inside
+    args/kwargs with the supplied ones.
+
+    >>> def override_replacer(args, kwargs, dispatchables):
+    ...     return (dispatchables[0], args[1]), {}
+
+    Next, we define the multimethod.
+
+    >>> overridden_me = generate_multimethod(
+    ...     override_me, override_replacer, "ua_examples"
+    ... )
+
+    Notice that there's no default implementation, unless you supply one.
+
+    >>> overridden_me(1, "a")
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    >>> overridden_me2 = generate_multimethod(
+    ...     override_me, override_replacer, "ua_examples", default=lambda x, y: (x, y)
+    ... )
+    >>> overridden_me2(1, "a")
+    (1, 'a')
+
+    See Also
+    --------
+    uarray
+        See the module documentation for how to override the method by creating
+        backends.
+    """
+    kw_defaults, arg_defaults, opts = get_defaults(argument_extractor)
+    ua_func = _Function(
+        argument_extractor,
+        argument_replacer,
+        domain,
+        arg_defaults,
+        kw_defaults,
+        default,
+    )
+
+    return functools.update_wrapper(ua_func, argument_extractor)
+
+
+def set_backend(backend, coerce=False, only=False):
+    """
+    A context manager that sets the preferred backend.
+
+    Parameters
+    ----------
+    backend
+        The backend to set.
+    coerce
+        Whether or not to coerce to a specific backend's types. Implies ``only``.
+    only
+        Whether or not this should be the last backend to try.
+
+    See Also
+    --------
+    skip_backend: A context manager that allows skipping of backends.
+    set_global_backend: Set a single, global backend for a domain.
+    """
+    tid = threading.get_native_id()
+    try:
+        return backend.__ua_cache__[tid, "set", coerce, only]
+    except AttributeError:
+        backend.__ua_cache__ = {}
+    except KeyError:
+        pass
+
+    ctx = _SetBackendContext(backend, coerce, only)
+    backend.__ua_cache__[tid, "set", coerce, only] = ctx
+    return ctx
+
+
+def skip_backend(backend):
+    """
+    A context manager that allows one to skip a given backend from processing
+    entirely. This allows one to use another backend's code in a library that
+    is also a consumer of the same backend.
+
+    Parameters
+    ----------
+    backend
+        The backend to skip.
+
+    See Also
+    --------
+    set_backend: A context manager that allows setting of backends.
+    set_global_backend: Set a single, global backend for a domain.
+    """
+    tid = threading.get_native_id()
+    try:
+        return backend.__ua_cache__[tid, "skip"]
+    except AttributeError:
+        backend.__ua_cache__ = {}
+    except KeyError:
+        pass
+
+    ctx = _SkipBackendContext(backend)
+    backend.__ua_cache__[tid, "skip"] = ctx
+    return ctx
+
+
+def get_defaults(f):
+    sig = inspect.signature(f)
+    kw_defaults = {}
+    arg_defaults = []
+    opts = set()
+    for k, v in sig.parameters.items():
+        if v.default is not inspect.Parameter.empty:
+            kw_defaults[k] = v.default
+        if v.kind in (
+            inspect.Parameter.POSITIONAL_ONLY,
+            inspect.Parameter.POSITIONAL_OR_KEYWORD,
+        ):
+            arg_defaults.append(v.default)
+        opts.add(k)
+
+    return kw_defaults, tuple(arg_defaults), opts
+
+
+def set_global_backend(backend, coerce=False, only=False, *, try_last=False):
+    """
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Note that this method is not thread-safe.
+
+    .. warning::
+        We caution library authors against using this function in
+        their code. We do *not* support this use-case. This function
+        is meant to be used only by users themselves, or by a reference
+        implementation, if one exists.
+
+    Parameters
+    ----------
+    backend
+        The backend to register.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    See Also
+    --------
+    set_backend: A context manager that allows setting of backends.
+    skip_backend: A context manager that allows skipping of backends.
+    """
+    _uarray.set_global_backend(backend, coerce, only, try_last)
+
+
+def register_backend(backend):
+    """
+    This utility method sets registers backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend.
+
+    Note that this method is not thread-safe.
+
+    Parameters
+    ----------
+    backend
+        The backend to register.
+    """
+    _uarray.register_backend(backend)
+
+
+def clear_backends(domain, registered=True, globals=False):
+    """
+    This utility method clears registered backends.
+
+    .. warning::
+        We caution library authors against using this function in
+        their code. We do *not* support this use-case. This function
+        is meant to be used only by users themselves.
+
+    .. warning::
+        Do NOT use this method inside a multimethod call, or the
+        program is likely to crash.
+
+    Parameters
+    ----------
+    domain : Optional[str]
+        The domain for which to de-register backends. ``None`` means
+        de-register for all domains.
+    registered : bool
+        Whether or not to clear registered backends. See :obj:`register_backend`.
+    globals : bool
+        Whether or not to clear global backends. See :obj:`set_global_backend`.
+
+    See Also
+    --------
+    register_backend : Register a backend globally.
+    set_global_backend : Set a global backend.
+    """
+    _uarray.clear_backends(domain, registered, globals)
+
+
+class Dispatchable:
+    """
+    A utility class which marks an argument with a specific dispatch type.
+
+
+    Attributes
+    ----------
+    value
+        The value of the Dispatchable.
+
+    type
+        The type of the Dispatchable.
+
+    Examples
+    --------
+    >>> x = Dispatchable(1, str)
+    >>> x
+    , value=1>
+
+    See Also
+    --------
+    all_of_type
+        Marks all unmarked parameters of a function.
+
+    mark_as
+        Allows one to create a utility function to mark as a given type.
+    """
+
+    def __init__(self, value, dispatch_type, coercible=True):
+        self.value = value
+        self.type = dispatch_type
+        self.coercible = coercible
+
+    def __getitem__(self, index):
+        return (self.type, self.value)[index]
+
+    def __str__(self):
+        return f"<{type(self).__name__}: type={self.type!r}, value={self.value!r}>"
+
+    __repr__ = __str__
+
+
+def mark_as(dispatch_type):
+    """
+    Creates a utility function to mark something as a specific type.
+
+    Examples
+    --------
+    >>> mark_int = mark_as(int)
+    >>> mark_int(1)
+    , value=1>
+    """
+    return functools.partial(Dispatchable, dispatch_type=dispatch_type)
+
+
+def all_of_type(arg_type):
+    """
+    Marks all unmarked arguments as a given type.
+
+    Examples
+    --------
+    >>> @all_of_type(str)
+    ... def f(a, b):
+    ...     return a, Dispatchable(b, int)
+    >>> f('a', 1)
+    (, value='a'>,
+     , value=1>)
+    """
+
+    def outer(func):
+        @functools.wraps(func)
+        def inner(*args, **kwargs):
+            extracted_args = func(*args, **kwargs)
+            return tuple(
+                Dispatchable(arg, arg_type)
+                if not isinstance(arg, Dispatchable)
+                else arg
+                for arg in extracted_args
+            )
+
+        return inner
+
+    return outer
+
+
+def wrap_single_convertor(convert_single):
+    """
+    Wraps a ``__ua_convert__`` defined for a single element to all elements.
+    If any of them return ``NotImplemented``, the operation is assumed to be
+    undefined.
+
+    Accepts a signature of (value, type, coerce).
+    """
+
+    @functools.wraps(convert_single)
+    def __ua_convert__(dispatchables, coerce):
+        converted = []
+        for d in dispatchables:
+            c = convert_single(d.value, d.type, coerce and d.coercible)
+
+            if c is NotImplemented:
+                return NotImplemented
+
+            converted.append(c)
+
+        return converted
+
+    return __ua_convert__
+
+
+def wrap_single_convertor_instance(convert_single):
+    """
+    Wraps a ``__ua_convert__`` defined for a single element to all elements.
+    If any of them return ``NotImplemented``, the operation is assumed to be
+    undefined.
+
+    Accepts a signature of (value, type, coerce).
+    """
+
+    @functools.wraps(convert_single)
+    def __ua_convert__(self, dispatchables, coerce):
+        converted = []
+        for d in dispatchables:
+            c = convert_single(self, d.value, d.type, coerce and d.coercible)
+
+            if c is NotImplemented:
+                return NotImplemented
+
+            converted.append(c)
+
+        return converted
+
+    return __ua_convert__
+
+
+def determine_backend(value, dispatch_type, *, domain, only=True, coerce=False):
+    """Set the backend to the first active backend that supports ``value``
+
+    This is useful for functions that call multimethods without any dispatchable
+    arguments. You can use :func:`determine_backend` to ensure the same backend
+    is used everywhere in a block of multimethod calls.
+
+    Parameters
+    ----------
+    value
+        The value being tested
+    dispatch_type
+        The dispatch type associated with ``value``, aka
+        ":ref:`marking `".
+    domain: string
+        The domain to query for backends and set.
+    coerce: bool
+        Whether or not to allow coercion to the backend's types. Implies ``only``.
+    only: bool
+        Whether or not this should be the last backend to try.
+
+    See Also
+    --------
+    set_backend: For when you know which backend to set
+
+    Notes
+    -----
+
+    Support is determined by the ``__ua_convert__`` protocol. Backends not
+    supporting the type must return ``NotImplemented`` from their
+    ``__ua_convert__`` if they don't support input of that type.
+
+    Examples
+    --------
+
+    Suppose we have two backends ``BackendA`` and ``BackendB`` each supporting
+    different types, ``TypeA`` and ``TypeB``. Neither supporting the other type:
+
+    >>> with ua.set_backend(ex.BackendA):
+    ...     ex.call_multimethod(ex.TypeB(), ex.TypeB())
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    Now consider a multimethod that creates a new object of ``TypeA``, or
+    ``TypeB`` depending on the active backend.
+
+    >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, ex.TypeA())
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    ``res`` is an object of ``TypeB`` because ``BackendB`` is set in the
+    innermost with statement. So, ``call_multimethod`` fails since the types
+    don't match.
+
+    Instead, we need to first find a backend suitable for all of our objects.
+
+    >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
+    ...     x = ex.TypeA()
+    ...     with ua.determine_backend(x, "mark", domain="ua_examples"):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, x)
+    TypeA
+
+    """
+    dispatchables = (Dispatchable(value, dispatch_type, coerce),)
+    backend = _uarray.determine_backend(domain, dispatchables, coerce)
+
+    return set_backend(backend, coerce=coerce, only=only)
+
+
+def determine_backend_multi(
+    dispatchables, *, domain, only=True, coerce=False, **kwargs
+):
+    """Set a backend supporting all ``dispatchables``
+
+    This is useful for functions that call multimethods without any dispatchable
+    arguments. You can use :func:`determine_backend_multi` to ensure the same
+    backend is used everywhere in a block of multimethod calls involving
+    multiple arrays.
+
+    Parameters
+    ----------
+    dispatchables: Sequence[Union[uarray.Dispatchable, Any]]
+        The dispatchables that must be supported
+    domain: string
+        The domain to query for backends and set.
+    coerce: bool
+        Whether or not to allow coercion to the backend's types. Implies ``only``.
+    only: bool
+        Whether or not this should be the last backend to try.
+    dispatch_type: Optional[Any]
+        The default dispatch type associated with ``dispatchables``, aka
+        ":ref:`marking `".
+
+    See Also
+    --------
+    determine_backend: For a single dispatch value
+    set_backend: For when you know which backend to set
+
+    Notes
+    -----
+
+    Support is determined by the ``__ua_convert__`` protocol. Backends not
+    supporting the type must return ``NotImplemented`` from their
+    ``__ua_convert__`` if they don't support input of that type.
+
+    Examples
+    --------
+
+    :func:`determine_backend` allows the backend to be set from a single
+    object. :func:`determine_backend_multi` allows multiple objects to be
+    checked simultaneously for support in the backend. Suppose we have a
+    ``BackendAB`` which supports ``TypeA`` and ``TypeB`` in the same call,
+    and a ``BackendBC`` that doesn't support ``TypeA``.
+
+    >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
+    ...     a, b = ex.TypeA(), ex.TypeB()
+    ...     with ua.determine_backend_multi(
+    ...         [ua.Dispatchable(a, "mark"), ua.Dispatchable(b, "mark")],
+    ...         domain="ua_examples"
+    ...     ):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, a, b)
+    TypeA
+
+    This won't call ``BackendBC`` because it doesn't support ``TypeA``.
+
+    We can also use leave out the ``ua.Dispatchable`` if we specify the
+    default ``dispatch_type`` for the ``dispatchables`` argument.
+
+    >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
+    ...     a, b = ex.TypeA(), ex.TypeB()
+    ...     with ua.determine_backend_multi(
+    ...         [a, b], dispatch_type="mark", domain="ua_examples"
+    ...     ):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, a, b)
+    TypeA
+
+    """
+    if "dispatch_type" in kwargs:
+        disp_type = kwargs.pop("dispatch_type")
+        dispatchables = tuple(
+            d if isinstance(d, Dispatchable) else Dispatchable(d, disp_type)
+            for d in dispatchables
+        )
+    else:
+        dispatchables = tuple(dispatchables)
+        if not all(isinstance(d, Dispatchable) for d in dispatchables):
+            raise TypeError("dispatchables must be instances of uarray.Dispatchable")
+
+    if len(kwargs) != 0:
+        raise TypeError(f"Received unexpected keyword arguments: {kwargs}")
+
+    backend = _uarray.determine_backend(domain, dispatchables, coerce)
+
+    return set_backend(backend, coerce=coerce, only=only)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/_util.py b/venv/lib/python3.10/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d16072007395221fdf7a1f5352fd2838fd7a6ec
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/_util.py
@@ -0,0 +1,1179 @@
+import re
+from contextlib import contextmanager
+import functools
+import operator
+import warnings
+import numbers
+from collections import namedtuple
+import inspect
+import math
+from typing import TypeAlias, TypeVar
+
+import numpy as np
+from scipy._lib._array_api import array_namespace, is_numpy, xp_size
+from scipy._lib._docscrape import FunctionDoc, Parameter
+
+
+AxisError: type[Exception]
+ComplexWarning: type[Warning]
+VisibleDeprecationWarning: type[Warning]
+
+if np.lib.NumpyVersion(np.__version__) >= '1.25.0':
+    from numpy.exceptions import (
+        AxisError, ComplexWarning, VisibleDeprecationWarning,
+        DTypePromotionError
+    )
+else:
+    from numpy import (  # type: ignore[attr-defined, no-redef]
+        AxisError, ComplexWarning, VisibleDeprecationWarning  # noqa: F401
+    )
+    DTypePromotionError = TypeError  # type: ignore
+
+np_long: type
+np_ulong: type
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0.dev0":
+    try:
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                r".*In the future `np\.long` will be defined as.*",
+                FutureWarning,
+            )
+            np_long = np.long  # type: ignore[attr-defined]
+            np_ulong = np.ulong  # type: ignore[attr-defined]
+    except AttributeError:
+            np_long = np.int_
+            np_ulong = np.uint
+else:
+    np_long = np.int_
+    np_ulong = np.uint
+
+IntNumber = int | np.integer
+DecimalNumber = float | np.floating | np.integer
+
+copy_if_needed: bool | None
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
+    copy_if_needed = None
+elif np.lib.NumpyVersion(np.__version__) < "1.28.0":
+    copy_if_needed = False
+else:
+    # 2.0.0 dev versions, handle cases where copy may or may not exist
+    try:
+        np.array([1]).__array__(copy=None)  # type: ignore[call-overload]
+        copy_if_needed = None
+    except TypeError:
+        copy_if_needed = False
+
+
+_RNG: TypeAlias = np.random.Generator | np.random.RandomState
+SeedType: TypeAlias = IntNumber | _RNG | None
+
+GeneratorType = TypeVar("GeneratorType", bound=_RNG)
+
+# Since Generator was introduced in numpy 1.17, the following condition is needed for
+# backward compatibility
+try:
+    from numpy.random import Generator as Generator
+except ImportError:
+    class Generator:  # type: ignore[no-redef]
+        pass
+
+
+def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
+    """Return elements chosen from two possibilities depending on a condition
+
+    Equivalent to ``f(*arrays) if cond else fillvalue`` performed elementwise.
+
+    Parameters
+    ----------
+    cond : array
+        The condition (expressed as a boolean array).
+    arrays : tuple of array
+        Arguments to `f` (and `f2`). Must be broadcastable with `cond`.
+    f : callable
+        Where `cond` is True, output will be ``f(arr1[cond], arr2[cond], ...)``
+    fillvalue : object
+        If provided, value with which to fill output array where `cond` is
+        not True.
+    f2 : callable
+        If provided, output will be ``f2(arr1[cond], arr2[cond], ...)`` where
+        `cond` is not True.
+
+    Returns
+    -------
+    out : array
+        An array with elements from the output of `f` where `cond` is True
+        and `fillvalue` (or elements from the output of `f2`) elsewhere. The
+        returned array has data type determined by Type Promotion Rules
+        with the output of `f` and `fillvalue` (or the output of `f2`).
+
+    Notes
+    -----
+    ``xp.where(cond, x, fillvalue)`` requires explicitly forming `x` even where
+    `cond` is False. This function evaluates ``f(arr1[cond], arr2[cond], ...)``
+    onle where `cond` ``is True.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
+    >>> def f(a, b):
+    ...     return a*b
+    >>> _lazywhere(a > 2, (a, b), f, np.nan)
+    array([ nan,  nan,  21.,  32.])
+
+    """
+    xp = array_namespace(cond, *arrays)
+
+    if (f2 is fillvalue is None) or (f2 is not None and fillvalue is not None):
+        raise ValueError("Exactly one of `fillvalue` or `f2` must be given.")
+
+    args = xp.broadcast_arrays(cond, *arrays)
+    bool_dtype = xp.asarray([True]).dtype  # numpy 1.xx doesn't have `bool`
+    cond, arrays = xp.astype(args[0], bool_dtype, copy=False), args[1:]
+
+    temp1 = xp.asarray(f(*(arr[cond] for arr in arrays)))
+
+    if f2 is None:
+        # If `fillvalue` is a Python scalar and we convert to `xp.asarray`, it gets the
+        # default `int` or `float` type of `xp`, so `result_type` could be wrong.
+        # `result_type` should/will handle mixed array/Python scalars;
+        # remove this special logic when it does.
+        if type(fillvalue) in {bool, int, float, complex}:
+            with np.errstate(invalid='ignore'):
+                dtype = (temp1 * fillvalue).dtype
+        else:
+           dtype = xp.result_type(temp1.dtype, fillvalue)
+        out = xp.full(cond.shape, dtype=dtype,
+                      fill_value=xp.asarray(fillvalue, dtype=dtype))
+    else:
+        ncond = ~cond
+        temp2 = xp.asarray(f2(*(arr[ncond] for arr in arrays)))
+        dtype = xp.result_type(temp1, temp2)
+        out = xp.empty(cond.shape, dtype=dtype)
+        out[ncond] = temp2
+
+    out[cond] = temp1
+
+    return out
+
+
+def _lazyselect(condlist, choicelist, arrays, default=0):
+    """
+    Mimic `np.select(condlist, choicelist)`.
+
+    Notice, it assumes that all `arrays` are of the same shape or can be
+    broadcasted together.
+
+    All functions in `choicelist` must accept array arguments in the order
+    given in `arrays` and must return an array of the same shape as broadcasted
+    `arrays`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> x = np.arange(6)
+    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
+    array([  0,   1,   4,   0,  64, 125])
+
+    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
+    array([   0.,    1.,    4.,   0.,   64.,  125.])
+
+    >>> a = -np.ones_like(x)
+    >>> _lazyselect([x < 3, x > 3],
+    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
+    ...             (x, a), default=np.nan)
+    array([   0.,    1.,    4.,   nan,  -64., -125.])
+
+    """
+    arrays = np.broadcast_arrays(*arrays)
+    tcode = np.mintypecode([a.dtype.char for a in arrays])
+    out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
+    for func, cond in zip(choicelist, condlist):
+        if np.all(cond is False):
+            continue
+        cond, _ = np.broadcast_arrays(cond, arrays[0])
+        temp = tuple(np.extract(cond, arr) for arr in arrays)
+        np.place(out, cond, func(*temp))
+    return out
+
+
+def _aligned_zeros(shape, dtype=float, order="C", align=None):
+    """Allocate a new ndarray with aligned memory.
+
+    Primary use case for this currently is working around a f2py issue
+    in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
+    not necessarily create arrays aligned up to it.
+
+    """
+    dtype = np.dtype(dtype)
+    if align is None:
+        align = dtype.alignment
+    if not hasattr(shape, '__len__'):
+        shape = (shape,)
+    size = functools.reduce(operator.mul, shape) * dtype.itemsize
+    buf = np.empty(size + align + 1, np.uint8)
+    offset = buf.__array_interface__['data'][0] % align
+    if offset != 0:
+        offset = align - offset
+    # Note: slices producing 0-size arrays do not necessarily change
+    # data pointer --- so we use and allocate size+1
+    buf = buf[offset:offset+size+1][:-1]
+    data = np.ndarray(shape, dtype, buf, order=order)
+    data.fill(0)
+    return data
+
+
+def _prune_array(array):
+    """Return an array equivalent to the input array. If the input
+    array is a view of a much larger array, copy its contents to a
+    newly allocated array. Otherwise, return the input unchanged.
+    """
+    if array.base is not None and array.size < array.base.size // 2:
+        return array.copy()
+    return array
+
+
+def float_factorial(n: int) -> float:
+    """Compute the factorial and return as a float
+
+    Returns infinity when result is too large for a double
+    """
+    return float(math.factorial(n)) if n < 171 else np.inf
+
+
+_rng_desc = (
+    r"""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. Specify `rng` for repeatable function behavior.
+
+    If this argument is passed by position or `{old_name}` is passed by keyword,
+    legacy behavior for the argument `{old_name}` applies:
+
+    - If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
+      singleton is used.
+    - If `{old_name}` is an int, a new ``RandomState`` instance is used,
+      seeded with `{old_name}`.
+    - If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
+      that instance is used.
+
+    .. 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 `{old_name}` to `rng`.
+        For an interim period, both keywords will continue to work, although only one
+        may be specified at a time. After the interim period, function calls using the
+        `{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
+        `rng` are outlined above, but only the `rng` keyword should be used in new code.
+        """
+)
+
+
+# SPEC 7
+def _transition_to_rng(old_name, *, position_num=None, end_version=None,
+                       replace_doc=True):
+    """Example decorator to transition from old PRNG usage to new `rng` behavior
+
+    Suppose the decorator is applied to a function that used to accept parameter
+    `old_name='random_state'` either by keyword or as a positional argument at
+    `position_num=1`. At the time of application, the name of the argument in the
+    function signature is manually changed to the new name, `rng`. If positional
+    use was allowed before, this is not changed.*
+
+    - If the function is called with both `random_state` and `rng`, the decorator
+      raises an error.
+    - If `random_state` is provided as a keyword argument, the decorator passes
+      `random_state` to the function's `rng` argument as a keyword. If `end_version`
+      is specified, the decorator will emit a `DeprecationWarning` about the
+      deprecation of keyword `random_state`.
+    - If `random_state` is provided as a positional argument, the decorator passes
+      `random_state` to the function's `rng` argument by position. If `end_version`
+      is specified, the decorator will emit a `FutureWarning` about the changing
+      interpretation of the argument.
+    - If `rng` is provided as a keyword argument, the decorator validates `rng` using
+      `numpy.random.default_rng` before passing it to the function.
+    - If `end_version` is specified and neither `random_state` nor `rng` is provided
+      by the user, the decorator checks whether `np.random.seed` has been used to set
+      the global seed. If so, it emits a `FutureWarning`, noting that usage of
+      `numpy.random.seed` will eventually have no effect. Either way, the decorator
+      calls the function without explicitly passing the `rng` argument.
+
+    If `end_version` is specified, a user must pass `rng` as a keyword to avoid
+    warnings.
+
+    After the deprecation period, the decorator can be removed, and the function
+    can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.
+
+    * A `FutureWarning` is emitted when the PRNG argument is used by
+      position. It indicates that the "Hinsen principle" (same
+      code yielding different results in two versions of the software)
+      will be violated, unless positional use is deprecated. Specifically:
+
+      - If `None` is passed by position and `np.random.seed` has been used,
+        the function will change from being seeded to being unseeded.
+      - If an integer is passed by position, the random stream will change.
+      - If `np.random` or an instance of `RandomState` is passed by position,
+        an error will be raised.
+
+      We suggest that projects consider deprecating positional use of
+      `random_state`/`rng` (i.e., change their function signatures to
+      ``def my_func(..., *, rng=None)``); that might not make sense
+      for all projects, so this SPEC does not make that
+      recommendation, neither does this decorator enforce it.
+
+    Parameters
+    ----------
+    old_name : str
+        The old name of the PRNG argument (e.g. `seed` or `random_state`).
+    position_num : int, optional
+        The (0-indexed) position of the old PRNG argument (if accepted by position).
+        Maintainers are welcome to eliminate this argument and use, for example,
+        `inspect`, if preferred.
+    end_version : str, optional
+        The full version number of the library when the behavior described in
+        `DeprecationWarning`s and `FutureWarning`s will take effect. If left
+        unspecified, no warnings will be emitted by the decorator.
+    replace_doc : bool, default: True
+        Whether the decorator should replace the documentation for parameter `rng` with
+        `_rng_desc` (defined above), which documents both new `rng` keyword behavior
+        and typical legacy `random_state`/`seed` behavior. If True, manually replace
+        the first paragraph of the function's old `random_state`/`seed` documentation
+        with the desired *final* `rng` documentation; this way, no changes to
+        documentation are needed when the decorator is removed. Documentation of `rng`
+        after the first blank line is preserved. Use False if the function's old
+        `random_state`/`seed` behavior does not match that described by `_rng_desc`.
+
+    """
+    NEW_NAME = "rng"
+
+    cmn_msg = (
+        "To silence this warning and ensure consistent behavior in SciPy "
+        f"{end_version}, control the RNG using argument `{NEW_NAME}`. Arguments passed "
+        f"to keyword `{NEW_NAME}` will be validated by `np.random.default_rng`, so the "
+        "behavior corresponding with a given value may change compared to use of "
+        f"`{old_name}`. For example, "
+        "1) `None` will result in unpredictable random numbers, "
+        "2) an integer will result in a different stream of random numbers, (with the "
+        "same distribution), and "
+        "3) `np.random` or `RandomState` instances will result in an error. "
+        "See the documentation of `default_rng` for more information."
+    )
+
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            # Determine how PRNG was passed
+            as_old_kwarg = old_name in kwargs
+            as_new_kwarg = NEW_NAME in kwargs
+            as_pos_arg = position_num is not None and len(args) >= position_num + 1
+            emit_warning = end_version is not None
+
+            # Can only specify PRNG one of the three ways
+            if int(as_old_kwarg) + int(as_new_kwarg) + int(as_pos_arg) > 1:
+                message = (
+                    f"{fun.__name__}() got multiple values for "
+                    f"argument now known as `{NEW_NAME}`. Specify one of "
+                    f"`{NEW_NAME}` or `{old_name}`."
+                )
+                raise TypeError(message)
+
+            # Check whether global random state has been set
+            global_seed_set = np.random.mtrand._rand._bit_generator._seed_seq is None
+
+            if as_old_kwarg:  # warn about deprecated use of old kwarg
+                kwargs[NEW_NAME] = kwargs.pop(old_name)
+                if emit_warning:
+                    message = (
+                        f"Use of keyword argument `{old_name}` is "
+                        f"deprecated and replaced by `{NEW_NAME}`.  "
+                        f"Support for `{old_name}` will be removed "
+                        f"in SciPy {end_version}. "
+                    ) + cmn_msg
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+            elif as_pos_arg:
+                # Warn about changing meaning of positional arg
+
+                # Note that this decorator does not deprecate positional use of the
+                # argument; it only warns that the behavior will change in the future.
+                # Simultaneously transitioning to keyword-only use is another option.
+
+                arg = args[position_num]
+                # If the argument is None and the global seed wasn't set, or if the
+                # argument is one of a few new classes, the user will not notice change
+                # in behavior.
+                ok_classes = (
+                    np.random.Generator,
+                    np.random.SeedSequence,
+                    np.random.BitGenerator,
+                )
+                if (arg is None and not global_seed_set) or isinstance(arg, ok_classes):
+                    pass
+                elif emit_warning:
+                    message = (
+                        f"Positional use of `{NEW_NAME}` (formerly known as "
+                        f"`{old_name}`) is still allowed, but the behavior is "
+                        "changing: the argument will be normalized using "
+                        f"`np.random.default_rng` beginning in SciPy {end_version}, "
+                        "and the resulting `Generator` will be used to generate "
+                        "random numbers."
+                    ) + cmn_msg
+                    warnings.warn(message, FutureWarning, stacklevel=2)
+
+            elif as_new_kwarg:  # no warnings; this is the preferred use
+                # After the removal of the decorator, normalization with
+                # np.random.default_rng will be done inside the decorated function
+                kwargs[NEW_NAME] = np.random.default_rng(kwargs[NEW_NAME])
+
+            elif global_seed_set and emit_warning:
+                # Emit FutureWarning if `np.random.seed` was used and no PRNG was passed
+                message = (
+                    "The NumPy global RNG was seeded by calling "
+                    f"`np.random.seed`. Beginning in {end_version}, this "
+                    "function will no longer use the global RNG."
+                ) + cmn_msg
+                warnings.warn(message, FutureWarning, stacklevel=2)
+
+            return fun(*args, **kwargs)
+
+        if replace_doc:
+            doc = FunctionDoc(wrapper)
+            parameter_names = [param.name for param in doc['Parameters']]
+            if 'rng' in parameter_names:
+                _type = "{None, int, `numpy.random.Generator`}, optional"
+                _desc = _rng_desc.replace("{old_name}", old_name)
+                old_doc = doc['Parameters'][parameter_names.index('rng')].desc
+                old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
+                new_doc = [_desc] + old_doc_keep
+                _rng_parameter_doc = Parameter('rng', _type, new_doc)
+                doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
+                doc = str(doc).split("\n", 1)[1]  # remove signature
+                wrapper.__doc__ = str(doc)
+        return wrapper
+
+    return decorator
+
+
+# copy-pasted from scikit-learn utils/validation.py
+def check_random_state(seed):
+    """Turn `seed` into a `np.random.RandomState` instance.
+
+    Parameters
+    ----------
+    seed : {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.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or seed is np.random:
+        return np.random.mtrand._rand
+    if isinstance(seed, numbers.Integral | np.integer):
+        return np.random.RandomState(seed)
+    if isinstance(seed, np.random.RandomState | np.random.Generator):
+        return seed
+
+    raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
+                     " instance")
+
+
+def _asarray_validated(a, check_finite=True,
+                       sparse_ok=False, objects_ok=False, mask_ok=False,
+                       as_inexact=False):
+    """
+    Helper function for SciPy argument validation.
+
+    Many SciPy linear algebra functions do support arbitrary array-like
+    input arguments. Examples of commonly unsupported inputs include
+    matrices containing inf/nan, sparse matrix representations, and
+    matrices with complicated elements.
+
+    Parameters
+    ----------
+    a : array_like
+        The array-like input.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    sparse_ok : bool, optional
+        True if scipy sparse matrices are allowed.
+    objects_ok : bool, optional
+        True if arrays with dype('O') are allowed.
+    mask_ok : bool, optional
+        True if masked arrays are allowed.
+    as_inexact : bool, optional
+        True to convert the input array to a np.inexact dtype.
+
+    Returns
+    -------
+    ret : ndarray
+        The converted validated array.
+
+    """
+    if not sparse_ok:
+        import scipy.sparse
+        if scipy.sparse.issparse(a):
+            msg = ('Sparse arrays/matrices are not supported by this function. '
+                   'Perhaps one of the `scipy.sparse.linalg` functions '
+                   'would work instead.')
+            raise ValueError(msg)
+    if not mask_ok:
+        if np.ma.isMaskedArray(a):
+            raise ValueError('masked arrays are not supported')
+    toarray = np.asarray_chkfinite if check_finite else np.asarray
+    a = toarray(a)
+    if not objects_ok:
+        if a.dtype is np.dtype('O'):
+            raise ValueError('object arrays are not supported')
+    if as_inexact:
+        if not np.issubdtype(a.dtype, np.inexact):
+            a = toarray(a, dtype=np.float64)
+    return a
+
+
+def _validate_int(k, name, minimum=None):
+    """
+    Validate a scalar integer.
+
+    This function can be used to validate an argument to a function
+    that expects the value to be an integer.  It uses `operator.index`
+    to validate the value (so, for example, k=2.0 results in a
+    TypeError).
+
+    Parameters
+    ----------
+    k : int
+        The value to be validated.
+    name : str
+        The name of the parameter.
+    minimum : int, optional
+        An optional lower bound.
+    """
+    try:
+        k = operator.index(k)
+    except TypeError:
+        raise TypeError(f'{name} must be an integer.') from None
+    if minimum is not None and k < minimum:
+        raise ValueError(f'{name} must be an integer not less '
+                         f'than {minimum}') from None
+    return k
+
+
+# Add a replacement for inspect.getfullargspec()/
+# The version below is borrowed from Django,
+# https://github.com/django/django/pull/4846.
+
+# Note an inconsistency between inspect.getfullargspec(func) and
+# inspect.signature(func). If `func` is a bound method, the latter does *not*
+# list `self` as a first argument, while the former *does*.
+# Hence, cook up a common ground replacement: `getfullargspec_no_self` which
+# mimics `inspect.getfullargspec` but does not list `self`.
+#
+# This way, the caller code does not need to know whether it uses a legacy
+# .getfullargspec or a bright and shiny .signature.
+
+FullArgSpec = namedtuple('FullArgSpec',
+                         ['args', 'varargs', 'varkw', 'defaults',
+                          'kwonlyargs', 'kwonlydefaults', 'annotations'])
+
+
+def getfullargspec_no_self(func):
+    """inspect.getfullargspec replacement using inspect.signature.
+
+    If func is a bound method, do not list the 'self' parameter.
+
+    Parameters
+    ----------
+    func : callable
+        A callable to inspect
+
+    Returns
+    -------
+    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                              kwonlydefaults, annotations)
+
+        NOTE: if the first argument of `func` is self, it is *not*, I repeat
+        *not*, included in fullargspec.args.
+        This is done for consistency between inspect.getargspec() under
+        Python 2.x, and inspect.signature() under Python 3.x.
+
+    """
+    sig = inspect.signature(func)
+    args = [
+        p.name for p in sig.parameters.values()
+        if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
+                      inspect.Parameter.POSITIONAL_ONLY]
+    ]
+    varargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_POSITIONAL
+    ]
+    varargs = varargs[0] if varargs else None
+    varkw = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_KEYWORD
+    ]
+    varkw = varkw[0] if varkw else None
+    defaults = tuple(
+        p.default for p in sig.parameters.values()
+        if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
+            p.default is not p.empty)
+    ) or None
+    kwonlyargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.KEYWORD_ONLY
+    ]
+    kwdefaults = {p.name: p.default for p in sig.parameters.values()
+                  if p.kind == inspect.Parameter.KEYWORD_ONLY and
+                  p.default is not p.empty}
+    annotations = {p.name: p.annotation for p in sig.parameters.values()
+                   if p.annotation is not p.empty}
+    return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                       kwdefaults or None, annotations)
+
+
+class _FunctionWrapper:
+    """
+    Object to wrap user's function, allowing picklability
+    """
+    def __init__(self, f, args):
+        self.f = f
+        self.args = [] if args is None else args
+
+    def __call__(self, x):
+        return self.f(x, *self.args)
+
+
+class MapWrapper:
+    """
+    Parallelisation wrapper for working with map-like callables, such as
+    `multiprocessing.Pool.map`.
+
+    Parameters
+    ----------
+    pool : int or map-like callable
+        If `pool` is an integer, then it specifies the number of threads to
+        use for parallelization. If ``int(pool) == 1``, then no parallel
+        processing is used and the map builtin is used.
+        If ``pool == -1``, then the pool will utilize all available CPUs.
+        If `pool` is a map-like callable that follows the same
+        calling sequence as the built-in map function, then this callable is
+        used for parallelization.
+    """
+    def __init__(self, pool=1):
+        self.pool = None
+        self._mapfunc = map
+        self._own_pool = False
+
+        if callable(pool):
+            self.pool = pool
+            self._mapfunc = self.pool
+        else:
+            from multiprocessing import Pool
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = Pool()
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            elif int(pool) == 1:
+                pass
+            elif int(pool) > 1:
+                # use the number of processors requested
+                self.pool = Pool(processes=int(pool))
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            else:
+                raise RuntimeError("Number of workers specified must be -1,"
+                                   " an int >= 1, or an object with a 'map' "
+                                   "method")
+
+    def __enter__(self):
+        return self
+
+    def terminate(self):
+        if self._own_pool:
+            self.pool.terminate()
+
+    def join(self):
+        if self._own_pool:
+            self.pool.join()
+
+    def close(self):
+        if self._own_pool:
+            self.pool.close()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if self._own_pool:
+            self.pool.close()
+            self.pool.terminate()
+
+    def __call__(self, func, iterable):
+        # only accept one iterable because that's all Pool.map accepts
+        try:
+            return self._mapfunc(func, iterable)
+        except TypeError as e:
+            # wrong number of arguments
+            raise TypeError("The map-like callable must be of the"
+                            " form f(func, iterable)") from e
+
+
+def rng_integers(gen, low, high=None, size=None, dtype='int64',
+                 endpoint=False):
+    """
+    Return random integers from low (inclusive) to high (exclusive), or if
+    endpoint=True, low (inclusive) to high (inclusive). Replaces
+    `RandomState.randint` (with endpoint=False) and
+    `RandomState.random_integers` (with endpoint=True).
+
+    Return random integers from the "discrete uniform" distribution of the
+    specified dtype. If high is None (the default), then results are from
+    0 to low.
+
+    Parameters
+    ----------
+    gen : {None, np.random.RandomState, np.random.Generator}
+        Random number generator. If None, then the np.random.RandomState
+        singleton is used.
+    low : int or array-like of ints
+        Lowest (signed) integers to be drawn from the distribution (unless
+        high=None, in which case this parameter is 0 and this value is used
+        for high).
+    high : int or array-like of ints
+        If provided, one above the largest (signed) integer to be drawn from
+        the distribution (see above for behavior if high=None). If array-like,
+        must contain integer values.
+    size : array-like of ints, optional
+        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
+        samples are drawn. Default is None, in which case a single value is
+        returned.
+    dtype : {str, dtype}, optional
+        Desired dtype of the result. All dtypes are determined by their name,
+        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
+        precision may have different C types depending on the platform.
+        The default value is 'int64'.
+    endpoint : bool, optional
+        If True, sample from the interval [low, high] instead of the default
+        [low, high) Defaults to False.
+
+    Returns
+    -------
+    out: int or ndarray of ints
+        size-shaped array of random integers from the appropriate distribution,
+        or a single such random int if size not provided.
+    """
+    if isinstance(gen, Generator):
+        return gen.integers(low, high=high, size=size, dtype=dtype,
+                            endpoint=endpoint)
+    else:
+        if gen is None:
+            # default is RandomState singleton used by np.random.
+            gen = np.random.mtrand._rand
+        if endpoint:
+            # inclusive of endpoint
+            # remember that low and high can be arrays, so don't modify in
+            # place
+            if high is None:
+                return gen.randint(low + 1, size=size, dtype=dtype)
+            if high is not None:
+                return gen.randint(low, high=high + 1, size=size, dtype=dtype)
+
+        # exclusive
+        return gen.randint(low, high=high, size=size, dtype=dtype)
+
+
+@contextmanager
+def _fixed_default_rng(seed=1638083107694713882823079058616272161):
+    """Context with a fixed np.random.default_rng seed."""
+    orig_fun = np.random.default_rng
+    np.random.default_rng = lambda seed=seed: orig_fun(seed)
+    try:
+        yield
+    finally:
+        np.random.default_rng = orig_fun
+
+
+def _rng_html_rewrite(func):
+    """Rewrite the HTML rendering of ``np.random.default_rng``.
+
+    This is intended to decorate
+    ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
+
+    Examples are only run by Sphinx when there are plot involved. Even so,
+    it does not change the result values getting printed.
+    """
+    # hexadecimal or number seed, case-insensitive
+    pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
+
+    def _wrapped(*args, **kwargs):
+        res = func(*args, **kwargs)
+        lines = [
+            re.sub(pattern, 'np.random.default_rng()', line)
+            for line in res
+        ]
+        return lines
+
+    return _wrapped
+
+
+def _argmin(a, keepdims=False, axis=None):
+    """
+    argmin with a `keepdims` parameter.
+
+    See https://github.com/numpy/numpy/issues/8710
+
+    If axis is not None, a.shape[axis] must be greater than 0.
+    """
+    res = np.argmin(a, axis=axis)
+    if keepdims and axis is not None:
+        res = np.expand_dims(res, axis=axis)
+    return res
+
+
+def _first_nonnan(a, axis):
+    """
+    Return the first non-nan value along the given axis.
+
+    If a slice is all nan, nan is returned for that slice.
+
+    The shape of the return value corresponds to ``keepdims=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> nan = np.nan
+    >>> a = np.array([[ 3.,  3., nan,  3.],
+                      [ 1., nan,  2.,  4.],
+                      [nan, nan,  9., -1.],
+                      [nan,  5.,  4.,  3.],
+                      [ 2.,  2.,  2.,  2.],
+                      [nan, nan, nan, nan]])
+    >>> _first_nonnan(a, axis=0)
+    array([[3., 3., 2., 3.]])
+    >>> _first_nonnan(a, axis=1)
+    array([[ 3.],
+           [ 1.],
+           [ 9.],
+           [ 5.],
+           [ 2.],
+           [nan]])
+    """
+    k = _argmin(np.isnan(a), axis=axis, keepdims=True)
+    return np.take_along_axis(a, k, axis=axis)
+
+
+def _nan_allsame(a, axis, keepdims=False):
+    """
+    Determine if the values along an axis are all the same.
+
+    nan values are ignored.
+
+    `a` must be a numpy array.
+
+    `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.
+
+    For an axis of length 0, the result is True.  That is, we adopt the
+    convention that ``allsame([])`` is True. (There are no values in the
+    input that are different.)
+
+    `True` is returned for slices that are all nan--not because all the
+    values are the same, but because this is equivalent to ``allsame([])``.
+
+    Examples
+    --------
+    >>> from numpy import nan, array
+    >>> a = array([[ 3.,  3., nan,  3.],
+    ...            [ 1., nan,  2.,  4.],
+    ...            [nan, nan,  9., -1.],
+    ...            [nan,  5.,  4.,  3.],
+    ...            [ 2.,  2.,  2.,  2.],
+    ...            [nan, nan, nan, nan]])
+    >>> _nan_allsame(a, axis=1, keepdims=True)
+    array([[ True],
+           [False],
+           [False],
+           [False],
+           [ True],
+           [ True]])
+    """
+    if axis is None:
+        if a.size == 0:
+            return True
+        a = a.ravel()
+        axis = 0
+    else:
+        shp = a.shape
+        if shp[axis] == 0:
+            shp = shp[:axis] + (1,)*keepdims + shp[axis + 1:]
+            return np.full(shp, fill_value=True, dtype=bool)
+    a0 = _first_nonnan(a, axis=axis)
+    return ((a0 == a) | np.isnan(a)).all(axis=axis, keepdims=keepdims)
+
+
+def _contains_nan(a, nan_policy='propagate', policies=None, *,
+                  xp_omit_okay=False, xp=None):
+    # Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
+    # handle non-NumPy arrays, most functions that call `_contains_nan` want
+    # it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
+    # Some functions support `nan_policy='omit'` natively, so setting this to
+    # `True` prevents the error from being raised.
+    if xp is None:
+        xp = array_namespace(a)
+    not_numpy = not is_numpy(xp)
+
+    if policies is None:
+        policies = {'propagate', 'raise', 'omit'}
+    if nan_policy not in policies:
+        raise ValueError(f"nan_policy must be one of {set(policies)}.")
+
+    if xp_size(a) == 0:
+        contains_nan = False
+    elif xp.isdtype(a.dtype, "real floating"):
+        # Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
+        # reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
+        contains_nan = xp.isnan(xp.max(a))
+    elif xp.isdtype(a.dtype, "complex floating"):
+        # Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
+        # would be more efficient.
+        contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
+    elif is_numpy(xp) and np.issubdtype(a.dtype, object):
+        contains_nan = False
+        for el in a.ravel():
+            # isnan doesn't work on non-numeric elements
+            if np.issubdtype(type(el), np.number) and np.isnan(el):
+                contains_nan = True
+                break
+    else:
+        # Only `object` and `inexact` arrays can have NaNs
+        contains_nan = False
+
+    if contains_nan and nan_policy == 'raise':
+        raise ValueError("The input contains nan values")
+
+    if not xp_omit_okay and not_numpy and contains_nan and nan_policy=='omit':
+        message = "`nan_policy='omit' is incompatible with non-NumPy arrays."
+        raise ValueError(message)
+
+    return contains_nan, nan_policy
+
+
+def _rename_parameter(old_name, new_name, dep_version=None):
+    """
+    Generate decorator for backward-compatible keyword renaming.
+
+    Apply the decorator generated by `_rename_parameter` to functions with a
+    recently renamed parameter to maintain backward-compatibility.
+
+    After decoration, the function behaves as follows:
+    If only the new parameter is passed into the function, behave as usual.
+    If only the old parameter is passed into the function (as a keyword), raise
+    a DeprecationWarning if `dep_version` is provided, and behave as usual
+    otherwise.
+    If both old and new parameters are passed into the function, raise a
+    DeprecationWarning if `dep_version` is provided, and raise the appropriate
+    TypeError (function got multiple values for argument).
+
+    Parameters
+    ----------
+    old_name : str
+        Old name of parameter
+    new_name : str
+        New name of parameter
+    dep_version : str, optional
+        Version of SciPy in which old parameter was deprecated in the format
+        'X.Y.Z'. If supplied, the deprecation message will indicate that
+        support for the old parameter will be removed in version 'X.Y+2.Z'
+
+    Notes
+    -----
+    Untested with functions that accept *args. Probably won't work as written.
+
+    """
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            if old_name in kwargs:
+                if dep_version:
+                    end_version = dep_version.split('.')
+                    end_version[1] = str(int(end_version[1]) + 2)
+                    end_version = '.'.join(end_version)
+                    message = (f"Use of keyword argument `{old_name}` is "
+                               f"deprecated and replaced by `{new_name}`.  "
+                               f"Support for `{old_name}` will be removed "
+                               f"in SciPy {end_version}.")
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+                if new_name in kwargs:
+                    message = (f"{fun.__name__}() got multiple values for "
+                               f"argument now known as `{new_name}`")
+                    raise TypeError(message)
+                kwargs[new_name] = kwargs.pop(old_name)
+            return fun(*args, **kwargs)
+        return wrapper
+    return decorator
+
+
+def _rng_spawn(rng, n_children):
+    # spawns independent RNGs from a parent RNG
+    bg = rng._bit_generator
+    ss = bg._seed_seq
+    child_rngs = [np.random.Generator(type(bg)(child_ss))
+                  for child_ss in ss.spawn(n_children)]
+    return child_rngs
+
+
+def _get_nan(*data, xp=None):
+    xp = array_namespace(*data) if xp is None else xp
+    # Get NaN of appropriate dtype for data
+    data = [xp.asarray(item) for item in data]
+    try:
+        min_float = getattr(xp, 'float16', xp.float32)
+        dtype = xp.result_type(*data, min_float)  # must be at least a float
+    except DTypePromotionError:
+        # fallback to float64
+        dtype = xp.float64
+    return xp.asarray(xp.nan, dtype=dtype)[()]
+
+
+def normalize_axis_index(axis, ndim):
+    # Check if `axis` is in the correct range and normalize it
+    if axis < -ndim or axis >= ndim:
+        msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
+        raise AxisError(msg)
+
+    if axis < 0:
+        axis = axis + ndim
+    return axis
+
+
+def _call_callback_maybe_halt(callback, res):
+    """Call wrapped callback; return True if algorithm should stop.
+
+    Parameters
+    ----------
+    callback : callable or None
+        A user-provided callback wrapped with `_wrap_callback`
+    res : OptimizeResult
+        Information about the current iterate
+
+    Returns
+    -------
+    halt : bool
+        True if minimization should stop
+
+    """
+    if callback is None:
+        return False
+    try:
+        callback(res)
+        return False
+    except StopIteration:
+        callback.stop_iteration = True
+        return True
+
+
+class _RichResult(dict):
+    """ Container for multiple outputs with pretty-printing """
+    def __getattr__(self, name):
+        try:
+            return self[name]
+        except KeyError as e:
+            raise AttributeError(name) from e
+
+    __setattr__ = dict.__setitem__  # type: ignore[assignment]
+    __delattr__ = dict.__delitem__  # type: ignore[assignment]
+
+    def __repr__(self):
+        order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
+                      'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
+                      'converged', 'flag', 'function_calls', 'iterations',
+                      'root']
+        order_keys = getattr(self, '_order_keys', order_keys)
+        # 'slack', 'con' are redundant with residuals
+        # 'crossover_nit' is probably not interesting to most users
+        omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
+
+        def key(item):
+            try:
+                return order_keys.index(item[0].lower())
+            except ValueError:  # item not in list
+                return np.inf
+
+        def omit_redundant(items):
+            for item in items:
+                if item[0] in omit_keys:
+                    continue
+                yield item
+
+        def item_sorter(d):
+            return sorted(omit_redundant(d.items()), key=key)
+
+        if self.keys():
+            return _dict_formatter(self, sorter=item_sorter)
+        else:
+            return self.__class__.__name__ + "()"
+
+    def __dir__(self):
+        return list(self.keys())
+
+
+def _indenter(s, n=0):
+    """
+    Ensures that lines after the first are indented by the specified amount
+    """
+    split = s.split("\n")
+    indent = " "*n
+    return ("\n" + indent).join(split)
+
+
+def _float_formatter_10(x):
+    """
+    Returns a string representation of a float with exactly ten characters
+    """
+    if np.isposinf(x):
+        return "       inf"
+    elif np.isneginf(x):
+        return "      -inf"
+    elif np.isnan(x):
+        return "       nan"
+    return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
+
+
+def _dict_formatter(d, n=0, mplus=1, sorter=None):
+    """
+    Pretty printer for dictionaries
+
+    `n` keeps track of the starting indentation;
+    lines are indented by this much after a line break.
+    `mplus` is additional left padding applied to keys
+    """
+    if isinstance(d, dict):
+        m = max(map(len, list(d.keys()))) + mplus  # width to print keys
+        s = '\n'.join([k.rjust(m) + ': ' +  # right justified, width m
+                       _indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
+                       for k, v in sorter(d)])  # +2 for ': '
+    else:
+        # By default, NumPy arrays print with linewidth=76. `n` is
+        # the indent at which a line begins printing, so it is subtracted
+        # from the default to avoid exceeding 76 characters total.
+        # `edgeitems` is the number of elements to include before and after
+        # ellipses when arrays are not shown in full.
+        # `threshold` is the maximum number of elements for which an
+        # array is shown in full.
+        # These values tend to work well for use with OptimizeResult.
+        with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
+                             formatter={'float_kind': _float_formatter_10}):
+            s = str(d)
+    return s
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..30b1d852db016240f06f8a6dfb163b2e3edafba0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py
@@ -0,0 +1,22 @@
+"""
+NumPy Array API compatibility library
+
+This is a small wrapper around NumPy and CuPy that is compatible with the
+Array API standard https://data-apis.org/array-api/latest/. See also NEP 47
+https://numpy.org/neps/nep-0047-array-api-standard.html.
+
+Unlike array_api_strict, this is not a strict minimal implementation of the
+Array API, but rather just an extension of the main NumPy namespace with
+changes needed to be compliant with the Array API. See
+https://numpy.org/doc/stable/reference/array_api.html for a full list of
+changes. In particular, unlike array_api_strict, this package does not use a
+separate Array object, but rather just uses numpy.ndarray directly.
+
+Library authors using the Array API may wish to test against array_api_strict
+to ensure they are not using functionality outside of the standard, but prefer
+this implementation for the default when working with NumPy arrays.
+
+"""
+__version__ = '1.9.1'
+
+from .common import *  # noqa: F401, F403
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c133bdfdcfcac72d63a31c98a75aff9d0452e6f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d30ebd1291429950881131c59a9374b9475b9b33
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..170a1ff9e6459a8cd76f8f6f9b4bca1e894e9883
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py
@@ -0,0 +1,46 @@
+"""
+Internal helpers
+"""
+
+from functools import wraps
+from inspect import signature
+
+def get_xp(xp):
+    """
+    Decorator to automatically replace xp with the corresponding array module.
+
+    Use like
+
+    import numpy as np
+
+    @get_xp(np)
+    def func(x, /, xp, kwarg=None):
+        return xp.func(x, kwarg=kwarg)
+
+    Note that xp must be a keyword argument and come after all non-keyword
+    arguments.
+
+    """
+
+    def inner(f):
+        @wraps(f)
+        def wrapped_f(*args, **kwargs):
+            return f(*args, xp=xp, **kwargs)
+
+        sig = signature(f)
+        new_sig = sig.replace(
+            parameters=[sig.parameters[i] for i in sig.parameters if i != "xp"]
+        )
+
+        if wrapped_f.__doc__ is None:
+            wrapped_f.__doc__ = f"""\
+Array API compatibility wrapper for {f.__name__}.
+
+See the corresponding documentation in NumPy/CuPy and/or the array API
+specification for more details.
+
+"""
+        wrapped_f.__signature__ = new_sig
+        return wrapped_f
+
+    return inner
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91ab1c405e1d700e2bab5a87fc70196a34871e7d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
@@ -0,0 +1 @@
+from ._helpers import * # noqa: F403
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..154da25e1a3575816efe7fdf7013c4a21a6f6030
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9efe0d96a3ab7dc562a0ab7fc25c02d90c19caa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..efdc4b056f8bf2657469781df080a32274ffa05c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d251f8ec47f2d7e2ac753345175a7192c2760f72
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d06751040f8f0633aab43161b1a585e8c8e261d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..219164a019192f67e6e1c65e36eb8284da089303
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a90f44424d81f25e54babb79b09fef7d1b05660
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
@@ -0,0 +1,555 @@
+"""
+These are functions that are just aliases of existing functions in NumPy.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Sequence, Tuple, Union
+    from ._typing import ndarray, Device, Dtype
+
+from typing import NamedTuple
+import inspect
+
+from ._helpers import array_namespace, _check_device, device, is_torch_array, is_cupy_namespace
+
+# These functions are modified from the NumPy versions.
+
+# Creation functions add the device keyword (which does nothing for NumPy)
+
+def arange(
+    start: Union[int, float],
+    /,
+    stop: Optional[Union[int, float]] = None,
+    step: Union[int, float] = 1,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs)
+
+def empty(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.empty(shape, dtype=dtype, **kwargs)
+
+def empty_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.empty_like(x, dtype=dtype, **kwargs)
+
+def eye(
+    n_rows: int,
+    n_cols: Optional[int] = None,
+    /,
+    *,
+    xp,
+    k: int = 0,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs)
+
+def full(
+    shape: Union[int, Tuple[int, ...]],
+    fill_value: Union[int, float],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.full(shape, fill_value, dtype=dtype, **kwargs)
+
+def full_like(
+    x: ndarray,
+    /,
+    fill_value: Union[int, float],
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.full_like(x, fill_value, dtype=dtype, **kwargs)
+
+def linspace(
+    start: Union[int, float],
+    stop: Union[int, float],
+    /,
+    num: int,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    endpoint: bool = True,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs)
+
+def ones(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.ones(shape, dtype=dtype, **kwargs)
+
+def ones_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.ones_like(x, dtype=dtype, **kwargs)
+
+def zeros(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.zeros(shape, dtype=dtype, **kwargs)
+
+def zeros_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.zeros_like(x, dtype=dtype, **kwargs)
+
+# np.unique() is split into four functions in the array API:
+# unique_all, unique_counts, unique_inverse, and unique_values (this is done
+# to remove polymorphic return types).
+
+# The functions here return namedtuples (np.unique() returns a normal
+# tuple).
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+class UniqueAllResult(NamedTuple):
+    values: ndarray
+    indices: ndarray
+    inverse_indices: ndarray
+    counts: ndarray
+
+
+class UniqueCountsResult(NamedTuple):
+    values: ndarray
+    counts: ndarray
+
+
+class UniqueInverseResult(NamedTuple):
+    values: ndarray
+    inverse_indices: ndarray
+
+
+def _unique_kwargs(xp):
+    # Older versions of NumPy and CuPy do not have equal_nan. Rather than
+    # trying to parse version numbers, just check if equal_nan is in the
+    # signature.
+    s = inspect.signature(xp.unique)
+    if 'equal_nan' in s.parameters:
+        return {'equal_nan': False}
+    return {}
+
+def unique_all(x: ndarray, /, xp) -> UniqueAllResult:
+    kwargs = _unique_kwargs(xp)
+    values, indices, inverse_indices, counts = xp.unique(
+        x,
+        return_counts=True,
+        return_index=True,
+        return_inverse=True,
+        **kwargs,
+    )
+    # np.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueAllResult(
+        values,
+        indices,
+        inverse_indices,
+        counts,
+    )
+
+
+def unique_counts(x: ndarray, /, xp) -> UniqueCountsResult:
+    kwargs = _unique_kwargs(xp)
+    res = xp.unique(
+        x,
+        return_counts=True,
+        return_index=False,
+        return_inverse=False,
+        **kwargs
+    )
+
+    return UniqueCountsResult(*res)
+
+
+def unique_inverse(x: ndarray, /, xp) -> UniqueInverseResult:
+    kwargs = _unique_kwargs(xp)
+    values, inverse_indices = xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=True,
+        **kwargs,
+    )
+    # xp.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueInverseResult(values, inverse_indices)
+
+
+def unique_values(x: ndarray, /, xp) -> ndarray:
+    kwargs = _unique_kwargs(xp)
+    return xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=False,
+        **kwargs,
+    )
+
+def astype(x: ndarray, dtype: Dtype, /, *, copy: bool = True) -> ndarray:
+    if not copy and dtype == x.dtype:
+        return x
+    return x.astype(dtype=dtype, copy=copy)
+
+# These functions have different keyword argument names
+
+def std(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    correction: Union[int, float] = 0.0, # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs,
+) -> ndarray:
+    return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+def var(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    correction: Union[int, float] = 0.0, # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs,
+) -> ndarray:
+    return xp.var(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+# cumulative_sum is renamed from cumsum, and adds the include_initial keyword
+# argument
+
+def cumulative_sum(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[int] = None,
+    dtype: Optional[Dtype] = None,
+    include_initial: bool = False,
+    **kwargs
+) -> ndarray:
+    wrapped_xp = array_namespace(x)
+
+    # TODO: The standard is not clear about what should happen when x.ndim == 0.
+    if axis is None:
+        if x.ndim > 1:
+            raise ValueError("axis must be specified in cumulative_sum for more than one dimension")
+        axis = 0
+
+    res = xp.cumsum(x, axis=axis, dtype=dtype, **kwargs)
+
+    # np.cumsum does not support include_initial
+    if include_initial:
+        initial_shape = list(x.shape)
+        initial_shape[axis] = 1
+        res = xp.concatenate(
+            [wrapped_xp.zeros(shape=initial_shape, dtype=res.dtype, device=device(res)), res],
+            axis=axis,
+        )
+    return res
+
+# The min and max argument names in clip are different and not optional in numpy, and type
+# promotion behavior is different.
+def clip(
+    x: ndarray,
+    /,
+    min: Optional[Union[int, float, ndarray]] = None,
+    max: Optional[Union[int, float, ndarray]] = None,
+    *,
+    xp,
+    # TODO: np.clip has other ufunc kwargs
+    out: Optional[ndarray] = None,
+) -> ndarray:
+    def _isscalar(a):
+        return isinstance(a, (int, float, type(None)))
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    wrapped_xp = array_namespace(x)
+
+    result_shape = xp.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    # np.clip does type promotion but the array API clip requires that the
+    # output have the same dtype as x. We do this instead of just downcasting
+    # the result of xp.clip() to handle some corner cases better (e.g.,
+    # avoiding uint64 -> float64 promotion).
+
+    # Note: cases where min or max overflow (integer) or round (float) in the
+    # wrong direction when downcasting to x.dtype are unspecified. This code
+    # just does whatever NumPy does when it downcasts in the assignment, but
+    # other behavior could be preferred, especially for integers. For example,
+    # this code produces:
+
+    # >>> clip(asarray(0, dtype=int8), asarray(128, dtype=int16), None)
+    # -128
+
+    # but an answer of 0 might be preferred. See
+    # https://github.com/numpy/numpy/issues/24976 for more discussion on this issue.
+
+
+    # At least handle the case of Python integers correctly (see
+    # https://github.com/numpy/numpy/pull/26892).
+    if type(min) is int and min <= wrapped_xp.iinfo(x.dtype).min:
+        min = None
+    if type(max) is int and max >= wrapped_xp.iinfo(x.dtype).max:
+        max = None
+
+    if out is None:
+        out = wrapped_xp.asarray(xp.broadcast_to(x, result_shape),
+                                 copy=True, device=device(x))
+    if min is not None:
+        if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(min):
+            # Avoid loss of precision due to torch defaulting to float32
+            min = wrapped_xp.asarray(min, dtype=xp.float64)
+        a = xp.broadcast_to(wrapped_xp.asarray(min, device=device(x)), result_shape)
+        ia = (out < a) | xp.isnan(a)
+        # torch requires an explicit cast here
+        out[ia] = wrapped_xp.astype(a[ia], out.dtype)
+    if max is not None:
+        if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(max):
+            max = wrapped_xp.asarray(max, dtype=xp.float64)
+        b = xp.broadcast_to(wrapped_xp.asarray(max, device=device(x)), result_shape)
+        ib = (out > b) | xp.isnan(b)
+        out[ib] = wrapped_xp.astype(b[ib], out.dtype)
+    # Return a scalar for 0-D
+    return out[()]
+
+# Unlike transpose(), the axes argument to permute_dims() is required.
+def permute_dims(x: ndarray, /, axes: Tuple[int, ...], xp) -> ndarray:
+    return xp.transpose(x, axes)
+
+# np.reshape calls the keyword argument 'newshape' instead of 'shape'
+def reshape(x: ndarray,
+            /,
+            shape: Tuple[int, ...],
+            xp, copy: Optional[bool] = None,
+            **kwargs) -> ndarray:
+    if copy is True:
+        x = x.copy()
+    elif copy is False:
+        y = x.view()
+        y.shape = shape
+        return y
+    return xp.reshape(x, shape, **kwargs)
+
+# The descending keyword is new in sort and argsort, and 'kind' replaced with
+# 'stable'
+def argsort(
+    x: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
+    **kwargs,
+) -> ndarray:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs['kind'] = "stable"
+    if not descending:
+        res = xp.argsort(x, axis=axis, **kwargs)
+    else:
+        # As NumPy has no native descending sort, we imitate it here. Note that
+        # simply flipping the results of xp.argsort(x, ...) would not
+        # respect the relative order like it would in native descending sorts.
+        res = xp.flip(
+            xp.argsort(xp.flip(x, axis=axis), axis=axis, **kwargs),
+            axis=axis,
+        )
+        # Rely on flip()/argsort() to validate axis
+        normalised_axis = axis if axis >= 0 else x.ndim + axis
+        max_i = x.shape[normalised_axis] - 1
+        res = max_i - res
+    return res
+
+def sort(
+    x: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
+    **kwargs,
+) -> ndarray:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs['kind'] = "stable"
+    res = xp.sort(x, axis=axis, **kwargs)
+    if descending:
+        res = xp.flip(res, axis=axis)
+    return res
+
+# nonzero should error for zero-dimensional arrays
+def nonzero(x: ndarray, /, xp, **kwargs) -> Tuple[ndarray, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return xp.nonzero(x, **kwargs)
+
+# ceil, floor, and trunc return integers for integer inputs
+
+def ceil(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.ceil(x, **kwargs)
+
+def floor(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.floor(x, **kwargs)
+
+def trunc(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.trunc(x, **kwargs)
+
+# linear algebra functions
+
+def matmul(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
+    return xp.matmul(x1, x2, **kwargs)
+
+# Unlike transpose, matrix_transpose only transposes the last two axes.
+def matrix_transpose(x: ndarray, /, xp) -> ndarray:
+    if x.ndim < 2:
+        raise ValueError("x must be at least 2-dimensional for matrix_transpose")
+    return xp.swapaxes(x, -1, -2)
+
+def tensordot(x1: ndarray,
+              x2: ndarray,
+              /,
+              xp,
+              *,
+              axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2,
+              **kwargs,
+) -> ndarray:
+    return xp.tensordot(x1, x2, axes=axes, **kwargs)
+
+def vecdot(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1) -> ndarray:
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    if hasattr(xp, 'broadcast_tensors'):
+        _broadcast = xp.broadcast_tensors
+    else:
+        _broadcast = xp.broadcast_arrays
+
+    x1_ = xp.moveaxis(x1, axis, -1)
+    x2_ = xp.moveaxis(x2, axis, -1)
+    x1_, x2_ = _broadcast(x1_, x2_)
+
+    res = x1_[..., None, :] @ x2_[..., None]
+    return res[..., 0, 0]
+
+# isdtype is a new function in the 2022.12 array API specification.
+
+def isdtype(
+    dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]], xp,
+    *, _tuple=True, # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return any(isdtype(dtype, k, xp, _tuple=False) for k in kind)
+    elif isinstance(kind, str):
+        if kind == 'bool':
+            return dtype == xp.bool_
+        elif kind == 'signed integer':
+            return xp.issubdtype(dtype, xp.signedinteger)
+        elif kind == 'unsigned integer':
+            return xp.issubdtype(dtype, xp.unsignedinteger)
+        elif kind == 'integral':
+            return xp.issubdtype(dtype, xp.integer)
+        elif kind == 'real floating':
+            return xp.issubdtype(dtype, xp.floating)
+        elif kind == 'complex floating':
+            return xp.issubdtype(dtype, xp.complexfloating)
+        elif kind == 'numeric':
+            return xp.issubdtype(dtype, xp.number)
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        # This will allow things that aren't required by the spec, like
+        # isdtype(np.float64, float) or isdtype(np.int64, 'l'). Should we be
+        # more strict here to match the type annotation? Note that the
+        # array_api_strict implementation will be very strict.
+        return dtype == kind
+
+# unstack is a new function in the 2023.12 array API standard
+def unstack(x: ndarray, /, xp, *, axis: int = 0) -> Tuple[ndarray, ...]:
+    if x.ndim == 0:
+        raise ValueError("Input array must be at least 1-d.")
+    return tuple(xp.moveaxis(x, axis, 0))
+
+# numpy 1.26 does not use the standard definition for sign on complex numbers
+
+def sign(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if isdtype(x.dtype, 'complex floating', xp=xp):
+        out = (x/xp.abs(x, **kwargs))[...]
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0+0j] = 0+0j
+    else:
+        out = xp.sign(x, **kwargs)
+    # CuPy sign() does not propagate nans. See
+    # https://github.com/data-apis/array-api-compat/issues/136
+    if is_cupy_namespace(xp) and isdtype(x.dtype, 'real floating', xp=xp):
+        out[xp.isnan(x)] = xp.nan
+    return out[()]
+
+__all__ = ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like',
+           'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like',
+           'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
+           'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
+           'astype', 'std', 'var', 'cumulative_sum', 'clip', 'permute_dims',
+           'reshape', 'argsort', 'sort', 'nonzero', 'ceil', 'floor', 'trunc',
+           'matmul', 'matrix_transpose', 'tensordot', 'vecdot', 'isdtype',
+           'unstack', 'sign']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..666b0b1f84211052ac23be8a2a3009457b3b19d2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Union, Optional, Literal
+
+if TYPE_CHECKING:
+    from ._typing import Device, ndarray
+    from collections.abc import Sequence
+
+# Note: NumPy fft functions improperly upcast float32 and complex64 to
+# complex128, which is why we require wrapping them all here.
+
+def fft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.fft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.ifft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.fftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.ifftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def rfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.rfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.irfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def rfftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.rfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.irfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def hfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.hfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.float32)
+    return res
+
+def ihfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.ihfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    return xp.fft.fftfreq(n, d=d)
+
+def rfftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    return xp.fft.rfftfreq(n, d=d)
+
+def fftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
+    return xp.fft.fftshift(x, axes=axes)
+
+def ifftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
+    return xp.fft.ifftshift(x, axes=axes)
+
+__all__ = [
+    "fft",
+    "ifft",
+    "fftn",
+    "ifftn",
+    "rfft",
+    "irfft",
+    "rfftn",
+    "irfftn",
+    "hfft",
+    "ihfft",
+    "fftfreq",
+    "rfftfreq",
+    "fftshift",
+    "ifftshift",
+]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..91056e249a30bf1d0f14341c31286d64dad0b676
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
@@ -0,0 +1,825 @@
+"""
+Various helper functions which are not part of the spec.
+
+Functions which start with an underscore are for internal use only but helpers
+that are in __all__ are intended as additional helper functions for use by end
+users of the compat library.
+"""
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional, Union, Any
+    from ._typing import Array, Device
+
+import sys
+import math
+import inspect
+import warnings
+
+def _is_jax_zero_gradient_array(x):
+    """Return True if `x` is a zero-gradient array.
+
+    These arrays are a design quirk of Jax that may one day be removed.
+    See https://github.com/google/jax/issues/20620.
+    """
+    if 'numpy' not in sys.modules or 'jax' not in sys.modules:
+        return False
+
+    import numpy as np
+    import jax
+
+    return isinstance(x, np.ndarray) and x.dtype == jax.float0
+
+def is_numpy_array(x):
+    """
+    Return True if `x` is a NumPy array.
+
+    This function does not import NumPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `ndarray` subclasses and NumPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing NumPy if it isn't already
+    if 'numpy' not in sys.modules:
+        return False
+
+    import numpy as np
+
+    # TODO: Should we reject ndarray subclasses?
+    return (isinstance(x, (np.ndarray, np.generic))
+            and not _is_jax_zero_gradient_array(x))
+
+def is_cupy_array(x):
+    """
+    Return True if `x` is a CuPy array.
+
+    This function does not import CuPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing CuPy if it isn't already
+    if 'cupy' not in sys.modules:
+        return False
+
+    import cupy as cp
+
+    # TODO: Should we reject ndarray subclasses?
+    return isinstance(x, (cp.ndarray, cp.generic))
+
+def is_torch_array(x):
+    """
+    Return True if `x` is a PyTorch tensor.
+
+    This function does not import PyTorch if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing torch if it isn't already
+    if 'torch' not in sys.modules:
+        return False
+
+    import torch
+
+    # TODO: Should we reject ndarray subclasses?
+    return isinstance(x, torch.Tensor)
+
+def is_ndonnx_array(x):
+    """
+    Return True if `x` is a ndonnx Array.
+
+    This function does not import ndonnx if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing torch if it isn't already
+    if 'ndonnx' not in sys.modules:
+        return False
+
+    import ndonnx as ndx
+
+    return isinstance(x, ndx.Array)
+
+def is_dask_array(x):
+    """
+    Return True if `x` is a dask.array Array.
+
+    This function does not import dask if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing dask if it isn't already
+    if 'dask.array' not in sys.modules:
+        return False
+
+    import dask.array
+
+    return isinstance(x, dask.array.Array)
+
+def is_jax_array(x):
+    """
+    Return True if `x` is a JAX array.
+
+    This function does not import JAX if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing jax if it isn't already
+    if 'jax' not in sys.modules:
+        return False
+
+    import jax
+
+    return isinstance(x, jax.Array) or _is_jax_zero_gradient_array(x)
+
+def is_pydata_sparse_array(x) -> bool:
+    """
+    Return True if `x` is an array from the `sparse` package.
+
+    This function does not import `sparse` if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    # Avoid importing jax if it isn't already
+    if 'sparse' not in sys.modules:
+        return False
+
+    import sparse
+
+    # TODO: Account for other backends.
+    return isinstance(x, sparse.SparseArray)
+
+def is_array_api_obj(x):
+    """
+    Return True if `x` is an array API compatible array object.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    return is_numpy_array(x) \
+        or is_cupy_array(x) \
+        or is_torch_array(x) \
+        or is_dask_array(x) \
+        or is_jax_array(x) \
+        or is_pydata_sparse_array(x) \
+        or hasattr(x, '__array_namespace__')
+
+def _compat_module_name():
+    assert __name__.endswith('.common._helpers')
+    return __name__.removesuffix('.common._helpers')
+
+def is_numpy_namespace(xp) -> bool:
+    """
+    Returns True if `xp` is a NumPy namespace.
+
+    This includes both NumPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'numpy', _compat_module_name() + '.numpy'}
+
+def is_cupy_namespace(xp) -> bool:
+    """
+    Returns True if `xp` is a CuPy namespace.
+
+    This includes both CuPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'cupy', _compat_module_name() + '.cupy'}
+
+def is_torch_namespace(xp) -> bool:
+    """
+    Returns True if `xp` is a PyTorch namespace.
+
+    This includes both PyTorch itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'torch', _compat_module_name() + '.torch'}
+
+
+def is_ndonnx_namespace(xp):
+    """
+    Returns True if `xp` is an NDONNX namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == 'ndonnx'
+
+def is_dask_namespace(xp):
+    """
+    Returns True if `xp` is a Dask namespace.
+
+    This includes both ``dask.array`` itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'dask.array', _compat_module_name() + '.dask.array'}
+
+def is_jax_namespace(xp):
+    """
+    Returns True if `xp` is a JAX namespace.
+
+    This includes ``jax.numpy`` and ``jax.experimental.array_api`` which existed in
+    older versions of JAX.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'jax.numpy', 'jax.experimental.array_api'}
+
+def is_pydata_sparse_namespace(xp):
+    """
+    Returns True if `xp` is a pydata/sparse namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == 'sparse'
+
+def is_array_api_strict_namespace(xp):
+    """
+    Returns True if `xp` is an array-api-strict namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    """
+    return xp.__name__ == 'array_api_strict'
+
+def _check_api_version(api_version):
+    if api_version in ['2021.12', '2022.12']:
+        warnings.warn(f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2023.12")
+    elif api_version is not None and api_version not in ['2021.12', '2022.12',
+                                                         '2023.12']:
+        raise ValueError("Only the 2023.12 version of the array API specification is currently supported")
+
+def array_namespace(*xs, api_version=None, use_compat=None):
+    """
+    Get the array API compatible namespace for the arrays `xs`.
+
+    Parameters
+    ----------
+    xs: arrays
+        one or more arrays.
+
+    api_version: str
+        The newest version of the spec that you need support for (currently
+        the compat library wrapped APIs support v2023.12).
+
+    use_compat: bool or None
+        If None (the default), the native namespace will be returned if it is
+        already array API compatible, otherwise a compat wrapper is used. If
+        True, the compat library wrapped library will be returned. If False,
+        the native library namespace is returned.
+
+    Returns
+    -------
+
+    out: namespace
+        The array API compatible namespace corresponding to the arrays in `xs`.
+
+    Raises
+    ------
+    TypeError
+        If `xs` contains arrays from different array libraries or contains a
+        non-array.
+
+
+    Typical usage is to pass the arguments of a function to
+    `array_namespace()` at the top of a function to get the corresponding
+    array API namespace:
+
+    .. code:: python
+
+       def your_function(x, y):
+           xp = array_api_compat.array_namespace(x, y)
+           # Now use xp as the array library namespace
+           return xp.mean(x, axis=0) + 2*xp.std(y, axis=0)
+
+
+    Wrapped array namespaces can also be imported directly. For example,
+    `array_namespace(np.array(...))` will return `array_api_compat.numpy`.
+    This function will also work for any array library not wrapped by
+    array-api-compat if it explicitly defines `__array_namespace__
+    `__
+    (the wrapped namespace is always preferred if it exists).
+
+    See Also
+    --------
+
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+
+    """
+    if use_compat not in [None, True, False]:
+        raise ValueError("use_compat must be None, True, or False")
+
+    _use_compat = use_compat in [None, True]
+
+    namespaces = set()
+    for x in xs:
+        if is_numpy_array(x):
+            from .. import numpy as numpy_namespace
+            import numpy as np
+            if use_compat is True:
+                _check_api_version(api_version)
+                namespaces.add(numpy_namespace)
+            elif use_compat is False:
+                namespaces.add(np)
+            else:
+                # numpy 2.0+ have __array_namespace__, however, they are not yet fully array API
+                # compatible.
+                namespaces.add(numpy_namespace)
+        elif is_cupy_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import cupy as cupy_namespace
+                namespaces.add(cupy_namespace)
+            else:
+                import cupy as cp
+                namespaces.add(cp)
+        elif is_torch_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import torch as torch_namespace
+                namespaces.add(torch_namespace)
+            else:
+                import torch
+                namespaces.add(torch)
+        elif is_dask_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from ..dask import array as dask_namespace
+                namespaces.add(dask_namespace)
+            else:
+                import dask.array as da
+                namespaces.add(da)
+        elif is_jax_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("JAX does not have an array-api-compat wrapper")
+            elif use_compat is False:
+                import jax.numpy as jnp
+            else:
+                # JAX v0.4.32 and newer implements the array API directly in jax.numpy.
+                # For older JAX versions, it is available via jax.experimental.array_api.
+                import jax.numpy
+                if hasattr(jax.numpy, "__array_api_version__"):
+                    jnp = jax.numpy
+                else:
+                    import jax.experimental.array_api as jnp
+            namespaces.add(jnp)
+        elif is_pydata_sparse_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("`sparse` does not have an array-api-compat wrapper")
+            else:
+                import sparse
+            # `sparse` is already an array namespace. We do not have a wrapper
+            # submodule for it.
+            namespaces.add(sparse)
+        elif hasattr(x, '__array_namespace__'):
+            if use_compat is True:
+                raise ValueError("The given array does not have an array-api-compat wrapper")
+            namespaces.add(x.__array_namespace__(api_version=api_version))
+        else:
+            # TODO: Support Python scalars?
+            raise TypeError(f"{type(x).__name__} is not a supported array type")
+
+    if not namespaces:
+        raise TypeError("Unrecognized array input")
+
+    if len(namespaces) != 1:
+        raise TypeError(f"Multiple namespaces for array inputs: {namespaces}")
+
+    xp, = namespaces
+
+    return xp
+
+# backwards compatibility alias
+get_namespace = array_namespace
+
+def _check_device(xp, device):
+    if xp == sys.modules.get('numpy'):
+        if device not in ["cpu", None]:
+            raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+# Placeholder object to represent the dask device
+# when the array backend is not the CPU.
+# (since it is not easy to tell which device a dask array is on)
+class _dask_device:
+    def __repr__(self):
+        return "DASK_DEVICE"
+
+_DASK_DEVICE = _dask_device()
+
+# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray
+# or cupy.ndarray. They are not included in array objects of this library
+# because this library just reuses the respective ndarray classes without
+# wrapping or subclassing them. These helper functions can be used instead of
+# the wrapper functions for libraries that need to support both NumPy/CuPy and
+# other libraries that use devices.
+def device(x: Array, /) -> Device:
+    """
+    Hardware device the array data resides on.
+
+    This is equivalent to `x.device` according to the `standard
+    `__.
+    This helper is included because some array libraries either do not have
+    the `device` attribute or include it with an incompatible API.
+
+    Parameters
+    ----------
+    x: array
+        array instance from an array API compatible library.
+
+    Returns
+    -------
+    out: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    Notes
+    -----
+
+    For NumPy the device is always `"cpu"`. For Dask, the device is always a
+    special `DASK_DEVICE` object.
+
+    See Also
+    --------
+
+    to_device : Move array data to a different device.
+
+    """
+    if is_numpy_array(x):
+        return "cpu"
+    elif is_dask_array(x):
+        # Peek at the metadata of the jax array to determine type
+        try:
+            import numpy as np
+            if isinstance(x._meta, np.ndarray):
+                # Must be on CPU since backed by numpy
+                return "cpu"
+        except ImportError:
+            pass
+        return _DASK_DEVICE
+    elif is_jax_array(x):
+        # JAX has .device() as a method, but it is being deprecated so that it
+        # can become a property, in accordance with the standard. In order for
+        # this function to not break when JAX makes the flip, we check for
+        # both here.
+        if inspect.ismethod(x.device):
+            return x.device()
+        else:
+            return x.device
+    elif is_pydata_sparse_array(x):
+        # `sparse` will gain `.device`, so check for this first.
+        x_device = getattr(x, 'device', None)
+        if x_device is not None:
+            return x_device
+        # Everything but DOK has this attr.
+        try:
+            inner = x.data
+        except AttributeError:
+            return "cpu"
+        # Return the device of the constituent array
+        return device(inner)
+    return x.device
+
+# Prevent shadowing, used below
+_device = device
+
+# Based on cupy.array_api.Array.to_device
+def _cupy_to_device(x, device, /, stream=None):
+    import cupy as cp
+    from cupy.cuda import Device as _Device
+    from cupy.cuda import stream as stream_module
+    from cupy_backends.cuda.api import runtime
+
+    if device == x.device:
+        return x
+    elif device == "cpu":
+        # allowing us to use `to_device(x, "cpu")`
+        # is useful for portable test swapping between
+        # host and device backends
+        return x.get()
+    elif not isinstance(device, _Device):
+        raise ValueError(f"Unsupported device {device!r}")
+    else:
+        # see cupy/cupy#5985 for the reason how we handle device/stream here
+        prev_device = runtime.getDevice()
+        prev_stream: stream_module.Stream = None
+        if stream is not None:
+            prev_stream = stream_module.get_current_stream()
+            # stream can be an int as specified in __dlpack__, or a CuPy stream
+            if isinstance(stream, int):
+                stream = cp.cuda.ExternalStream(stream)
+            elif isinstance(stream, cp.cuda.Stream):
+                pass
+            else:
+                raise ValueError('the input stream is not recognized')
+            stream.use()
+        try:
+            runtime.setDevice(device.id)
+            arr = x.copy()
+        finally:
+            runtime.setDevice(prev_device)
+            if stream is not None:
+                prev_stream.use()
+        return arr
+
+def _torch_to_device(x, device, /, stream=None):
+    if stream is not None:
+        raise NotImplementedError
+    return x.to(device)
+
+def to_device(x: Array, device: Device, /, *, stream: Optional[Union[int, Any]] = None) -> Array:
+    """
+    Copy the array from the device on which it currently resides to the specified ``device``.
+
+    This is equivalent to `x.to_device(device, stream=stream)` according to
+    the `standard
+    `__.
+    This helper is included because some array libraries do not have the
+    `to_device` method.
+
+    Parameters
+    ----------
+
+    x: array
+        array instance from an array API compatible library.
+
+    device: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    stream: Optional[Union[int, Any]]
+        stream object to use during copy. In addition to the types supported
+        in ``array.__dlpack__``, implementations may choose to support any
+        library-specific stream object with the caveat that any code using
+        such an object would not be portable.
+
+    Returns
+    -------
+
+    out: array
+        an array with the same data and data type as ``x`` and located on the
+        specified ``device``.
+
+    Notes
+    -----
+
+    For NumPy, this function effectively does nothing since the only supported
+    device is the CPU. For CuPy, this method supports CuPy CUDA
+    :external+cupy:class:`Device ` and
+    :external+cupy:class:`Stream ` objects. For PyTorch,
+    this is the same as :external+torch:meth:`x.to(device) `
+    (the ``stream`` argument is not supported in PyTorch).
+
+    See Also
+    --------
+
+    device : Hardware device the array data resides on.
+
+    """
+    if is_numpy_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        if device == 'cpu':
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_cupy_array(x):
+        # cupy does not yet have to_device
+        return _cupy_to_device(x, device, stream=stream)
+    elif is_torch_array(x):
+        return _torch_to_device(x, device, stream=stream)
+    elif is_dask_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        # TODO: What if our array is on the GPU already?
+        if device == 'cpu':
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_jax_array(x):
+        if not hasattr(x, "__array_namespace__"):
+            # In JAX v0.4.31 and older, this import adds to_device method to x.
+            import jax.experimental.array_api # noqa: F401
+        return x.to_device(device, stream=stream)
+    elif is_pydata_sparse_array(x) and device == _device(x):
+        # Perform trivial check to return the same array if
+        # device is same instead of err-ing.
+        return x
+    return x.to_device(device, stream=stream)
+
+def size(x):
+    """
+    Return the total number of elements of x.
+
+    This is equivalent to `x.size` according to the `standard
+    `__.
+    This helper is included because PyTorch defines `size` in an
+    :external+torch:meth:`incompatible way `.
+
+    """
+    if None in x.shape:
+        return None
+    return math.prod(x.shape)
+
+__all__ = [
+    "array_namespace",
+    "device",
+    "get_namespace",
+    "is_array_api_obj",
+    "is_array_api_strict_namespace",
+    "is_cupy_array",
+    "is_cupy_namespace",
+    "is_dask_array",
+    "is_dask_namespace",
+    "is_jax_array",
+    "is_jax_namespace",
+    "is_numpy_array",
+    "is_numpy_namespace",
+    "is_torch_array",
+    "is_torch_namespace",
+    "is_ndonnx_array",
+    "is_ndonnx_namespace",
+    "is_pydata_sparse_array",
+    "is_pydata_sparse_namespace",
+    "size",
+    "to_device",
+]
+
+_all_ignore = ['sys', 'math', 'inspect', 'warnings']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1f1b937fddc5c2f95ef3a22850403ffd4b955
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, NamedTuple
+if TYPE_CHECKING:
+    from typing import Literal, Optional, Tuple, Union
+    from ._typing import ndarray
+
+import math
+
+import numpy as np
+if np.__version__[0] == "2":
+    from numpy.lib.array_utils import normalize_axis_tuple
+else:
+    from numpy.core.numeric import normalize_axis_tuple
+
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot, isdtype
+from .._internal import get_xp
+
+# These are in the main NumPy namespace but not in numpy.linalg
+def cross(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1, **kwargs) -> ndarray:
+    return xp.cross(x1, x2, axis=axis, **kwargs)
+
+def outer(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
+    return xp.outer(x1, x2, **kwargs)
+
+class EighResult(NamedTuple):
+    eigenvalues: ndarray
+    eigenvectors: ndarray
+
+class QRResult(NamedTuple):
+    Q: ndarray
+    R: ndarray
+
+class SlogdetResult(NamedTuple):
+    sign: ndarray
+    logabsdet: ndarray
+
+class SVDResult(NamedTuple):
+    U: ndarray
+    S: ndarray
+    Vh: ndarray
+
+# These functions are the same as their NumPy counterparts except they return
+# a namedtuple.
+def eigh(x: ndarray, /, xp, **kwargs) -> EighResult:
+    return EighResult(*xp.linalg.eigh(x, **kwargs))
+
+def qr(x: ndarray, /, xp, *, mode: Literal['reduced', 'complete'] = 'reduced',
+       **kwargs) -> QRResult:
+    return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs))
+
+def slogdet(x: ndarray, /, xp, **kwargs) -> SlogdetResult:
+    return SlogdetResult(*xp.linalg.slogdet(x, **kwargs))
+
+def svd(x: ndarray, /, xp, *, full_matrices: bool = True, **kwargs) -> SVDResult:
+    return SVDResult(*xp.linalg.svd(x, full_matrices=full_matrices, **kwargs))
+
+# These functions have additional keyword arguments
+
+# The upper keyword argument is new from NumPy
+def cholesky(x: ndarray, /, xp, *, upper: bool = False, **kwargs) -> ndarray:
+    L = xp.linalg.cholesky(x, **kwargs)
+    if upper:
+        U = get_xp(xp)(matrix_transpose)(L)
+        if get_xp(xp)(isdtype)(U.dtype, 'complex floating'):
+            U = xp.conj(U)
+        return U
+    return L
+
+# The rtol keyword argument of matrix_rank() and pinv() is new from NumPy.
+# Note that it has a different semantic meaning from tol and rcond.
+def matrix_rank(x: ndarray,
+                /,
+                xp,
+                *,
+                rtol: Optional[Union[float, ndarray]] = None,
+                **kwargs) -> ndarray:
+    # this is different from xp.linalg.matrix_rank, which supports 1
+    # dimensional arrays.
+    if x.ndim < 2:
+        raise xp.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
+    S = get_xp(xp)(svdvals)(x, **kwargs)
+    if rtol is None:
+        tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * xp.finfo(S.dtype).eps
+    else:
+        # this is different from xp.linalg.matrix_rank, which does not
+        # multiply the tolerance by the largest singular value.
+        tol = S.max(axis=-1, keepdims=True)*xp.asarray(rtol)[..., xp.newaxis]
+    return xp.count_nonzero(S > tol, axis=-1)
+
+def pinv(x: ndarray, /, xp, *, rtol: Optional[Union[float, ndarray]] = None, **kwargs) -> ndarray:
+    # this is different from xp.linalg.pinv, which does not multiply the
+    # default tolerance by max(M, N).
+    if rtol is None:
+        rtol = max(x.shape[-2:]) * xp.finfo(x.dtype).eps
+    return xp.linalg.pinv(x, rcond=rtol, **kwargs)
+
+# These functions are new in the array API spec
+
+def matrix_norm(x: ndarray, /, xp, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> ndarray:
+    return xp.linalg.norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord)
+
+# svdvals is not in NumPy (but it is in SciPy). It is equivalent to
+# xp.linalg.svd(compute_uv=False).
+def svdvals(x: ndarray, /, xp) -> Union[ndarray, Tuple[ndarray, ...]]:
+    return xp.linalg.svd(x, compute_uv=False)
+
+def vector_norm(x: ndarray, /, xp, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> ndarray:
+    # xp.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
+    # when axis=None and the input is 2-D, so to force a vector norm, we make
+    # it so the input is 1-D (for axis=None), or reshape so that norm is done
+    # on a single dimension.
+    if axis is None:
+        # Note: xp.linalg.norm() doesn't handle 0-D arrays
+        _x = x.ravel()
+        _axis = 0
+    elif isinstance(axis, tuple):
+        # Note: The axis argument supports any number of axes, whereas
+        # xp.linalg.norm() only supports a single axis for vector norm.
+        normalized_axis = normalize_axis_tuple(axis, x.ndim)
+        rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
+        newshape = axis + rest
+        _x = xp.transpose(x, newshape).reshape(
+            (math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest]))
+        _axis = 0
+    else:
+        _x = x
+        _axis = axis
+
+    res = xp.linalg.norm(_x, axis=_axis, ord=ord)
+
+    if keepdims:
+        # We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks
+        # above to avoid matrix norm logic.
+        shape = list(x.shape)
+        _axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
+        for i in _axis:
+            shape[i] = 1
+        res = xp.reshape(res, tuple(shape))
+
+    return res
+
+# xp.diagonal and xp.trace operate on the first two axes whereas these
+# operates on the last two
+
+def diagonal(x: ndarray, /, xp, *, offset: int = 0, **kwargs) -> ndarray:
+    return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs)
+
+def trace(x: ndarray, /, xp, *, offset: int = 0, dtype=None, **kwargs) -> ndarray:
+    return xp.asarray(xp.trace(x, offset=offset, dtype=dtype, axis1=-2, axis2=-1, **kwargs))
+
+__all__ = ['cross', 'matmul', 'outer', 'tensordot', 'EighResult',
+           'QRResult', 'SlogdetResult', 'SVDResult', 'eigh', 'qr', 'slogdet',
+           'svd', 'cholesky', 'matrix_rank', 'pinv', 'matrix_norm',
+           'matrix_transpose', 'svdvals', 'vecdot', 'vector_norm', 'diagonal',
+           'trace']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..07f3850d21fade94814f9fe1e638286c72a1c552
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+__all__ = [
+    "NestedSequence",
+    "SupportsBufferProtocol",
+]
+
+from typing import (
+    Any,
+    TypeVar,
+    Protocol,
+)
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+class NestedSequence(Protocol[_T_co]):
+    def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
+    def __len__(self, /) -> int: ...
+
+SupportsBufferProtocol = Any
+
+Array = Any
+Device = Any
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d86857618458bf422e7f16dab302b179e5d520d8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
@@ -0,0 +1,16 @@
+from cupy import * # noqa: F403
+
+# from cupy import * doesn't overwrite these builtin names
+from cupy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from ..common._helpers import * # noqa: F401,F403
+
+__array_api_version__ = '2023.12'
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d1e46d2ffd85fb506ca871f2299d00465b66cf8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28bf208594018fb43085ec001784e31a089a57e7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f7f98d96d889073b98a61e4942bfc112c58cd70
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_info.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aeaae6e13f7ec13f04919ca580074dfcb054abef
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/_typing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/fft.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b3a30a29f48f3f69f938181b6f7816e1fb5bdbc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/fft.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adb27d8893eb7ceef251130d270beb6ff56ffaa1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__pycache__/linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..3627fb6b97820c292c86d26b9aabcefd899cfed1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
@@ -0,0 +1,136 @@
+from __future__ import annotations
+
+import cupy as cp
+
+from ..common import _aliases
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+    from ._typing import ndarray, Device, Dtype, NestedSequence, SupportsBufferProtocol
+
+bool = cp.bool_
+
+# Basic renames
+acos = cp.arccos
+acosh = cp.arccosh
+asin = cp.arcsin
+asinh = cp.arcsinh
+atan = cp.arctan
+atan2 = cp.arctan2
+atanh = cp.arctanh
+bitwise_left_shift = cp.left_shift
+bitwise_invert = cp.invert
+bitwise_right_shift = cp.right_shift
+concat = cp.concatenate
+pow = cp.power
+
+arange = get_xp(cp)(_aliases.arange)
+empty = get_xp(cp)(_aliases.empty)
+empty_like = get_xp(cp)(_aliases.empty_like)
+eye = get_xp(cp)(_aliases.eye)
+full = get_xp(cp)(_aliases.full)
+full_like = get_xp(cp)(_aliases.full_like)
+linspace = get_xp(cp)(_aliases.linspace)
+ones = get_xp(cp)(_aliases.ones)
+ones_like = get_xp(cp)(_aliases.ones_like)
+zeros = get_xp(cp)(_aliases.zeros)
+zeros_like = get_xp(cp)(_aliases.zeros_like)
+UniqueAllResult = get_xp(cp)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(cp)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(cp)(_aliases.UniqueInverseResult)
+unique_all = get_xp(cp)(_aliases.unique_all)
+unique_counts = get_xp(cp)(_aliases.unique_counts)
+unique_inverse = get_xp(cp)(_aliases.unique_inverse)
+unique_values = get_xp(cp)(_aliases.unique_values)
+astype = _aliases.astype
+std = get_xp(cp)(_aliases.std)
+var = get_xp(cp)(_aliases.var)
+cumulative_sum = get_xp(cp)(_aliases.cumulative_sum)
+clip = get_xp(cp)(_aliases.clip)
+permute_dims = get_xp(cp)(_aliases.permute_dims)
+reshape = get_xp(cp)(_aliases.reshape)
+argsort = get_xp(cp)(_aliases.argsort)
+sort = get_xp(cp)(_aliases.sort)
+nonzero = get_xp(cp)(_aliases.nonzero)
+ceil = get_xp(cp)(_aliases.ceil)
+floor = get_xp(cp)(_aliases.floor)
+trunc = get_xp(cp)(_aliases.trunc)
+matmul = get_xp(cp)(_aliases.matmul)
+matrix_transpose = get_xp(cp)(_aliases.matrix_transpose)
+tensordot = get_xp(cp)(_aliases.tensordot)
+sign = get_xp(cp)(_aliases.sign)
+
+_copy_default = object()
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Union[
+        ndarray,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: Optional[bool] = _copy_default,
+    **kwargs,
+) -> ndarray:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    with cp.cuda.Device(device):
+        # cupy is like NumPy 1.26 (except without _CopyMode). See the comments
+        # in asarray in numpy/_aliases.py.
+        if copy is not _copy_default:
+            # A future version of CuPy will change the meaning of copy=False
+            # to mean no-copy. We don't know for certain what version it will
+            # be yet, so to avoid breaking that version, we use a different
+            # default value for copy so asarray(obj) with no copy kwarg will
+            # always do the copy-if-needed behavior.
+
+            # This will still need to be updated to remove the
+            # NotImplementedError for copy=False, but at least this won't
+            # break the default or existing behavior.
+            if copy is None:
+                copy = False
+            elif copy is False:
+                raise NotImplementedError("asarray(copy=False) is not yet supported in cupy")
+            kwargs['copy'] = copy
+
+        return cp.array(obj, dtype=dtype, **kwargs)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp, 'vecdot'):
+    vecdot = cp.vecdot
+else:
+    vecdot = get_xp(cp)(_aliases.vecdot)
+
+if hasattr(cp, 'isdtype'):
+    isdtype = cp.isdtype
+else:
+    isdtype = get_xp(cp)(_aliases.isdtype)
+
+if hasattr(cp, 'unstack'):
+    unstack = cp.unstack
+else:
+    unstack = get_xp(cp)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + ['__array_namespace_info__', 'asarray', 'bool',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'concat', 'pow', 'sign']
+
+_all_ignore = ['cp', 'get_xp']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..4440807d2240fb4125229b68a4af8b562b636753
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
@@ -0,0 +1,326 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from cupy import (
+    dtype,
+    cuda,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for CuPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for CuPy.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': cupy.float64,
+     'complex floating': cupy.complex128,
+     'integral': cupy.int64,
+     'indexing': cupy.int64}
+
+    """
+
+    __module__ = 'cupy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for CuPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          CuPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new CuPy arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new CuPy arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        Device(0)
+
+        """
+        return cuda.Device(0)
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new CuPy arrays.
+
+        For CuPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``cupy.float64``
+        - **"complex floating"**: ``cupy.complex128``
+        - **"integral"**: ``cupy.intp``
+        - **"indexing"**: ``cupy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new CuPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': cupy.float64,
+         'complex floating': cupy.complex128,
+         'integral': cupy.int64,
+         'indexing': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by CuPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            CuPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': cupy.int8,
+         'int16': cupy.int16,
+         'int32': cupy.int32,
+         'int64': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by CuPy.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by CuPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        """
+        return [cuda.Device(i) for i in range(cuda.runtime.getDeviceCount())]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3d9aab67e52f3300cd96c3d0e701d1604eaccbb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+__all__ = [
+    "ndarray",
+    "Device",
+    "Dtype",
+]
+
+import sys
+from typing import (
+    Union,
+    TYPE_CHECKING,
+)
+
+from cupy import (
+    ndarray,
+    dtype,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+)
+
+from cupy.cuda.device import Device
+
+if TYPE_CHECKING or sys.version_info >= (3, 9):
+    Dtype = dtype[Union[
+        int8,
+        int16,
+        int32,
+        int64,
+        uint8,
+        uint16,
+        uint32,
+        uint64,
+        float32,
+        float64,
+    ]]
+else:
+    Dtype = dtype
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..307e0f7277710693063ef8c4d2cd7893275ad44a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py
@@ -0,0 +1,36 @@
+from cupy.fft import * # noqa: F403
+# cupy.fft doesn't have __all__. If it is added, replace this with
+#
+# from cupy.fft import __all__ as linalg_all
+_n = {}
+exec('from cupy.fft import *', _n)
+del _n['__builtins__']
+fft_all = list(_n)
+del _n
+
+from ..common import _fft
+from .._internal import get_xp
+
+import cupy as cp
+
+fft = get_xp(cp)(_fft.fft)
+ifft = get_xp(cp)(_fft.ifft)
+fftn = get_xp(cp)(_fft.fftn)
+ifftn = get_xp(cp)(_fft.ifftn)
+rfft = get_xp(cp)(_fft.rfft)
+irfft = get_xp(cp)(_fft.irfft)
+rfftn = get_xp(cp)(_fft.rfftn)
+irfftn = get_xp(cp)(_fft.irfftn)
+hfft = get_xp(cp)(_fft.hfft)
+ihfft = get_xp(cp)(_fft.ihfft)
+fftfreq = get_xp(cp)(_fft.fftfreq)
+rfftfreq = get_xp(cp)(_fft.rfftfreq)
+fftshift = get_xp(cp)(_fft.fftshift)
+ifftshift = get_xp(cp)(_fft.ifftshift)
+
+__all__ = fft_all + _fft.__all__
+
+del get_xp
+del cp
+del fft_all
+del _fft
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fcdd498e0073ada094a20a9ae423e01cb0f8ceb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
@@ -0,0 +1,49 @@
+from cupy.linalg import * # noqa: F403
+# cupy.linalg doesn't have __all__. If it is added, replace this with
+#
+# from cupy.linalg import __all__ as linalg_all
+_n = {}
+exec('from cupy.linalg import *', _n)
+del _n['__builtins__']
+linalg_all = list(_n)
+del _n
+
+from ..common import _linalg
+from .._internal import get_xp
+
+import cupy as cp
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401
+
+cross = get_xp(cp)(_linalg.cross)
+outer = get_xp(cp)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(cp)(_linalg.eigh)
+qr = get_xp(cp)(_linalg.qr)
+slogdet = get_xp(cp)(_linalg.slogdet)
+svd = get_xp(cp)(_linalg.svd)
+cholesky = get_xp(cp)(_linalg.cholesky)
+matrix_rank = get_xp(cp)(_linalg.matrix_rank)
+pinv = get_xp(cp)(_linalg.pinv)
+matrix_norm = get_xp(cp)(_linalg.matrix_norm)
+svdvals = get_xp(cp)(_linalg.svdvals)
+diagonal = get_xp(cp)(_linalg.diagonal)
+trace = get_xp(cp)(_linalg.trace)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp.linalg, 'vector_norm'):
+    vector_norm = cp.linalg.vector_norm
+else:
+    vector_norm = get_xp(cp)(_linalg.vector_norm)
+
+__all__ = linalg_all + _linalg.__all__
+
+del get_xp
+del cp
+del linalg_all
+del _linalg
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a561f6b8c28192532923b8a5dff2069fa8c11da
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49be6cf38f1d905c75278fdb857692f11adcdea
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
@@ -0,0 +1,9 @@
+from dask.array import * # noqa: F403
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+__array_api_version__ = '2023.12'
+
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2fbf9731664369152547cbcac07b6e72e5ce72a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/_aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5777fc9144a99fba861f0c1b332df7604a5705c6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c03a538ae98da598f7248450bce440decfbbb18c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/_info.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/fft.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..642f2c2d37772772c54f4a5951a6990b8c2e4019
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/fft.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a70f0754bc3ad5421ce69f9dbd113bbdaa7b508d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__pycache__/linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee2d88c048b29f603e54818319cb7f7163d43b36
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+
+from ...common import _aliases
+from ...common._helpers import _check_device
+
+from ..._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+import numpy as np
+from numpy import (
+    # Dtypes
+    iinfo,
+    finfo,
+    bool_ as bool,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    complex64,
+    complex128,
+    can_cast,
+    result_type,
+)
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+
+    from ...common._typing import Device, Dtype, Array, NestedSequence, SupportsBufferProtocol
+
+import dask.array as da
+
+isdtype = get_xp(np)(_aliases.isdtype)
+unstack = get_xp(da)(_aliases.unstack)
+astype = _aliases.astype
+
+# Common aliases
+
+# This arange func is modified from the common one to
+# not pass stop/step as keyword arguments, which will cause
+# an error with dask
+
+# TODO: delete the xp stuff, it shouldn't be necessary
+def _dask_arange(
+    start: Union[int, float],
+    /,
+    stop: Optional[Union[int, float]] = None,
+    step: Union[int, float] = 1,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> Array:
+    _check_device(xp, device)
+    args = [start]
+    if stop is not None:
+        args.append(stop)
+    else:
+        # stop is None, so start is actually stop
+        # prepend the default value for start which is 0
+        args.insert(0, 0)
+    args.append(step)
+    return xp.arange(*args, dtype=dtype, **kwargs)
+
+arange = get_xp(da)(_dask_arange)
+eye = get_xp(da)(_aliases.eye)
+
+linspace = get_xp(da)(_aliases.linspace)
+eye = get_xp(da)(_aliases.eye)
+UniqueAllResult = get_xp(da)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(da)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(da)(_aliases.UniqueInverseResult)
+unique_all = get_xp(da)(_aliases.unique_all)
+unique_counts = get_xp(da)(_aliases.unique_counts)
+unique_inverse = get_xp(da)(_aliases.unique_inverse)
+unique_values = get_xp(da)(_aliases.unique_values)
+permute_dims = get_xp(da)(_aliases.permute_dims)
+std = get_xp(da)(_aliases.std)
+var = get_xp(da)(_aliases.var)
+cumulative_sum = get_xp(da)(_aliases.cumulative_sum)
+empty = get_xp(da)(_aliases.empty)
+empty_like = get_xp(da)(_aliases.empty_like)
+full = get_xp(da)(_aliases.full)
+full_like = get_xp(da)(_aliases.full_like)
+ones = get_xp(da)(_aliases.ones)
+ones_like = get_xp(da)(_aliases.ones_like)
+zeros = get_xp(da)(_aliases.zeros)
+zeros_like = get_xp(da)(_aliases.zeros_like)
+reshape = get_xp(da)(_aliases.reshape)
+matrix_transpose = get_xp(da)(_aliases.matrix_transpose)
+vecdot = get_xp(da)(_aliases.vecdot)
+
+nonzero = get_xp(da)(_aliases.nonzero)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Union[
+        Array,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: "Optional[Union[bool, np._CopyMode]]" = None,
+    **kwargs,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    if copy is False:
+        # copy=False is not yet implemented in dask
+        raise NotImplementedError("copy=False is not yet implemented")
+    elif copy is True:
+        if isinstance(obj, da.Array) and dtype is None:
+            return obj.copy()
+        # Go through numpy, since dask copy is no-op by default
+        obj = np.array(obj, dtype=dtype, copy=True)
+        return da.array(obj, dtype=dtype)
+    else:
+        if not isinstance(obj, da.Array) or dtype is not None and obj.dtype != dtype:
+            obj = np.asarray(obj, dtype=dtype)
+            return da.from_array(obj)
+        return obj
+
+    return da.asarray(obj, dtype=dtype, **kwargs)
+
+from dask.array import (
+    # Element wise aliases
+    arccos as acos,
+    arccosh as acosh,
+    arcsin as asin,
+    arcsinh as asinh,
+    arctan as atan,
+    arctan2 as atan2,
+    arctanh as atanh,
+    left_shift as bitwise_left_shift,
+    right_shift as bitwise_right_shift,
+    invert as bitwise_invert,
+    power as pow,
+    # Other
+    concatenate as concat,
+)
+
+# dask.array.clip does not work unless all three arguments are provided.
+# Furthermore, the masking workaround in common._aliases.clip cannot work with
+# dask (meaning uint64 promoting to float64 is going to just be unfixed for
+# now).
+@get_xp(da)
+def clip(
+    x: Array,
+    /,
+    min: Optional[Union[int, float, Array]] = None,
+    max: Optional[Union[int, float, Array]] = None,
+    *,
+    xp,
+) -> Array:
+    def _isscalar(a):
+        return isinstance(a, (int, float, type(None)))
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    # TODO: This won't handle dask unknown shapes
+    import numpy as np
+    result_shape = np.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    if min is not None:
+        min = xp.broadcast_to(xp.asarray(min), result_shape)
+    if max is not None:
+        max = xp.broadcast_to(xp.asarray(max), result_shape)
+
+    if min is None and max is None:
+        return xp.positive(x)
+
+    if min is None:
+        return astype(xp.minimum(x, max), x.dtype)
+    if max is None:
+        return astype(xp.maximum(x, min), x.dtype)
+
+    return astype(xp.minimum(xp.maximum(x, min), max), x.dtype)
+
+# exclude these from all since dask.array has no sorting functions
+_da_unsupported = ['sort', 'argsort']
+
+_common_aliases = [alias for alias in _aliases.__all__ if alias not in _da_unsupported]
+
+__all__ = _common_aliases + ['__array_namespace_info__', 'asarray', 'acos',
+                    'acosh', 'asin', 'asinh', 'atan', 'atan2',
+                    'atanh', 'bitwise_left_shift', 'bitwise_invert',
+                    'bitwise_right_shift', 'concat', 'pow', 'iinfo', 'finfo', 'can_cast',
+                    'result_type', 'bool', 'float32', 'float64', 'int8', 'int16', 'int32', 'int64',
+                    'uint8', 'uint16', 'uint32', 'uint64',
+                    'complex64', 'complex128', 'iinfo', 'finfo',
+                    'can_cast', 'result_type']
+
+_all_ignore = ["get_xp", "da", "np"]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3b12dc960f5a7a5d5a8dfb3345c0ad1f4d470e7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
@@ -0,0 +1,345 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from numpy import (
+    dtype,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+from ...common._helpers import _DASK_DEVICE
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for Dask.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for Dask.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': dask.float64,
+     'complex floating': dask.complex128,
+     'integral': dask.int64,
+     'indexing': dask.int64}
+
+    """
+
+    __module__ = 'dask.array'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``False`` for Dask.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``False`` for
+          Dask.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": False,
+            "data-dependent shapes": False,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new Dask arrays.
+
+        For Dask, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new Dask arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new Dask arrays.
+
+        For Dask, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new Dask
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': dask.float64,
+         'complex floating': dask.complex128,
+         'integral': dask.int64,
+         'indexing': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE is allowed, but received:'
+                f' {device}'
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by Dask.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            Dask data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': dask.int8,
+         'int16': dask.int16,
+         'int32': dask.int32,
+         'int64': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE is allowed, but received:'
+                f' {device}'
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by Dask.
+
+        For Dask, this always returns ``['cpu', DASK_DEVICE]``.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by Dask.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu', DASK_DEVICE]
+
+        """
+        return ["cpu", _DASK_DEVICE]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..aebd86f7b201d9eb7cd707b25ab3fae117f2d6e5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
@@ -0,0 +1,24 @@
+from dask.array.fft import * # noqa: F403
+# dask.array.fft doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.fft import __all__ as linalg_all
+_n = {}
+exec('from dask.array.fft import *', _n)
+del _n['__builtins__']
+fft_all = list(_n)
+del _n
+
+from ...common import _fft
+from ..._internal import get_xp
+
+import dask.array as da
+
+fftfreq = get_xp(da)(_fft.fftfreq)
+rfftfreq = get_xp(da)(_fft.rfftfreq)
+
+__all__ = [elem for elem in fft_all if elem != "annotations"] + ["fftfreq", "rfftfreq"]
+
+del get_xp
+del da
+del fft_all
+del _fft
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c26d8b819f88e226e34e02947a1ecf50c4895e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from ...common import _linalg
+from ..._internal import get_xp
+
+# Exports
+from dask.array.linalg import * # noqa: F403
+from dask.array import outer
+
+# These functions are in both the main and linalg namespaces
+from dask.array import matmul, tensordot
+from ._aliases import matrix_transpose, vecdot
+
+import dask.array as da
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from ...common._typing import Array
+    from typing import Literal
+
+# dask.array.linalg doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.linalg import __all__ as linalg_all
+_n = {}
+exec('from dask.array.linalg import *', _n)
+del _n['__builtins__']
+if 'annotations' in _n:
+    del _n['annotations']
+linalg_all = list(_n)
+del _n
+
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+# TODO: use the QR wrapper once dask
+# supports the mode keyword on QR
+# https://github.com/dask/dask/issues/10388
+#qr = get_xp(da)(_linalg.qr)
+def qr(x: Array, mode: Literal['reduced', 'complete'] = 'reduced',
+       **kwargs) -> QRResult:
+    if mode != "reduced":
+        raise ValueError("dask arrays only support using mode='reduced'")
+    return QRResult(*da.linalg.qr(x, **kwargs))
+trace = get_xp(da)(_linalg.trace)
+cholesky = get_xp(da)(_linalg.cholesky)
+matrix_rank = get_xp(da)(_linalg.matrix_rank)
+matrix_norm = get_xp(da)(_linalg.matrix_norm)
+
+
+# Wrap the svd functions to not pass full_matrices to dask
+# when full_matrices=False (as that is the default behavior for dask),
+# and dask doesn't have the full_matrices keyword
+def svd(x: Array, full_matrices: bool = True, **kwargs) -> SVDResult:
+    if full_matrices:
+        raise ValueError("full_matrics=True is not supported by dask.")
+    return da.linalg.svd(x, coerce_signs=False, **kwargs)
+
+def svdvals(x: Array) -> Array:
+    # TODO: can't avoid computing U or V for dask
+    _, s, _ =  svd(x)
+    return s
+
+vector_norm = get_xp(da)(_linalg.vector_norm)
+diagonal = get_xp(da)(_linalg.diagonal)
+
+__all__ = linalg_all + ["trace", "outer", "matmul", "tensordot",
+                        "matrix_transpose", "vecdot", "EighResult",
+                        "QRResult", "SlogdetResult", "SVDResult", "qr",
+                        "cholesky", "matrix_rank", "matrix_norm", "svdvals",
+                        "vector_norm", "diagonal"]
+
+_all_ignore = ['get_xp', 'da', 'linalg_all']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bdbf31293d480f8a8a266dd096e6aa92e1cc48e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
@@ -0,0 +1,30 @@
+from numpy import * # noqa: F403
+
+# from numpy import * doesn't overwrite these builtin names
+from numpy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# Don't know why, but we have to do an absolute import to import linalg. If we
+# instead do
+#
+# from . import linalg
+#
+# It doesn't overwrite np.linalg from above. The import is generated
+# dynamically so that the library can be vendored.
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from .linalg import matrix_transpose, vecdot # noqa: F401
+
+from ..common._helpers import * # noqa: F403
+
+try:
+    # Used in asarray(). Not present in older versions.
+    from numpy import _CopyMode # noqa: F401
+except ImportError:
+    pass
+
+__array_api_version__ = '2023.12'
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a19058175ebd118993dad34c2c11b9ca60a5e4b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15f0f1cba6f37c69d0c7088df0a1513011db30e8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97a2abcda0636912a709c975c495e6681f3f775c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c0c8588c0bef93fea262efc360f0d40aa4505a2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a90b93009edd5d76e9400ce1d14b99ccac440bb2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cc9673b4e58efb74455b9fbad5451c3837b4c85
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bfc98ff7ba4082a3986652b85dc15fdd85350ad
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+from ..common import _aliases
+
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+    from ._typing import ndarray, Device, Dtype, NestedSequence, SupportsBufferProtocol
+
+import numpy as np
+bool = np.bool_
+
+# Basic renames
+acos = np.arccos
+acosh = np.arccosh
+asin = np.arcsin
+asinh = np.arcsinh
+atan = np.arctan
+atan2 = np.arctan2
+atanh = np.arctanh
+bitwise_left_shift = np.left_shift
+bitwise_invert = np.invert
+bitwise_right_shift = np.right_shift
+concat = np.concatenate
+pow = np.power
+
+arange = get_xp(np)(_aliases.arange)
+empty = get_xp(np)(_aliases.empty)
+empty_like = get_xp(np)(_aliases.empty_like)
+eye = get_xp(np)(_aliases.eye)
+full = get_xp(np)(_aliases.full)
+full_like = get_xp(np)(_aliases.full_like)
+linspace = get_xp(np)(_aliases.linspace)
+ones = get_xp(np)(_aliases.ones)
+ones_like = get_xp(np)(_aliases.ones_like)
+zeros = get_xp(np)(_aliases.zeros)
+zeros_like = get_xp(np)(_aliases.zeros_like)
+UniqueAllResult = get_xp(np)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(np)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(np)(_aliases.UniqueInverseResult)
+unique_all = get_xp(np)(_aliases.unique_all)
+unique_counts = get_xp(np)(_aliases.unique_counts)
+unique_inverse = get_xp(np)(_aliases.unique_inverse)
+unique_values = get_xp(np)(_aliases.unique_values)
+astype = _aliases.astype
+std = get_xp(np)(_aliases.std)
+var = get_xp(np)(_aliases.var)
+cumulative_sum = get_xp(np)(_aliases.cumulative_sum)
+clip = get_xp(np)(_aliases.clip)
+permute_dims = get_xp(np)(_aliases.permute_dims)
+reshape = get_xp(np)(_aliases.reshape)
+argsort = get_xp(np)(_aliases.argsort)
+sort = get_xp(np)(_aliases.sort)
+nonzero = get_xp(np)(_aliases.nonzero)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+matrix_transpose = get_xp(np)(_aliases.matrix_transpose)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+
+def _supports_buffer_protocol(obj):
+    try:
+        memoryview(obj)
+    except TypeError:
+        return False
+    return True
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+# asarray() is different enough between numpy, cupy, and dask, the logic
+# complicated enough that it's easier to define it separately for each module
+# rather than trying to combine everything into one function in common/
+def asarray(
+    obj: Union[
+        ndarray,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: "Optional[Union[bool, np._CopyMode]]" = None,
+    **kwargs,
+) -> ndarray:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+    if hasattr(np, '_CopyMode'):
+        if copy is None:
+            copy = np._CopyMode.IF_NEEDED
+        elif copy is False:
+            copy = np._CopyMode.NEVER
+        elif copy is True:
+            copy = np._CopyMode.ALWAYS
+    else:
+        # Not present in older NumPys. In this case, we cannot really support
+        # copy=False.
+        if copy is False:
+            raise NotImplementedError("asarray(copy=False) requires a newer version of NumPy.")
+
+    return np.array(obj, copy=copy, dtype=dtype, **kwargs)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np, 'vecdot'):
+    vecdot = np.vecdot
+else:
+    vecdot = get_xp(np)(_aliases.vecdot)
+
+if hasattr(np, 'isdtype'):
+    isdtype = np.isdtype
+else:
+    isdtype = get_xp(np)(_aliases.isdtype)
+
+if hasattr(np, 'unstack'):
+    unstack = np.unstack
+else:
+    unstack = get_xp(np)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + ['__array_namespace_info__', 'asarray', 'bool',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'concat', 'pow']
+
+_all_ignore = ['np', 'get_xp']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..62f7ae62ca242cc17def5703b4412823aa31abcd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
@@ -0,0 +1,346 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from numpy import (
+    dtype,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for NumPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for NumPy.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'numpy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for NumPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          NumPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new NumPy arrays.
+
+        For NumPy, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new NumPy arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new NumPy arrays.
+
+        For NumPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For NumPy, only
+            ``'cpu'`` is allowed.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new NumPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': numpy.float64,
+         'complex floating': numpy.complex128,
+         'integral': numpy.int64,
+         'indexing': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by NumPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for. For NumPy, only ``'cpu'`` is
+            allowed.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            NumPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by NumPy.
+
+        For NumPy, this always returns ``['cpu']``.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by NumPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu']
+
+        """
+        return ["cpu"]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5ebb5abb987572be625ee864a37e61126d36d8b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+__all__ = [
+    "ndarray",
+    "Device",
+    "Dtype",
+]
+
+import sys
+from typing import (
+    Literal,
+    Union,
+    TYPE_CHECKING,
+)
+
+from numpy import (
+    ndarray,
+    dtype,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+)
+
+Device = Literal["cpu"]
+if TYPE_CHECKING or sys.version_info >= (3, 9):
+    Dtype = dtype[Union[
+        int8,
+        int16,
+        int32,
+        int64,
+        uint8,
+        uint16,
+        uint32,
+        uint64,
+        float32,
+        float64,
+    ]]
+else:
+    Dtype = dtype
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..286675946e0fbb0aa18105d25db08ebbbd2e4d0c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
@@ -0,0 +1,29 @@
+from numpy.fft import * # noqa: F403
+from numpy.fft import __all__ as fft_all
+
+from ..common import _fft
+from .._internal import get_xp
+
+import numpy as np
+
+fft = get_xp(np)(_fft.fft)
+ifft = get_xp(np)(_fft.ifft)
+fftn = get_xp(np)(_fft.fftn)
+ifftn = get_xp(np)(_fft.ifftn)
+rfft = get_xp(np)(_fft.rfft)
+irfft = get_xp(np)(_fft.irfft)
+rfftn = get_xp(np)(_fft.rfftn)
+irfftn = get_xp(np)(_fft.irfftn)
+hfft = get_xp(np)(_fft.hfft)
+ihfft = get_xp(np)(_fft.ihfft)
+fftfreq = get_xp(np)(_fft.fftfreq)
+rfftfreq = get_xp(np)(_fft.rfftfreq)
+fftshift = get_xp(np)(_fft.fftshift)
+ifftshift = get_xp(np)(_fft.ifftshift)
+
+__all__ = fft_all + _fft.__all__
+
+del get_xp
+del np
+del fft_all
+del _fft
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f01593bd0ae619b3bea471980b4eeabfc29f319
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
@@ -0,0 +1,90 @@
+from numpy.linalg import * # noqa: F403
+from numpy.linalg import __all__ as linalg_all
+import numpy as _np
+
+from ..common import _linalg
+from .._internal import get_xp
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401
+
+import numpy as np
+
+cross = get_xp(np)(_linalg.cross)
+outer = get_xp(np)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(np)(_linalg.eigh)
+qr = get_xp(np)(_linalg.qr)
+slogdet = get_xp(np)(_linalg.slogdet)
+svd = get_xp(np)(_linalg.svd)
+cholesky = get_xp(np)(_linalg.cholesky)
+matrix_rank = get_xp(np)(_linalg.matrix_rank)
+pinv = get_xp(np)(_linalg.pinv)
+matrix_norm = get_xp(np)(_linalg.matrix_norm)
+svdvals = get_xp(np)(_linalg.svdvals)
+diagonal = get_xp(np)(_linalg.diagonal)
+trace = get_xp(np)(_linalg.trace)
+
+# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
+# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
+# of matrices. The np.linalg.solve behavior of allowing stacks of both
+# matrices and vectors is ambiguous c.f.
+# https://github.com/numpy/numpy/issues/15349 and
+# https://github.com/data-apis/array-api/issues/285.
+
+# To workaround this, the below is the code from np.linalg.solve except
+# only calling solve1 in the exactly 1D case.
+
+# This code is here instead of in common because it is numpy specific. Also
+# note that CuPy's solve() does not currently support broadcasting (see
+# https://github.com/cupy/cupy/blob/main/cupy/cublas.py#L43).
+def solve(x1: _np.ndarray, x2: _np.ndarray, /) -> _np.ndarray:
+    try:
+        from numpy.linalg._linalg import (
+        _makearray, _assert_stacked_2d, _assert_stacked_square,
+        _commonType, isComplexType, _raise_linalgerror_singular
+        )
+    except ImportError:
+        from numpy.linalg.linalg import (
+        _makearray, _assert_stacked_2d, _assert_stacked_square,
+        _commonType, isComplexType, _raise_linalgerror_singular
+        )
+    from numpy.linalg import _umath_linalg
+
+    x1, _ = _makearray(x1)
+    _assert_stacked_2d(x1)
+    _assert_stacked_square(x1)
+    x2, wrap = _makearray(x2)
+    t, result_t = _commonType(x1, x2)
+
+    # This part is different from np.linalg.solve
+    if x2.ndim == 1:
+        gufunc = _umath_linalg.solve1
+    else:
+        gufunc = _umath_linalg.solve
+
+    # This does nothing currently but is left in because it will be relevant
+    # when complex dtype support is added to the spec in 2022.
+    signature = 'DD->D' if isComplexType(t) else 'dd->d'
+    with _np.errstate(call=_raise_linalgerror_singular, invalid='call',
+                      over='ignore', divide='ignore', under='ignore'):
+        r = gufunc(x1, x2, signature=signature)
+
+    return wrap(r.astype(result_t, copy=False))
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np.linalg, 'vector_norm'):
+    vector_norm = np.linalg.vector_norm
+else:
+    vector_norm = get_xp(np)(_linalg.vector_norm)
+
+__all__ = linalg_all + _linalg.__all__ + ['solve']
+
+del get_xp
+del np
+del linalg_all
+del _linalg
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfa3acf8945a84c8e3fcdc892edc19d4f674cd30
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
@@ -0,0 +1,24 @@
+from torch import * # noqa: F403
+
+# Several names are not included in the above import *
+import torch
+for n in dir(torch):
+    if (n.startswith('_')
+        or n.endswith('_')
+        or 'cuda' in n
+        or 'cpu' in n
+        or 'backward' in n):
+        continue
+    exec(n + ' = torch.' + n)
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from ..common._helpers import * # noqa: F403
+
+__array_api_version__ = '2023.12'
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53fce8975dc7b22511a56918591a2b43442f2c52
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/_aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cdff98f69ca42d41a29cd32b3de8ed63d3a8428
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7106e8855c6759d4b1fbe5d8606613b15c35d44
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/_info.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/fft.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6bed25d0c1ab16a62aef1383365d51d81dd41bf2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/fft.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ee9b229c944397d598234d6a9483db2808443b7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__pycache__/linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ac66bcb17e6f13a51bd6c7fd345bee23c16140f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
@@ -0,0 +1,752 @@
+from __future__ import annotations
+
+from functools import wraps as _wraps
+from builtins import all as _builtin_all, any as _builtin_any
+
+from ..common._aliases import (matrix_transpose as _aliases_matrix_transpose,
+                               vecdot as _aliases_vecdot,
+                               clip as _aliases_clip,
+                               unstack as _aliases_unstack,
+                               cumulative_sum as _aliases_cumulative_sum,
+                               )
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+import torch
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import List, Optional, Sequence, Tuple, Union
+    from ..common._typing import Device
+    from torch import dtype as Dtype
+
+    array = torch.Tensor
+
+_int_dtypes = {
+    torch.uint8,
+    torch.int8,
+    torch.int16,
+    torch.int32,
+    torch.int64,
+}
+
+_array_api_dtypes = {
+    torch.bool,
+    *_int_dtypes,
+    torch.float32,
+    torch.float64,
+    torch.complex64,
+    torch.complex128,
+}
+
+_promotion_table  = {
+    # bool
+    (torch.bool, torch.bool): torch.bool,
+    # ints
+    (torch.int8, torch.int8): torch.int8,
+    (torch.int8, torch.int16): torch.int16,
+    (torch.int8, torch.int32): torch.int32,
+    (torch.int8, torch.int64): torch.int64,
+    (torch.int16, torch.int8): torch.int16,
+    (torch.int16, torch.int16): torch.int16,
+    (torch.int16, torch.int32): torch.int32,
+    (torch.int16, torch.int64): torch.int64,
+    (torch.int32, torch.int8): torch.int32,
+    (torch.int32, torch.int16): torch.int32,
+    (torch.int32, torch.int32): torch.int32,
+    (torch.int32, torch.int64): torch.int64,
+    (torch.int64, torch.int8): torch.int64,
+    (torch.int64, torch.int16): torch.int64,
+    (torch.int64, torch.int32): torch.int64,
+    (torch.int64, torch.int64): torch.int64,
+    # uints
+    (torch.uint8, torch.uint8): torch.uint8,
+    # ints and uints (mixed sign)
+    (torch.int8, torch.uint8): torch.int16,
+    (torch.int16, torch.uint8): torch.int16,
+    (torch.int32, torch.uint8): torch.int32,
+    (torch.int64, torch.uint8): torch.int64,
+    (torch.uint8, torch.int8): torch.int16,
+    (torch.uint8, torch.int16): torch.int16,
+    (torch.uint8, torch.int32): torch.int32,
+    (torch.uint8, torch.int64): torch.int64,
+    # floats
+    (torch.float32, torch.float32): torch.float32,
+    (torch.float32, torch.float64): torch.float64,
+    (torch.float64, torch.float32): torch.float64,
+    (torch.float64, torch.float64): torch.float64,
+    # complexes
+    (torch.complex64, torch.complex64): torch.complex64,
+    (torch.complex64, torch.complex128): torch.complex128,
+    (torch.complex128, torch.complex64): torch.complex128,
+    (torch.complex128, torch.complex128): torch.complex128,
+    # Mixed float and complex
+    (torch.float32, torch.complex64): torch.complex64,
+    (torch.float32, torch.complex128): torch.complex128,
+    (torch.float64, torch.complex64): torch.complex128,
+    (torch.float64, torch.complex128): torch.complex128,
+}
+
+
+def _two_arg(f):
+    @_wraps(f)
+    def _f(x1, x2, /, **kwargs):
+        x1, x2 = _fix_promotion(x1, x2)
+        return f(x1, x2, **kwargs)
+    if _f.__doc__ is None:
+        _f.__doc__ = f"""\
+Array API compatibility wrapper for torch.{f.__name__}.
+
+See the corresponding PyTorch documentation and/or the array API specification
+for more details.
+
+"""
+    return _f
+
+def _fix_promotion(x1, x2, only_scalar=True):
+    if not isinstance(x1, torch.Tensor) or not isinstance(x2, torch.Tensor):
+        return x1, x2
+    if x1.dtype not in _array_api_dtypes or x2.dtype not in _array_api_dtypes:
+        return x1, x2
+    # If an argument is 0-D pytorch downcasts the other argument
+    if not only_scalar or x1.shape == ():
+        dtype = result_type(x1, x2)
+        x2 = x2.to(dtype)
+    if not only_scalar or x2.shape == ():
+        dtype = result_type(x1, x2)
+        x1 = x1.to(dtype)
+    return x1, x2
+
+def result_type(*arrays_and_dtypes: Union[array, Dtype]) -> Dtype:
+    if len(arrays_and_dtypes) == 0:
+        raise TypeError("At least one array or dtype must be provided")
+    if len(arrays_and_dtypes) == 1:
+        x = arrays_and_dtypes[0]
+        if isinstance(x, torch.dtype):
+            return x
+        return x.dtype
+    if len(arrays_and_dtypes) > 2:
+        return result_type(arrays_and_dtypes[0], result_type(*arrays_and_dtypes[1:]))
+
+    x, y = arrays_and_dtypes
+    xdt = x.dtype if not isinstance(x, torch.dtype) else x
+    ydt = y.dtype if not isinstance(y, torch.dtype) else y
+
+    if (xdt, ydt) in _promotion_table:
+        return _promotion_table[xdt, ydt]
+
+    # This doesn't result_type(dtype, dtype) for non-array API dtypes
+    # because torch.result_type only accepts tensors. This does however, allow
+    # cross-kind promotion.
+    x = torch.tensor([], dtype=x) if isinstance(x, torch.dtype) else x
+    y = torch.tensor([], dtype=y) if isinstance(y, torch.dtype) else y
+    return torch.result_type(x, y)
+
+def can_cast(from_: Union[Dtype, array], to: Dtype, /) -> bool:
+    if not isinstance(from_, torch.dtype):
+        from_ = from_.dtype
+    return torch.can_cast(from_, to)
+
+# Basic renames
+bitwise_invert = torch.bitwise_not
+newaxis = None
+# torch.conj sets the conjugation bit, which breaks conversion to other
+# libraries. See https://github.com/data-apis/array-api-compat/issues/173
+conj = torch.conj_physical
+
+# Two-arg elementwise functions
+# These require a wrapper to do the correct type promotion on 0-D tensors
+add = _two_arg(torch.add)
+atan2 = _two_arg(torch.atan2)
+bitwise_and = _two_arg(torch.bitwise_and)
+bitwise_left_shift = _two_arg(torch.bitwise_left_shift)
+bitwise_or = _two_arg(torch.bitwise_or)
+bitwise_right_shift = _two_arg(torch.bitwise_right_shift)
+bitwise_xor = _two_arg(torch.bitwise_xor)
+copysign = _two_arg(torch.copysign)
+divide = _two_arg(torch.divide)
+# Also a rename. torch.equal does not broadcast
+equal = _two_arg(torch.eq)
+floor_divide = _two_arg(torch.floor_divide)
+greater = _two_arg(torch.greater)
+greater_equal = _two_arg(torch.greater_equal)
+hypot = _two_arg(torch.hypot)
+less = _two_arg(torch.less)
+less_equal = _two_arg(torch.less_equal)
+logaddexp = _two_arg(torch.logaddexp)
+# logical functions are not included here because they only accept bool in the
+# spec, so type promotion is irrelevant.
+maximum = _two_arg(torch.maximum)
+minimum = _two_arg(torch.minimum)
+multiply = _two_arg(torch.multiply)
+not_equal = _two_arg(torch.not_equal)
+pow = _two_arg(torch.pow)
+remainder = _two_arg(torch.remainder)
+subtract = _two_arg(torch.subtract)
+
+# These wrappers are mostly based on the fact that pytorch uses 'dim' instead
+# of 'axis'.
+
+# torch.min and torch.max return a tuple and don't support multiple axes https://github.com/pytorch/pytorch/issues/58745
+def max(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False) -> array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amax(x, axis, keepdims=keepdims)
+
+def min(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False) -> array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amin(x, axis, keepdims=keepdims)
+
+clip = get_xp(torch)(_aliases_clip)
+unstack = get_xp(torch)(_aliases_unstack)
+cumulative_sum = get_xp(torch)(_aliases_cumulative_sum)
+
+# torch.sort also returns a tuple
+# https://github.com/pytorch/pytorch/issues/70921
+def sort(x: array, /, *, axis: int = -1, descending: bool = False, stable: bool = True, **kwargs) -> array:
+    return torch.sort(x, dim=axis, descending=descending, stable=stable, **kwargs).values
+
+def _normalize_axes(axis, ndim):
+    axes = []
+    if ndim == 0 and axis:
+        # Better error message in this case
+        raise IndexError(f"Dimension out of range: {axis[0]}")
+    lower, upper = -ndim, ndim - 1
+    for a in axis:
+        if a < lower or a > upper:
+            # Match torch error message (e.g., from sum())
+            raise IndexError(f"Dimension out of range (expected to be in range of [{lower}, {upper}], but got {a}")
+        if a < 0:
+            a = a + ndim
+        if a in axes:
+            # Use IndexError instead of RuntimeError, and "axis" instead of "dim"
+            raise IndexError(f"Axis {a} appears multiple times in the list of axes")
+        axes.append(a)
+    return sorted(axes)
+
+def _axis_none_keepdims(x, ndim, keepdims):
+    # Apply keepdims when axis=None
+    # (https://github.com/pytorch/pytorch/issues/71209)
+    # Note that this is only valid for the axis=None case.
+    if keepdims:
+        for i in range(ndim):
+            x = torch.unsqueeze(x, 0)
+    return x
+
+def _reduce_multiple_axes(f, x, axis, keepdims=False, **kwargs):
+    # Some reductions don't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    axes = _normalize_axes(axis, x.ndim)
+    for a in reversed(axes):
+        x = torch.movedim(x, a, -1)
+    x = torch.flatten(x, -len(axes))
+
+    out = f(x, -1, **kwargs)
+
+    if keepdims:
+        for a in axes:
+            out = torch.unsqueeze(out, a)
+    return out
+
+def prod(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[Dtype] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+
+    # https://github.com/pytorch/pytorch/issues/29137. Separate from the logic
+    # below because it still needs to upcast.
+    if axis == ():
+        if dtype is None:
+            # We can't upcast uint8 according to the spec because there is no
+            # torch.uint64, so at least upcast to int64 which is what sum does
+            # when axis=None.
+            if x.dtype in [torch.int8, torch.int16, torch.int32, torch.uint8]:
+                return x.to(torch.int64)
+            return x.clone()
+        return x.to(dtype)
+
+    # torch.prod doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        return _reduce_multiple_axes(torch.prod, x, axis, keepdims=keepdims, dtype=dtype, **kwargs)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.prod(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res
+
+    return torch.prod(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+
+def sum(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[Dtype] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+
+    # https://github.com/pytorch/pytorch/issues/29137.
+    # Make sure it upcasts.
+    if axis == ():
+        if dtype is None:
+            # We can't upcast uint8 according to the spec because there is no
+            # torch.uint64, so at least upcast to int64 which is what sum does
+            # when axis=None.
+            if x.dtype in [torch.int8, torch.int16, torch.int32, torch.uint8]:
+                return x.to(torch.int64)
+            return x.clone()
+        return x.to(dtype)
+
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.sum(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res
+
+    return torch.sum(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+def any(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.any doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.any, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.any(x, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.any doesn't return bool for uint8
+    return torch.any(x, axis, keepdims=keepdims).to(torch.bool)
+
+def all(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.all doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.all, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.all(x, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.all doesn't return bool for uint8
+    return torch.all(x, axis, keepdims=keepdims).to(torch.bool)
+
+def mean(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.mean(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.mean(x, axis, keepdims=keepdims, **kwargs)
+
+def std(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    if isinstance(correction, float):
+        _correction = int(correction)
+        if correction != _correction:
+            raise NotImplementedError("float correction in torch std() is not yet supported")
+    else:
+        _correction = correction
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.std(x, tuple(range(x.ndim)), correction=_correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.std(x, axis, correction=_correction, keepdims=keepdims, **kwargs)
+
+def var(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    # if isinstance(correction, float):
+    #     correction = int(correction)
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.var(x, tuple(range(x.ndim)), correction=correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.var(x, axis, correction=correction, keepdims=keepdims, **kwargs)
+
+# torch.concat doesn't support dim=None
+# https://github.com/pytorch/pytorch/issues/70925
+def concat(arrays: Union[Tuple[array, ...], List[array]],
+           /,
+           *,
+           axis: Optional[int] = 0,
+           **kwargs) -> array:
+    if axis is None:
+        arrays = tuple(ar.flatten() for ar in arrays)
+        axis = 0
+    return torch.concat(arrays, axis, **kwargs)
+
+# torch.squeeze only accepts int dim and doesn't require it
+# https://github.com/pytorch/pytorch/issues/70924. Support for tuple dim was
+# added at https://github.com/pytorch/pytorch/pull/89017.
+def squeeze(x: array, /, axis: Union[int, Tuple[int, ...]]) -> array:
+    if isinstance(axis, int):
+        axis = (axis,)
+    for a in axis:
+        if x.shape[a] != 1:
+            raise ValueError("squeezed dimensions must be equal to 1")
+    axes = _normalize_axes(axis, x.ndim)
+    # Remove this once pytorch 1.14 is released with the above PR #89017.
+    sequence = [a - i for i, a in enumerate(axes)]
+    for a in sequence:
+        x = torch.squeeze(x, a)
+    return x
+
+# torch.broadcast_to uses size instead of shape
+def broadcast_to(x: array, /, shape: Tuple[int, ...], **kwargs) -> array:
+    return torch.broadcast_to(x, shape, **kwargs)
+
+# torch.permute uses dims instead of axes
+def permute_dims(x: array, /, axes: Tuple[int, ...]) -> array:
+    return torch.permute(x, axes)
+
+# The axis parameter doesn't work for flip() and roll()
+# https://github.com/pytorch/pytorch/issues/71210. Also torch.flip() doesn't
+# accept axis=None
+def flip(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> array:
+    if axis is None:
+        axis = tuple(range(x.ndim))
+    # torch.flip doesn't accept dim as an int but the method does
+    # https://github.com/pytorch/pytorch/issues/18095
+    return x.flip(axis, **kwargs)
+
+def roll(x: array, /, shift: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> array:
+    return torch.roll(x, shift, axis, **kwargs)
+
+def nonzero(x: array, /, **kwargs) -> Tuple[array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return torch.nonzero(x, as_tuple=True, **kwargs)
+
+def where(condition: array, x1: array, x2: array, /) -> array:
+    x1, x2 = _fix_promotion(x1, x2)
+    return torch.where(condition, x1, x2)
+
+# torch.reshape doesn't have the copy keyword
+def reshape(x: array,
+            /,
+            shape: Tuple[int, ...],
+            copy: Optional[bool] = None,
+            **kwargs) -> array:
+    if copy is not None:
+        raise NotImplementedError("torch.reshape doesn't yet support the copy keyword")
+    return torch.reshape(x, shape, **kwargs)
+
+# torch.arange doesn't support returning empty arrays
+# (https://github.com/pytorch/pytorch/issues/70915), and doesn't support some
+# keyword argument combinations
+# (https://github.com/pytorch/pytorch/issues/70914)
+def arange(start: Union[int, float],
+           /,
+           stop: Optional[Union[int, float]] = None,
+           step: Union[int, float] = 1,
+           *,
+           dtype: Optional[Dtype] = None,
+           device: Optional[Device] = None,
+           **kwargs) -> array:
+    if stop is None:
+        start, stop = 0, start
+    if step > 0 and stop <= start or step < 0 and stop >= start:
+        if dtype is None:
+            if _builtin_all(isinstance(i, int) for i in [start, stop, step]):
+                dtype = torch.int64
+            else:
+                dtype = torch.float32
+        return torch.empty(0, dtype=dtype, device=device, **kwargs)
+    return torch.arange(start, stop, step, dtype=dtype, device=device, **kwargs)
+
+# torch.eye does not accept None as a default for the second argument and
+# doesn't support off-diagonals (https://github.com/pytorch/pytorch/issues/70910)
+def eye(n_rows: int,
+        n_cols: Optional[int] = None,
+        /,
+        *,
+        k: int = 0,
+        dtype: Optional[Dtype] = None,
+        device: Optional[Device] = None,
+        **kwargs) -> array:
+    if n_cols is None:
+        n_cols = n_rows
+    z = torch.zeros(n_rows, n_cols, dtype=dtype, device=device, **kwargs)
+    if abs(k) <= n_rows + n_cols:
+        z.diagonal(k).fill_(1)
+    return z
+
+# torch.linspace doesn't have the endpoint parameter
+def linspace(start: Union[int, float],
+             stop: Union[int, float],
+             /,
+             num: int,
+             *,
+             dtype: Optional[Dtype] = None,
+             device: Optional[Device] = None,
+             endpoint: bool = True,
+             **kwargs) -> array:
+    if not endpoint:
+        return torch.linspace(start, stop, num+1, dtype=dtype, device=device, **kwargs)[:-1]
+    return torch.linspace(start, stop, num, dtype=dtype, device=device, **kwargs)
+
+# torch.full does not accept an int size
+# https://github.com/pytorch/pytorch/issues/70906
+def full(shape: Union[int, Tuple[int, ...]],
+         fill_value: Union[bool, int, float, complex],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    if isinstance(shape, int):
+        shape = (shape,)
+
+    return torch.full(shape, fill_value, dtype=dtype, device=device, **kwargs)
+
+# ones, zeros, and empty do not accept shape as a keyword argument
+def ones(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.ones(shape, dtype=dtype, device=device, **kwargs)
+
+def zeros(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.zeros(shape, dtype=dtype, device=device, **kwargs)
+
+def empty(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.empty(shape, dtype=dtype, device=device, **kwargs)
+
+# tril and triu do not call the keyword argument k
+
+def tril(x: array, /, *, k: int = 0) -> array:
+    return torch.tril(x, k)
+
+def triu(x: array, /, *, k: int = 0) -> array:
+    return torch.triu(x, k)
+
+# Functions that aren't in torch https://github.com/pytorch/pytorch/issues/58742
+def expand_dims(x: array, /, *, axis: int = 0) -> array:
+    return torch.unsqueeze(x, axis)
+
+def astype(x: array, dtype: Dtype, /, *, copy: bool = True) -> array:
+    return x.to(dtype, copy=copy)
+
+def broadcast_arrays(*arrays: array) -> List[array]:
+    shape = torch.broadcast_shapes(*[a.shape for a in arrays])
+    return [torch.broadcast_to(a, shape) for a in arrays]
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+from ..common._aliases import (UniqueAllResult, UniqueCountsResult,
+                               UniqueInverseResult)
+
+# https://github.com/pytorch/pytorch/issues/70920
+def unique_all(x: array) -> UniqueAllResult:
+    # torch.unique doesn't support returning indices.
+    # https://github.com/pytorch/pytorch/issues/36748. The workaround
+    # suggested in that issue doesn't actually function correctly (it relies
+    # on non-deterministic behavior of scatter()).
+    raise NotImplementedError("unique_all() not yet implemented for pytorch (see https://github.com/pytorch/pytorch/issues/36748)")
+
+    # values, inverse_indices, counts = torch.unique(x, return_counts=True, return_inverse=True)
+    # # torch.unique incorrectly gives a 0 count for nan values.
+    # # https://github.com/pytorch/pytorch/issues/94106
+    # counts[torch.isnan(values)] = 1
+    # return UniqueAllResult(values, indices, inverse_indices, counts)
+
+def unique_counts(x: array) -> UniqueCountsResult:
+    values, counts = torch.unique(x, return_counts=True)
+
+    # torch.unique incorrectly gives a 0 count for nan values.
+    # https://github.com/pytorch/pytorch/issues/94106
+    counts[torch.isnan(values)] = 1
+    return UniqueCountsResult(values, counts)
+
+def unique_inverse(x: array) -> UniqueInverseResult:
+    values, inverse = torch.unique(x, return_inverse=True)
+    return UniqueInverseResult(values, inverse)
+
+def unique_values(x: array) -> array:
+    return torch.unique(x)
+
+def matmul(x1: array, x2: array, /, **kwargs) -> array:
+    # torch.matmul doesn't type promote (but differently from _fix_promotion)
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.matmul(x1, x2, **kwargs)
+
+matrix_transpose = get_xp(torch)(_aliases_matrix_transpose)
+_vecdot = get_xp(torch)(_aliases_vecdot)
+
+def vecdot(x1: array, x2: array, /, *, axis: int = -1) -> array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return _vecdot(x1, x2, axis=axis)
+
+# torch.tensordot uses dims instead of axes
+def tensordot(x1: array, x2: array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2, **kwargs) -> array:
+    # Note: torch.tensordot fails with integer dtypes when there is only 1
+    # element in the axis (https://github.com/pytorch/pytorch/issues/84530).
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.tensordot(x1, x2, dims=axes, **kwargs)
+
+
+def isdtype(
+    dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]],
+    *, _tuple=True, # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return _builtin_any(isdtype(dtype, k, _tuple=False) for k in kind)
+    elif isinstance(kind, str):
+        if kind == 'bool':
+            return dtype == torch.bool
+        elif kind == 'signed integer':
+            return dtype in _int_dtypes and dtype.is_signed
+        elif kind == 'unsigned integer':
+            return dtype in _int_dtypes and not dtype.is_signed
+        elif kind == 'integral':
+            return dtype in _int_dtypes
+        elif kind == 'real floating':
+            return dtype.is_floating_point
+        elif kind == 'complex floating':
+            return dtype.is_complex
+        elif kind == 'numeric':
+            return isdtype(dtype, ('integral', 'real floating', 'complex floating'))
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        return dtype == kind
+
+def take(x: array, indices: array, /, *, axis: Optional[int] = None, **kwargs) -> array:
+    if axis is None:
+        if x.ndim != 1:
+            raise ValueError("axis must be specified when ndim > 1")
+        axis = 0
+    return torch.index_select(x, axis, indices, **kwargs)
+
+def sign(x: array, /) -> array:
+    # torch sign() does not support complex numbers and does not propagate
+    # nans. See https://github.com/data-apis/array-api-compat/issues/136
+    if x.dtype.is_complex:
+        out = x/torch.abs(x)
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0+0j] = 0+0j
+        return out
+    else:
+        out = torch.sign(x)
+        if x.dtype.is_floating_point:
+            out[torch.isnan(x)] = torch.nan
+        return out
+
+
+__all__ = ['__array_namespace_info__', 'result_type', 'can_cast',
+           'permute_dims', 'bitwise_invert', 'newaxis', 'conj', 'add',
+           'atan2', 'bitwise_and', 'bitwise_left_shift', 'bitwise_or',
+           'bitwise_right_shift', 'bitwise_xor', 'copysign', 'divide',
+           'equal', 'floor_divide', 'greater', 'greater_equal', 'hypot',
+           'less', 'less_equal', 'logaddexp', 'maximum', 'minimum',
+           'multiply', 'not_equal', 'pow', 'remainder', 'subtract', 'max',
+           'min', 'clip', 'unstack', 'cumulative_sum', 'sort', 'prod', 'sum',
+           'any', 'all', 'mean', 'std', 'var', 'concat', 'squeeze',
+           'broadcast_to', 'flip', 'roll', 'nonzero', 'where', 'reshape',
+           'arange', 'eye', 'linspace', 'full', 'ones', 'zeros', 'empty',
+           'tril', 'triu', 'expand_dims', 'astype', 'broadcast_arrays',
+           'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
+           'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
+           'matmul', 'matrix_transpose', 'vecdot', 'tensordot', 'isdtype',
+           'take', 'sign']
+
+_all_ignore = ['torch', 'get_xp']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..264caa9e5fbbe9da3d9b9594b8d11f313d8536ef
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py
@@ -0,0 +1,358 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+import torch
+
+from functools import cache
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for PyTorch.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for PyTorch.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'torch'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for PyTorch.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          PyTorch.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new PyTorch arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new PyTorch arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return torch.device("cpu")
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new PyTorch arrays.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For PyTorch, only
+            ``'cpu'`` is allowed.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new PyTorch
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': torch.float32,
+         'complex floating': torch.complex64,
+         'integral': torch.int64,
+         'indexing': torch.int64}
+
+        """
+        # Note: if the default is set to float64, the devices like MPS that
+        # don't support float64 will error. We still return the default_dtype
+        # value here because this error doesn't represent a different default
+        # per-device.
+        default_floating = torch.get_default_dtype()
+        default_complex = torch.complex64 if default_floating == torch.float32 else torch.complex128
+        default_integral = torch.int64
+        return {
+            "real floating": default_floating,
+            "complex floating": default_complex,
+            "integral": default_integral,
+            "indexing": default_integral,
+        }
+
+
+    def _dtypes(self, kind):
+        bool = torch.bool
+        int8 = torch.int8
+        int16 = torch.int16
+        int32 = torch.int32
+        int64 = torch.int64
+        uint8 = torch.uint8
+        # uint16, uint32, and uint64 are present in newer versions of pytorch,
+        # but they aren't generally supported by the array API functions, so
+        # we omit them from this function.
+        float32 = torch.float32
+        float64 = torch.float64
+        complex64 = torch.complex64
+        complex128 = torch.complex128
+
+        if kind is None:
+            return {
+                "bool": bool,
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": uint8,
+            }
+        if kind == "integral":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+            }
+        if kind == "real floating":
+            return {
+                "float32": float32,
+                "float64": float64,
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "numeric":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    @cache
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by PyTorch.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            PyTorch data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        res = self._dtypes(kind)
+        for k, v in res.copy().items():
+            try:
+                torch.empty((0,), dtype=v, device=device)
+            except:
+                del res[k]
+        return res
+
+    @cache
+    def devices(self):
+        """
+        The devices supported by PyTorch.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by PyTorch.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        [device(type='cpu'), device(type='mps', index=0), device(type='meta')]
+
+        """
+        # Torch doesn't have a straightforward way to get the list of all
+        # currently supported devices. To do this, we first parse the error
+        # message of torch.device to get the list of all possible types of
+        # device:
+        try:
+            torch.device('notadevice')
+        except RuntimeError as e:
+            # The error message is something like:
+            # "Expected one of cpu, cuda, ipu, xpu, mkldnn, opengl, opencl, ideep, hip, ve, fpga, ort, xla, lazy, vulkan, mps, meta, hpu, mtia, privateuseone device type at start of device string: notadevice"
+            devices_names = e.args[0].split('Expected one of ')[1].split(' device type')[0].split(', ')
+
+        # Next we need to check for different indices for different devices.
+        # device(device_name, index=index) doesn't actually check if the
+        # device name or index is valid. We have to try to create a tensor
+        # with it (which is why this function is cached).
+        devices = []
+        for device_name in devices_names:
+            i = 0
+            while True:
+                try:
+                    a = torch.empty((0,), device=torch.device(device_name, index=i))
+                    if a.device in devices:
+                        break
+                    devices.append(a.device)
+                except:
+                    break
+                i += 1
+
+        return devices
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c9117ee57d3534e3e72329d740632c02e936200
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    import torch
+    array = torch.Tensor
+    from typing import Union, Sequence, Literal
+
+from torch.fft import * # noqa: F403
+import torch.fft
+
+# Several torch fft functions do not map axes to dim
+
+def fftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.fftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def ifftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.ifftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def rfftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.rfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def irfftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def fftshift(
+    x: array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> array:
+    return torch.fft.fftshift(x, dim=axes, **kwargs)
+
+def ifftshift(
+    x: array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> array:
+    return torch.fft.ifftshift(x, dim=axes, **kwargs)
+
+
+__all__ = torch.fft.__all__ + [
+    "fftn",
+    "ifftn",
+    "rfftn",
+    "irfftn",
+    "fftshift",
+    "ifftshift",
+]
+
+_all_ignore = ['torch']
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..e26198b9b562ed307206dd08dd9de7c8aa2a918b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    import torch
+    array = torch.Tensor
+    from torch import dtype as Dtype
+    from typing import Optional, Union, Tuple, Literal
+    inf = float('inf')
+
+from ._aliases import _fix_promotion, sum
+
+from torch.linalg import * # noqa: F403
+
+# torch.linalg doesn't define __all__
+# from torch.linalg import __all__ as linalg_all
+from torch import linalg as torch_linalg
+linalg_all = [i for i in dir(torch_linalg) if not i.startswith('_')]
+
+# outer is implemented in torch but aren't in the linalg namespace
+from torch import outer
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot
+
+# Note: torch.linalg.cross does not default to axis=-1 (it defaults to the
+# first axis with size 3), see https://github.com/pytorch/pytorch/issues/58743
+
+# torch.cross also does not support broadcasting when it would add new
+# dimensions https://github.com/pytorch/pytorch/issues/39656
+def cross(x1: array, x2: array, /, *, axis: int = -1) -> array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    if not (-min(x1.ndim, x2.ndim) <= axis < max(x1.ndim, x2.ndim)):
+        raise ValueError(f"axis {axis} out of bounds for cross product of arrays with shapes {x1.shape} and {x2.shape}")
+    if not (x1.shape[axis] == x2.shape[axis] == 3):
+        raise ValueError(f"cross product axis must have size 3, got {x1.shape[axis]} and {x2.shape[axis]}")
+    x1, x2 = torch.broadcast_tensors(x1, x2)
+    return torch_linalg.cross(x1, x2, dim=axis)
+
+def vecdot(x1: array, x2: array, /, *, axis: int = -1, **kwargs) -> array:
+    from ._aliases import isdtype
+
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+
+    # torch.linalg.vecdot incorrectly allows broadcasting along the contracted dimension
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    # torch.linalg.vecdot doesn't support integer dtypes
+    if isdtype(x1.dtype, 'integral') or isdtype(x2.dtype, 'integral'):
+        if kwargs:
+            raise RuntimeError("vecdot kwargs not supported for integral dtypes")
+
+        x1_ = torch.moveaxis(x1, axis, -1)
+        x2_ = torch.moveaxis(x2, axis, -1)
+        x1_, x2_ = torch.broadcast_tensors(x1_, x2_)
+
+        res = x1_[..., None, :] @ x2_[..., None]
+        return res[..., 0, 0]
+    return torch.linalg.vecdot(x1, x2, dim=axis, **kwargs)
+
+def solve(x1: array, x2: array, /, **kwargs) -> array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    # Torch tries to emulate NumPy 1 solve behavior by using batched 1-D solve
+    # whenever
+    # 1. x1.ndim - 1 == x2.ndim
+    # 2. x1.shape[:-1] == x2.shape
+    #
+    # See linalg_solve_is_vector_rhs in
+    # aten/src/ATen/native/LinearAlgebraUtils.h and
+    # TORCH_META_FUNC(_linalg_solve_ex) in
+    # aten/src/ATen/native/BatchLinearAlgebra.cpp in the PyTorch source code.
+    #
+    # The easiest way to work around this is to prepend a size 1 dimension to
+    # x2, since x2 is already one dimension less than x1.
+    #
+    # See https://github.com/pytorch/pytorch/issues/52915
+    if x2.ndim != 1 and x1.ndim - 1 == x2.ndim and x1.shape[:-1] == x2.shape:
+        x2 = x2[None]
+    return torch.linalg.solve(x1, x2, **kwargs)
+
+# torch.trace doesn't support the offset argument and doesn't support stacking
+def trace(x: array, /, *, offset: int = 0, dtype: Optional[Dtype] = None) -> array:
+    # Use our wrapped sum to make sure it does upcasting correctly
+    return sum(torch.diagonal(x, offset=offset, dim1=-2, dim2=-1), axis=-1, dtype=dtype)
+
+def vector_norm(
+    x: array,
+    /,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    keepdims: bool = False,
+    ord: Union[int, float, Literal[inf, -inf]] = 2,
+    **kwargs,
+) -> array:
+    # torch.vector_norm incorrectly treats axis=() the same as axis=None
+    if axis == ():
+        out = kwargs.get('out')
+        if out is None:
+            dtype = None
+            if x.dtype == torch.complex64:
+                dtype = torch.float32
+            elif x.dtype == torch.complex128:
+                dtype = torch.float64
+
+            out = torch.zeros_like(x, dtype=dtype)
+
+        # The norm of a single scalar works out to abs(x) in every case except
+        # for ord=0, which is x != 0.
+        if ord == 0:
+            out[:] = (x != 0)
+        else:
+            out[:] = torch.abs(x)
+        return out
+    return torch.linalg.vector_norm(x, ord=ord, axis=axis, keepdim=keepdims, **kwargs)
+
+__all__ = linalg_all + ['outer', 'matmul', 'matrix_transpose', 'tensordot',
+                        'cross', 'vecdot', 'solve', 'trace', 'vector_norm']
+
+_all_ignore = ['torch_linalg', 'sum']
+
+del linalg_all
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2062f7d5d6a4d9f5a3556164720a6abc4da456bc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from ._funcs import atleast_nd, cov, create_diagonal, expand_dims, kron, sinc
+
+__version__ = "0.2.0"
+
+__all__ = [
+    "__version__",
+    "atleast_nd",
+    "cov",
+    "create_diagonal",
+    "expand_dims",
+    "kron",
+    "sinc",
+]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d87bbccd6e4393c1d01f25f93ea32b9aa13ff8e0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0a3e558d856c0a12d2f75a2d38f96ddbca7cdb3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce9c636c82f9bdbe256c918aae38cd594418434e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_typing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce800189b46d25316c3123a22ce4ff2e7e1e81ce
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py
@@ -0,0 +1,484 @@
+from __future__ import annotations
+
+import warnings
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from ._typing import Array, ModuleType
+
+__all__ = ["atleast_nd", "cov", "create_diagonal", "expand_dims", "kron", "sinc"]
+
+
+def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array:
+    """
+    Recursively expand the dimension of an array to at least `ndim`.
+
+    Parameters
+    ----------
+    x : array
+    ndim : int
+        The minimum number of dimensions for the result.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        An array with ``res.ndim`` >= `ndim`.
+        If ``x.ndim`` >= `ndim`, `x` is returned.
+        If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes
+        until ``res.ndim`` equals `ndim`.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([1])
+    >>> xpx.atleast_nd(x, ndim=3, xp=xp)
+    Array([[[1]]], dtype=array_api_strict.int64)
+
+    >>> x = xp.asarray([[[1, 2],
+    ...                  [3, 4]]])
+    >>> xpx.atleast_nd(x, ndim=1, xp=xp) is x
+    True
+
+    """
+    if x.ndim < ndim:
+        x = xp.expand_dims(x, axis=0)
+        x = atleast_nd(x, ndim=ndim, xp=xp)
+    return x
+
+
+def cov(m: Array, /, *, xp: ModuleType) -> Array:
+    """
+    Estimate a covariance matrix.
+
+    Covariance indicates the level to which two variables vary together.
+    If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
+    then the covariance matrix element :math:`C_{ij}` is the covariance of
+    :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
+    of :math:`x_i`.
+
+    This provides a subset of the functionality of ``numpy.cov``.
+
+    Parameters
+    ----------
+    m : array
+        A 1-D or 2-D array containing multiple variables and observations.
+        Each row of `m` represents a variable, and each column a single
+        observation of all those variables.
+    xp : array_namespace
+        The standard-compatible namespace for `m`.
+
+    Returns
+    -------
+    res : array
+        The covariance matrix of the variables.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+
+    Consider two variables, :math:`x_0` and :math:`x_1`, which
+    correlate perfectly, but in opposite directions:
+
+    >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T
+    >>> x
+    Array([[0, 1, 2],
+           [2, 1, 0]], dtype=array_api_strict.int64)
+
+    Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
+    matrix shows this clearly:
+
+    >>> xpx.cov(x, xp=xp)
+    Array([[ 1., -1.],
+           [-1.,  1.]], dtype=array_api_strict.float64)
+
+
+    Note that element :math:`C_{0,1}`, which shows the correlation between
+    :math:`x_0` and :math:`x_1`, is negative.
+
+    Further, note how `x` and `y` are combined:
+
+    >>> x = xp.asarray([-2.1, -1,  4.3])
+    >>> y = xp.asarray([3,  1.1,  0.12])
+    >>> X = xp.stack((x, y), axis=0)
+    >>> xpx.cov(X, xp=xp)
+    Array([[11.71      , -4.286     ],
+           [-4.286     ,  2.14413333]], dtype=array_api_strict.float64)
+
+    >>> xpx.cov(x, xp=xp)
+    Array(11.71, dtype=array_api_strict.float64)
+
+    >>> xpx.cov(y, xp=xp)
+    Array(2.14413333, dtype=array_api_strict.float64)
+
+    """
+    m = xp.asarray(m, copy=True)
+    dtype = (
+        xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64)
+    )
+
+    m = atleast_nd(m, ndim=2, xp=xp)
+    m = xp.astype(m, dtype)
+
+    avg = _mean(m, axis=1, xp=xp)
+    fact = m.shape[1] - 1
+
+    if fact <= 0:
+        warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2)
+        fact = 0.0
+
+    m -= avg[:, None]
+    m_transpose = m.T
+    if xp.isdtype(m_transpose.dtype, "complex floating"):
+        m_transpose = xp.conj(m_transpose)
+    c = m @ m_transpose
+    c /= fact
+    axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1)
+    return xp.squeeze(c, axis=axes)
+
+
+def create_diagonal(x: Array, /, *, offset: int = 0, xp: ModuleType) -> Array:
+    """
+    Construct a diagonal array.
+
+    Parameters
+    ----------
+    x : array
+        A 1-D array
+    offset : int, optional
+        Offset from the leading diagonal (default is ``0``).
+        Use positive ints for diagonals above the leading diagonal,
+        and negative ints for diagonals below the leading diagonal.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        A 2-D array with `x` on the diagonal (offset by `offset`).
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([2, 4, 8])
+
+    >>> xpx.create_diagonal(x, xp=xp)
+    Array([[2, 0, 0],
+           [0, 4, 0],
+           [0, 0, 8]], dtype=array_api_strict.int64)
+
+    >>> xpx.create_diagonal(x, offset=-2, xp=xp)
+    Array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [2, 0, 0, 0, 0],
+           [0, 4, 0, 0, 0],
+           [0, 0, 8, 0, 0]], dtype=array_api_strict.int64)
+
+    """
+    if x.ndim != 1:
+        err_msg = "`x` must be 1-dimensional."
+        raise ValueError(err_msg)
+    n = x.shape[0] + abs(offset)
+    diag = xp.zeros(n**2, dtype=x.dtype)
+    i = offset if offset >= 0 else abs(offset) * n
+    diag[i : min(n * (n - offset), diag.shape[0]) : n + 1] = x
+    return xp.reshape(diag, (n, n))
+
+
+def _mean(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    xp: ModuleType,
+) -> Array:
+    """
+    Complex mean, https://github.com/data-apis/array-api/issues/846.
+    """
+    if xp.isdtype(x.dtype, "complex floating"):
+        x_real = xp.real(x)
+        x_imag = xp.imag(x)
+        mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims)
+        mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims)
+        return mean_real + (mean_imag * xp.asarray(1j))
+    return xp.mean(x, axis=axis, keepdims=keepdims)
+
+
+def expand_dims(
+    a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType
+) -> Array:
+    """
+    Expand the shape of an array.
+
+    Insert (a) new axis/axes that will appear at the position(s) specified by
+    `axis` in the expanded array shape.
+
+    This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*.
+    Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays.
+
+    Parameters
+    ----------
+    a : array
+    axis : int or tuple of ints, optional
+        Position(s) in the expanded axes where the new axis (or axes) is/are placed.
+        If multiple positions are provided, they should be unique (note that a position
+        given by a positive index could also be referred to by a negative index -
+        that will also result in an error).
+        Default: ``(0,)``.
+    xp : array_namespace
+        The standard-compatible namespace for `a`.
+
+    Returns
+    -------
+    res : array
+        `a` with an expanded shape.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([1, 2])
+    >>> x.shape
+    (2,)
+
+    The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``:
+
+    >>> y = xpx.expand_dims(x, axis=0, xp=xp)
+    >>> y
+    Array([[1, 2]], dtype=array_api_strict.int64)
+    >>> y.shape
+    (1, 2)
+
+    The following is equivalent to ``x[:, xp.newaxis]``:
+
+    >>> y = xpx.expand_dims(x, axis=1, xp=xp)
+    >>> y
+    Array([[1],
+           [2]], dtype=array_api_strict.int64)
+    >>> y.shape
+    (2, 1)
+
+    ``axis`` may also be a tuple:
+
+    >>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp)
+    >>> y
+    Array([[[1, 2]]], dtype=array_api_strict.int64)
+
+    >>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp)
+    >>> y
+    Array([[[1],
+            [2]]], dtype=array_api_strict.int64)
+
+    """
+    if not isinstance(axis, tuple):
+        axis = (axis,)
+    ndim = a.ndim + len(axis)
+    if axis != () and (min(axis) < -ndim or max(axis) >= ndim):
+        err_msg = (
+            f"a provided axis position is out of bounds for array of dimension {a.ndim}"
+        )
+        raise IndexError(err_msg)
+    axis = tuple(dim % ndim for dim in axis)
+    if len(set(axis)) != len(axis):
+        err_msg = "Duplicate dimensions specified in `axis`."
+        raise ValueError(err_msg)
+    for i in sorted(axis):
+        a = xp.expand_dims(a, axis=i)
+    return a
+
+
+def kron(a: Array, b: Array, /, *, xp: ModuleType) -> Array:
+    """
+    Kronecker product of two arrays.
+
+    Computes the Kronecker product, a composite array made of blocks of the
+    second array scaled by the first.
+
+    Equivalent to ``numpy.kron`` for NumPy arrays.
+
+    Parameters
+    ----------
+    a, b : array
+    xp : array_namespace
+        The standard-compatible namespace for `a` and `b`.
+
+    Returns
+    -------
+    res : array
+        The Kronecker product of `a` and `b`.
+
+    Notes
+    -----
+    The function assumes that the number of dimensions of `a` and `b`
+    are the same, if necessary prepending the smallest with ones.
+    If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
+    the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
+    The elements are products of elements from `a` and `b`, organized
+    explicitly by::
+
+        kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
+
+    where::
+
+        kt = it * st + jt,  t = 0,...,N
+
+    In the common 2-D case (N=1), the block structure can be visualized::
+
+        [[ a[0,0]*b,   a[0,1]*b,  ... , a[0,-1]*b  ],
+         [  ...                              ...   ],
+         [ a[-1,0]*b,  a[-1,1]*b, ... , a[-1,-1]*b ]]
+
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp)
+    Array([  5,   6,   7,  50,  60,  70, 500,
+           600, 700], dtype=array_api_strict.int64)
+
+    >>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp)
+    Array([  5,  50, 500,   6,  60, 600,   7,
+            70, 700], dtype=array_api_strict.int64)
+
+    >>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp)
+    Array([[1., 1., 0., 0.],
+           [1., 1., 0., 0.],
+           [0., 0., 1., 1.],
+           [0., 0., 1., 1.]], dtype=array_api_strict.float64)
+
+
+    >>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5))
+    >>> b = xp.reshape(xp.arange(24), (2, 3, 4))
+    >>> c = xpx.kron(a, b, xp=xp)
+    >>> c.shape
+    (2, 10, 6, 20)
+    >>> I = (1, 3, 0, 2)
+    >>> J = (0, 2, 1)
+    >>> J1 = (0,) + J             # extend to ndim=4
+    >>> S1 = (1,) + b.shape
+    >>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1))
+    >>> c[K] == a[I]*b[J]
+    Array(True, dtype=array_api_strict.bool)
+
+    """
+
+    b = xp.asarray(b)
+    singletons = (1,) * (b.ndim - a.ndim)
+    a = xp.broadcast_to(xp.asarray(a), singletons + a.shape)
+
+    nd_b, nd_a = b.ndim, a.ndim
+    nd_max = max(nd_b, nd_a)
+    if nd_a == 0 or nd_b == 0:
+        return xp.multiply(a, b)
+
+    a_shape = a.shape
+    b_shape = b.shape
+
+    # Equalise the shapes by prepending smaller one with 1s
+    a_shape = (1,) * max(0, nd_b - nd_a) + a_shape
+    b_shape = (1,) * max(0, nd_a - nd_b) + b_shape
+
+    # Insert empty dimensions
+    a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp)
+    b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp)
+
+    # Compute the product
+    a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp)
+    b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp)
+    result = xp.multiply(a_arr, b_arr)
+
+    # Reshape back and return
+    a_shape = xp.asarray(a_shape)
+    b_shape = xp.asarray(b_shape)
+    return xp.reshape(result, tuple(xp.multiply(a_shape, b_shape)))
+
+
+def sinc(x: Array, /, *, xp: ModuleType) -> Array:
+    r"""
+    Return the normalized sinc function.
+
+    The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
+    :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
+    only everywhere continuous but also infinitely differentiable.
+
+    .. note::
+
+        Note the normalization factor of ``pi`` used in the definition.
+        This is the most commonly used definition in signal processing.
+        Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function
+        :math:`\sin(x)/x` that is more common in mathematics.
+
+    Parameters
+    ----------
+    x : array
+        Array (possibly multi-dimensional) of values for which to calculate
+        ``sinc(x)``. Must have a real floating point dtype.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        ``sinc(x)`` calculated elementwise, which has the same shape as the input.
+
+    Notes
+    -----
+    The name sinc is short for "sine cardinal" or "sinus cardinalis".
+
+    The sinc function is used in various signal processing applications,
+    including in anti-aliasing, in the construction of a Lanczos resampling
+    filter, and in interpolation.
+
+    For bandlimited interpolation of discrete-time signals, the ideal
+    interpolation kernel is proportional to the sinc function.
+
+    References
+    ----------
+    .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
+           Resource. https://mathworld.wolfram.com/SincFunction.html
+    .. [2] Wikipedia, "Sinc function",
+           https://en.wikipedia.org/wiki/Sinc_function
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.linspace(-4, 4, 41)
+    >>> xpx.sinc(x, xp=xp)
+    Array([-3.89817183e-17, -4.92362781e-02,
+           -8.40918587e-02, -8.90384387e-02,
+           -5.84680802e-02,  3.89817183e-17,
+            6.68206631e-02,  1.16434881e-01,
+            1.26137788e-01,  8.50444803e-02,
+           -3.89817183e-17, -1.03943254e-01,
+           -1.89206682e-01, -2.16236208e-01,
+           -1.55914881e-01,  3.89817183e-17,
+            2.33872321e-01,  5.04551152e-01,
+            7.56826729e-01,  9.35489284e-01,
+            1.00000000e+00,  9.35489284e-01,
+            7.56826729e-01,  5.04551152e-01,
+            2.33872321e-01,  3.89817183e-17,
+           -1.55914881e-01, -2.16236208e-01,
+           -1.89206682e-01, -1.03943254e-01,
+           -3.89817183e-17,  8.50444803e-02,
+            1.26137788e-01,  1.16434881e-01,
+            6.68206631e-02,  3.89817183e-17,
+           -5.84680802e-02, -8.90384387e-02,
+           -8.40918587e-02, -4.92362781e-02,
+           -3.89817183e-17], dtype=array_api_strict.float64)
+
+    """
+    if not xp.isdtype(x.dtype, "real floating"):
+        err_msg = "`x` must have a real floating data type."
+        raise ValueError(err_msg)
+    # no scalars in `where` - array-api#807
+    y = xp.pi * xp.where(
+        x, x, xp.asarray(xp.finfo(x.dtype).smallest_normal, dtype=x.dtype)
+    )
+    return xp.sin(y) / y
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ffa13f23fc8c52abf5c65206ec1ff5a8481832c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py
@@ -0,0 +1,8 @@
+from __future__ import annotations
+
+from types import ModuleType
+from typing import Any
+
+Array = Any  # To be changed to a Protocol later (see array-api#589)
+
+__all__ = ["Array", "ModuleType"]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2418395425d7ecce9e1a4da68985c8fde93bc1c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py
@@ -0,0 +1,20 @@
+from .main import minimize
+from .utils import show_versions
+
+# PEP0440 compatible formatted version, see:
+# https://www.python.org/dev/peps/pep-0440/
+#
+# Final release markers:
+#   X.Y.0   # For first release after an increment in Y
+#   X.Y.Z   # For bugfix releases
+#
+# Admissible pre-release markers:
+#   X.YaN   # Alpha release
+#   X.YbN   # Beta release
+#   X.YrcN  # Release Candidate
+#
+# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
+# 'X.Y.dev0' is the canonical version of 'X.Y.dev'.
+__version__ = "1.1.2"
+
+__all__ = ["minimize", "show_versions"]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd0a910c0fa9cb0698eb94bca89c9f0210c99203
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c5de3dc823a5922f28310a598f8ea2acc5a5cb0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1714ab8d6b148b7c855f7649ba2c71ff11237fb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c749a2b269f8066688c9b43664797580acf0a106
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0df4e8affdae4dfd77d481dcffd5e795316bf146
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a8b8b8b43fcecf0738edbda613b467e6220c27c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py
new file mode 100644
index 0000000000000000000000000000000000000000..9afea66281067e27a486ff317a4bffa03ec3e68b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py
@@ -0,0 +1,1240 @@
+import warnings
+
+import numpy as np
+from scipy.optimize import lsq_linear
+
+from .models import Models, Quadratic
+from .settings import Options, Constants
+from .subsolvers import (
+    cauchy_geometry,
+    spider_geometry,
+    normal_byrd_omojokun,
+    tangential_byrd_omojokun,
+    constrained_tangential_byrd_omojokun,
+)
+from .subsolvers.optim import qr_tangential_byrd_omojokun
+from .utils import get_arrays_tol
+
+
+TINY = np.finfo(float).tiny
+EPS = np.finfo(float).eps
+
+
+class TrustRegion:
+    """
+    Trust-region framework.
+    """
+
+    def __init__(self, pb, options, constants):
+        """
+        Initialize the trust-region framework.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to solve.
+        options : dict
+            Options of the solver.
+        constants : dict
+            Constants of the solver.
+
+        Raises
+        ------
+        `cobyqa.utils.MaxEvalError`
+            If the maximum number of evaluations is reached.
+        `cobyqa.utils.TargetSuccess`
+            If a nearly feasible point has been found with an objective
+            function value below the target.
+        `cobyqa.utils.FeasibleSuccess`
+            If a feasible point has been found for a feasibility problem.
+        `numpy.linalg.LinAlgError`
+            If the initial interpolation system is ill-defined.
+        """
+        # Set the initial penalty parameter.
+        self._penalty = 0.0
+
+        # Initialize the models.
+        self._pb = pb
+        self._models = Models(self._pb, options, self.penalty)
+        self._constants = constants
+
+        # Set the index of the best interpolation point.
+        self._best_index = 0
+        self.set_best_index()
+
+        # Set the initial Lagrange multipliers.
+        self._lm_linear_ub = np.zeros(self.m_linear_ub)
+        self._lm_linear_eq = np.zeros(self.m_linear_eq)
+        self._lm_nonlinear_ub = np.zeros(self.m_nonlinear_ub)
+        self._lm_nonlinear_eq = np.zeros(self.m_nonlinear_eq)
+        self.set_multipliers(self.x_best)
+
+        # Set the initial trust-region radius and the resolution.
+        self._resolution = options[Options.RHOBEG]
+        self._radius = self.resolution
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self._pb.n
+
+    @property
+    def m_linear_ub(self):
+        """
+        Number of linear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear inequality constraints.
+        """
+        return self._pb.m_linear_ub
+
+    @property
+    def m_linear_eq(self):
+        """
+        Number of linear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear equality constraints.
+        """
+        return self._pb.m_linear_eq
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+        """
+        return self._pb.m_nonlinear_ub
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+        """
+        return self._pb.m_nonlinear_eq
+
+    @property
+    def radius(self):
+        """
+        Trust-region radius.
+
+        Returns
+        -------
+        float
+            Trust-region radius.
+        """
+        return self._radius
+
+    @radius.setter
+    def radius(self, radius):
+        """
+        Set the trust-region radius.
+
+        Parameters
+        ----------
+        radius : float
+            New trust-region radius.
+        """
+        self._radius = radius
+        if (
+            self.radius
+            <= self._constants[Constants.DECREASE_RADIUS_THRESHOLD]
+            * self.resolution
+        ):
+            self._radius = self.resolution
+
+    @property
+    def resolution(self):
+        """
+        Resolution of the trust-region framework.
+
+        The resolution is a lower bound on the trust-region radius.
+
+        Returns
+        -------
+        float
+            Resolution of the trust-region framework.
+        """
+        return self._resolution
+
+    @resolution.setter
+    def resolution(self, resolution):
+        """
+        Set the resolution of the trust-region framework.
+
+        Parameters
+        ----------
+        resolution : float
+            New resolution of the trust-region framework.
+        """
+        self._resolution = resolution
+
+    @property
+    def penalty(self):
+        """
+        Penalty parameter.
+
+        Returns
+        -------
+        float
+            Penalty parameter.
+        """
+        return self._penalty
+
+    @property
+    def models(self):
+        """
+        Models of the objective function and constraints.
+
+        Returns
+        -------
+        `cobyqa.models.Models`
+            Models of the objective function and constraints.
+        """
+        return self._models
+
+    @property
+    def best_index(self):
+        """
+        Index of the best interpolation point.
+
+        Returns
+        -------
+        int
+            Index of the best interpolation point.
+        """
+        return self._best_index
+
+    @property
+    def x_best(self):
+        """
+        Best interpolation point.
+
+        Its value is interpreted as relative to the origin, not the base point.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Best interpolation point.
+        """
+        return self.models.interpolation.point(self.best_index)
+
+    @property
+    def fun_best(self):
+        """
+        Value of the objective function at `x_best`.
+
+        Returns
+        -------
+        float
+            Value of the objective function at `x_best`.
+        """
+        return self.models.fun_val[self.best_index]
+
+    @property
+    def cub_best(self):
+        """
+        Values of the nonlinear inequality constraints at `x_best`.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Values of the nonlinear inequality constraints at `x_best`.
+        """
+        return self.models.cub_val[self.best_index, :]
+
+    @property
+    def ceq_best(self):
+        """
+        Values of the nonlinear equality constraints at `x_best`.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Values of the nonlinear equality constraints at `x_best`.
+        """
+        return self.models.ceq_val[self.best_index, :]
+
+    def lag_model(self, x):
+        """
+        Evaluate the Lagrangian model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the Lagrangian model is evaluated.
+
+        Returns
+        -------
+        float
+            Value of the Lagrangian model at `x`.
+        """
+        return (
+            self.models.fun(x)
+            + self._lm_linear_ub
+            @ (self._pb.linear.a_ub @ x - self._pb.linear.b_ub)
+            + self._lm_linear_eq
+            @ (self._pb.linear.a_eq @ x - self._pb.linear.b_eq)
+            + self._lm_nonlinear_ub @ self.models.cub(x)
+            + self._lm_nonlinear_eq @ self.models.ceq(x)
+        )
+
+    def lag_model_grad(self, x):
+        """
+        Evaluate the gradient of the Lagrangian model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the gradient of the Lagrangian model is evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the Lagrangian model at `x`.
+        """
+        return (
+            self.models.fun_grad(x)
+            + self._lm_linear_ub @ self._pb.linear.a_ub
+            + self._lm_linear_eq @ self._pb.linear.a_eq
+            + self._lm_nonlinear_ub @ self.models.cub_grad(x)
+            + self._lm_nonlinear_eq @ self.models.ceq_grad(x)
+        )
+
+    def lag_model_hess(self):
+        """
+        Evaluate the Hessian matrix of the Lagrangian model at a given point.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the Lagrangian model at `x`.
+        """
+        hess = self.models.fun_hess()
+        if self.m_nonlinear_ub > 0:
+            hess += self._lm_nonlinear_ub @ self.models.cub_hess()
+        if self.m_nonlinear_eq > 0:
+            hess += self._lm_nonlinear_eq @ self.models.ceq_hess()
+        return hess
+
+    def lag_model_hess_prod(self, v):
+        """
+        Evaluate the right product of the Hessian matrix of the Lagrangian
+        model with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the Lagrangian model is
+            multiplied from the right.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the Lagrangian model with
+            `v`.
+        """
+        return (
+            self.models.fun_hess_prod(v)
+            + self._lm_nonlinear_ub @ self.models.cub_hess_prod(v)
+            + self._lm_nonlinear_eq @ self.models.ceq_hess_prod(v)
+        )
+
+    def lag_model_curv(self, v):
+        """
+        Evaluate the curvature of the Lagrangian model along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the Lagrangian model is
+            evaluated.
+
+        Returns
+        -------
+        float
+            Curvature of the Lagrangian model along `v`.
+        """
+        return (
+            self.models.fun_curv(v)
+            + self._lm_nonlinear_ub @ self.models.cub_curv(v)
+            + self._lm_nonlinear_eq @ self.models.ceq_curv(v)
+        )
+
+    def sqp_fun(self, step):
+        """
+        Evaluate the objective function of the SQP subproblem.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Step along which the objective function of the SQP subproblem is
+            evaluated.
+
+        Returns
+        -------
+        float
+            Value of the objective function of the SQP subproblem along `step`.
+        """
+        return step @ (
+            self.models.fun_grad(self.x_best)
+            + 0.5 * self.lag_model_hess_prod(step)
+        )
+
+    def sqp_cub(self, step):
+        """
+        Evaluate the linearization of the nonlinear inequality constraints.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Step along which the linearization of the nonlinear inequality
+            constraints is evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Value of the linearization of the nonlinear inequality constraints
+            along `step`.
+        """
+        return (
+            self.models.cub(self.x_best)
+            + self.models.cub_grad(self.x_best) @ step
+        )
+
+    def sqp_ceq(self, step):
+        """
+        Evaluate the linearization of the nonlinear equality constraints.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Step along which the linearization of the nonlinear equality
+            constraints is evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Value of the linearization of the nonlinear equality constraints
+            along `step`.
+        """
+        return (
+            self.models.ceq(self.x_best)
+            + self.models.ceq_grad(self.x_best) @ step
+        )
+
+    def merit(self, x, fun_val=None, cub_val=None, ceq_val=None):
+        """
+        Evaluate the merit function at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the merit function is evaluated.
+        fun_val : float, optional
+            Value of the objective function at `x`. If not provided, the
+            objective function is evaluated at `x`.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Values of the nonlinear inequality constraints. If not provided,
+            the nonlinear inequality constraints are evaluated at `x`.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Values of the nonlinear equality constraints. If not provided,
+            the nonlinear equality constraints are evaluated at `x`.
+
+        Returns
+        -------
+        float
+            Value of the merit function at `x`.
+        """
+        if fun_val is None or cub_val is None or ceq_val is None:
+            fun_val, cub_val, ceq_val = self._pb(x, self.penalty)
+        m_val = fun_val
+        if self._penalty > 0.0:
+            c_val = self._pb.violation(x, cub_val=cub_val, ceq_val=ceq_val)
+            if np.count_nonzero(c_val):
+                m_val += self._penalty * np.linalg.norm(c_val)
+        return m_val
+
+    def get_constraint_linearizations(self, x):
+        """
+        Get the linearizations of the constraints at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the linearizations of the constraints are evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub, n)
+            Left-hand side matrix of the linearized inequality constraints.
+        `numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub,)
+            Right-hand side vector of the linearized inequality constraints.
+        `numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq, n)
+            Left-hand side matrix of the linearized equality constraints.
+        `numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq,)
+            Right-hand side vector of the linearized equality constraints.
+        """
+        aub = np.block(
+            [
+                [self._pb.linear.a_ub],
+                [self.models.cub_grad(x)],
+            ]
+        )
+        bub = np.block(
+            [
+                self._pb.linear.b_ub - self._pb.linear.a_ub @ x,
+                -self.models.cub(x),
+            ]
+        )
+        aeq = np.block(
+            [
+                [self._pb.linear.a_eq],
+                [self.models.ceq_grad(x)],
+            ]
+        )
+        beq = np.block(
+            [
+                self._pb.linear.b_eq - self._pb.linear.a_eq @ x,
+                -self.models.ceq(x),
+            ]
+        )
+        return aub, bub, aeq, beq
+
+    def get_trust_region_step(self, options):
+        """
+        Get the trust-region step.
+
+        The trust-region step is computed by solving the derivative-free
+        trust-region SQP subproblem using a Byrd-Omojokun composite-step
+        approach. For more details, see Section 5.2.3 of [1]_.
+
+        Parameters
+        ----------
+        options : dict
+            Options of the solver.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Normal step.
+        `numpy.ndarray`, shape (n,)
+            Tangential step.
+
+        References
+        ----------
+        .. [1] T. M. Ragonneau. *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.
+        """
+        # Evaluate the linearizations of the constraints.
+        aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
+        xl = self._pb.bounds.xl - self.x_best
+        xu = self._pb.bounds.xu - self.x_best
+
+        # Evaluate the normal step.
+        radius = self._constants[Constants.BYRD_OMOJOKUN_FACTOR] * self.radius
+        normal_step = normal_byrd_omojokun(
+            aub,
+            bub,
+            aeq,
+            beq,
+            xl,
+            xu,
+            radius,
+            options[Options.DEBUG],
+            **self._constants,
+        )
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if (np.any(normal_step + tol < xl)
+                    or np.any(xu < normal_step - tol)):
+                warnings.warn(
+                    "the normal step does not respect the bound constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+            if np.linalg.norm(normal_step) > 1.1 * radius:
+                warnings.warn(
+                    "the normal step does not respect the trust-region "
+                    "constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+
+        # Evaluate the tangential step.
+        radius = np.sqrt(self.radius**2.0 - normal_step @ normal_step)
+        xl -= normal_step
+        xu -= normal_step
+        bub = np.maximum(bub - aub @ normal_step, 0.0)
+        g_best = self.models.fun_grad(self.x_best) + self.lag_model_hess_prod(
+            normal_step
+        )
+        if self._pb.type in ["unconstrained", "bound-constrained"]:
+            tangential_step = tangential_byrd_omojokun(
+                g_best,
+                self.lag_model_hess_prod,
+                xl,
+                xu,
+                radius,
+                options[Options.DEBUG],
+                **self._constants,
+            )
+        else:
+            tangential_step = constrained_tangential_byrd_omojokun(
+                g_best,
+                self.lag_model_hess_prod,
+                xl,
+                xu,
+                aub,
+                bub,
+                aeq,
+                radius,
+                options["debug"],
+                **self._constants,
+            )
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if np.any(tangential_step + tol < xl) or np.any(
+                xu < tangential_step - tol
+            ):
+                warnings.warn(
+                    "The tangential step does not respect the bound "
+                    "constraints.",
+                    RuntimeWarning,
+                    2,
+                )
+            if (
+                np.linalg.norm(normal_step + tangential_step)
+                > 1.1 * np.sqrt(2.0) * self.radius
+            ):
+                warnings.warn(
+                    "The trial step does not respect the trust-region "
+                    "constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+        return normal_step, tangential_step
+
+    def get_geometry_step(self, k_new, options):
+        """
+        Get the geometry-improving step.
+
+        Three different geometry-improving steps are computed and the best one
+        is returned. For more details, see Section 5.2.7 of [1]_.
+
+        Parameters
+        ----------
+        k_new : int
+            Index of the interpolation point to be modified.
+        options : dict
+            Options of the solver.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Geometry-improving step.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the computation of a determinant fails.
+
+        References
+        ----------
+        .. [1] T. M. Ragonneau. *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.
+        """
+        if options[Options.DEBUG]:
+            assert (
+                k_new != self.best_index
+            ), "The index `k_new` must be different from the best index."
+
+        # Build the k_new-th Lagrange polynomial.
+        coord_vec = np.squeeze(np.eye(1, self.models.npt, k_new))
+        lag = Quadratic(
+            self.models.interpolation,
+            coord_vec,
+            options[Options.DEBUG],
+        )
+        g_lag = lag.grad(self.x_best, self.models.interpolation)
+
+        # Compute a simple constrained Cauchy step.
+        xl = self._pb.bounds.xl - self.x_best
+        xu = self._pb.bounds.xu - self.x_best
+        step = cauchy_geometry(
+            0.0,
+            g_lag,
+            lambda v: lag.curv(v, self.models.interpolation),
+            xl,
+            xu,
+            self.radius,
+            options[Options.DEBUG],
+        )
+        sigma = self.models.determinants(self.x_best + step, k_new)
+
+        # Compute the solution on the straight lines joining the interpolation
+        # points to the k-th one, and choose it if it provides a larger value
+        # of the determinant of the interpolation system in absolute value.
+        xpt = (
+            self.models.interpolation.xpt
+            - self.models.interpolation.xpt[:, self.best_index, np.newaxis]
+        )
+        xpt[:, [0, self.best_index]] = xpt[:, [self.best_index, 0]]
+        step_alt = spider_geometry(
+            0.0,
+            g_lag,
+            lambda v: lag.curv(v, self.models.interpolation),
+            xpt[:, 1:],
+            xl,
+            xu,
+            self.radius,
+            options[Options.DEBUG],
+        )
+        sigma_alt = self.models.determinants(self.x_best + step_alt, k_new)
+        if abs(sigma_alt) > abs(sigma):
+            step = step_alt
+            sigma = sigma_alt
+
+        # Compute a Cauchy step on the tangent space of the active constraints.
+        if self._pb.type in [
+            "linearly constrained",
+            "nonlinearly constrained",
+        ]:
+            aub, bub, aeq, beq = (
+                self.get_constraint_linearizations(self.x_best))
+            tol_bd = get_arrays_tol(xl, xu)
+            tol_ub = get_arrays_tol(bub)
+            free_xl = xl <= -tol_bd
+            free_xu = xu >= tol_bd
+            free_ub = bub >= tol_ub
+
+            # Compute the Cauchy step.
+            n_act, q = qr_tangential_byrd_omojokun(
+                aub,
+                aeq,
+                free_xl,
+                free_xu,
+                free_ub,
+            )
+            g_lag_proj = q[:, n_act:] @ (q[:, n_act:].T @ g_lag)
+            norm_g_lag_proj = np.linalg.norm(g_lag_proj)
+            if 0 < n_act < self._pb.n and norm_g_lag_proj > TINY * self.radius:
+                step_alt = (self.radius / norm_g_lag_proj) * g_lag_proj
+                if lag.curv(step_alt, self.models.interpolation) < 0.0:
+                    step_alt = -step_alt
+
+                # Evaluate the constraint violation at the Cauchy step.
+                cbd = np.block([xl - step_alt, step_alt - xu])
+                cub = aub @ step_alt - bub
+                ceq = aeq @ step_alt - beq
+                maxcv_val = max(
+                    np.max(array, initial=0.0)
+                    for array in [cbd, cub, np.abs(ceq)]
+                )
+
+                # Accept the new step if it is nearly feasible and do not
+                # drastically worsen the determinant of the interpolation
+                # system in absolute value.
+                tol = np.max(np.abs(step_alt[~free_xl]), initial=0.0)
+                tol = np.max(np.abs(step_alt[~free_xu]), initial=tol)
+                tol = np.max(np.abs(aub[~free_ub, :] @ step_alt), initial=tol)
+                tol = min(10.0 * tol, 1e-2 * np.linalg.norm(step_alt))
+                if maxcv_val <= tol:
+                    sigma_alt = self.models.determinants(
+                        self.x_best + step_alt, k_new
+                    )
+                    if abs(sigma_alt) >= 0.1 * abs(sigma):
+                        step = np.clip(step_alt, xl, xu)
+
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if np.any(step + tol < xl) or np.any(xu < step - tol):
+                warnings.warn(
+                    "The geometry step does not respect the bound "
+                    "constraints.",
+                    RuntimeWarning,
+                    2,
+                )
+            if np.linalg.norm(step) > 1.1 * self.radius:
+                warnings.warn(
+                    "The geometry step does not respect the "
+                    "trust-region constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+        return step
+
+    def get_second_order_correction_step(self, step, options):
+        """
+        Get the second-order correction step.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        options : dict
+            Options of the solver.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Second-order correction step.
+        """
+        # Evaluate the linearizations of the constraints.
+        aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
+        xl = self._pb.bounds.xl - self.x_best
+        xu = self._pb.bounds.xu - self.x_best
+        radius = np.linalg.norm(step)
+        soc_step = normal_byrd_omojokun(
+            aub,
+            bub,
+            aeq,
+            beq,
+            xl,
+            xu,
+            radius,
+            options[Options.DEBUG],
+            **self._constants,
+        )
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if np.any(soc_step + tol < xl) or np.any(xu < soc_step - tol):
+                warnings.warn(
+                    "The second-order correction step does not "
+                    "respect the bound constraints.",
+                    RuntimeWarning,
+                    2,
+                )
+            if np.linalg.norm(soc_step) > 1.1 * radius:
+                warnings.warn(
+                    "The second-order correction step does not "
+                    "respect the trust-region constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+        return soc_step
+
+    def get_reduction_ratio(self, step, fun_val, cub_val, ceq_val):
+        """
+        Get the reduction ratio.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        fun_val : float
+            Objective function value at the trial point.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Nonlinear inequality constraint values at the trial point.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Nonlinear equality constraint values at the trial point.
+
+        Returns
+        -------
+        float
+            Reduction ratio.
+        """
+        merit_old = self.merit(
+            self.x_best,
+            self.fun_best,
+            self.cub_best,
+            self.ceq_best,
+        )
+        merit_new = self.merit(self.x_best + step, fun_val, cub_val, ceq_val)
+        merit_model_old = self.merit(
+            self.x_best,
+            0.0,
+            self.models.cub(self.x_best),
+            self.models.ceq(self.x_best),
+        )
+        merit_model_new = self.merit(
+            self.x_best + step,
+            self.sqp_fun(step),
+            self.sqp_cub(step),
+            self.sqp_ceq(step),
+        )
+        if abs(merit_model_old - merit_model_new) > TINY * abs(
+            merit_old - merit_new
+        ):
+            return (merit_old - merit_new) / abs(
+                merit_model_old - merit_model_new
+            )
+        else:
+            return -1.0
+
+    def increase_penalty(self, step):
+        """
+        Increase the penalty parameter.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        """
+        aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
+        viol_diff = max(
+            np.linalg.norm(
+                np.block(
+                    [
+                        np.maximum(0.0, -bub),
+                        beq,
+                    ]
+                )
+            )
+            - np.linalg.norm(
+                np.block(
+                    [
+                        np.maximum(0.0, aub @ step - bub),
+                        aeq @ step - beq,
+                    ]
+                )
+            ),
+            0.0,
+        )
+        sqp_val = self.sqp_fun(step)
+
+        threshold = np.linalg.norm(
+            np.block(
+                [
+                    self._lm_linear_ub,
+                    self._lm_linear_eq,
+                    self._lm_nonlinear_ub,
+                    self._lm_nonlinear_eq,
+                ]
+            )
+        )
+        if abs(viol_diff) > TINY * abs(sqp_val):
+            threshold = max(threshold, sqp_val / viol_diff)
+        best_index_save = self.best_index
+        if (
+            self._penalty
+            <= self._constants[Constants.PENALTY_INCREASE_THRESHOLD]
+                * threshold
+        ):
+            self._penalty = max(
+                self._constants[Constants.PENALTY_INCREASE_FACTOR] * threshold,
+                1.0,
+            )
+            self.set_best_index()
+        return best_index_save == self.best_index
+
+    def decrease_penalty(self):
+        """
+        Decrease the penalty parameter.
+        """
+        self._penalty = min(self._penalty, self._get_low_penalty())
+        self.set_best_index()
+
+    def set_best_index(self):
+        """
+        Set the index of the best point.
+        """
+        best_index = self.best_index
+        m_best = self.merit(
+            self.x_best,
+            self.models.fun_val[best_index],
+            self.models.cub_val[best_index, :],
+            self.models.ceq_val[best_index, :],
+        )
+        r_best = self._pb.maxcv(
+            self.x_best,
+            self.models.cub_val[best_index, :],
+            self.models.ceq_val[best_index, :],
+        )
+        tol = (
+            10.0
+            * EPS
+            * max(self.models.n, self.models.npt)
+            * max(abs(m_best), 1.0)
+        )
+        for k in range(self.models.npt):
+            if k != self.best_index:
+                x_val = self.models.interpolation.point(k)
+                m_val = self.merit(
+                    x_val,
+                    self.models.fun_val[k],
+                    self.models.cub_val[k, :],
+                    self.models.ceq_val[k, :],
+                )
+                r_val = self._pb.maxcv(
+                    x_val,
+                    self.models.cub_val[k, :],
+                    self.models.ceq_val[k, :],
+                )
+                if m_val < m_best or (m_val < m_best + tol and r_val < r_best):
+                    best_index = k
+                    m_best = m_val
+                    r_best = r_val
+        self._best_index = best_index
+
+    def get_index_to_remove(self, x_new=None):
+        """
+        Get the index of the interpolation point to remove.
+
+        If `x_new` is not provided, the index returned should be used during
+        the geometry-improvement phase. Otherwise, the index returned is the
+        best index for included `x_new` in the interpolation set.
+
+        Parameters
+        ----------
+        x_new : `numpy.ndarray`, shape (n,), optional
+            New point to be included in the interpolation set.
+
+        Returns
+        -------
+        int
+            Index of the interpolation point to remove.
+        float
+            Distance between `x_best` and the removed point.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the computation of a determinant fails.
+        """
+        dist_sq = np.sum(
+            (
+                self.models.interpolation.xpt
+                - self.models.interpolation.xpt[:, self.best_index, np.newaxis]
+            )
+            ** 2.0,
+            axis=0,
+        )
+        if x_new is None:
+            sigma = 1.0
+            weights = dist_sq
+        else:
+            sigma = self.models.determinants(x_new)
+            weights = (
+                np.maximum(
+                    1.0,
+                    dist_sq
+                    / max(
+                        self._constants[Constants.LOW_RADIUS_FACTOR]
+                        * self.radius,
+                        self.resolution,
+                    )
+                    ** 2.0,
+                )
+                ** 3.0
+            )
+            weights[self.best_index] = -1.0  # do not remove the best point
+        k_max = np.argmax(weights * np.abs(sigma))
+        return k_max, np.sqrt(dist_sq[k_max])
+
+    def update_radius(self, step, ratio):
+        """
+        Update the trust-region radius.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        ratio : float
+            Reduction ratio.
+        """
+        s_norm = np.linalg.norm(step)
+        if ratio <= self._constants[Constants.LOW_RATIO]:
+            self.radius *= self._constants[Constants.DECREASE_RADIUS_FACTOR]
+        elif ratio <= self._constants[Constants.HIGH_RATIO]:
+            self.radius = max(
+                self._constants[Constants.DECREASE_RADIUS_FACTOR]
+                * self.radius,
+                s_norm,
+            )
+        else:
+            self.radius = min(
+                self._constants[Constants.INCREASE_RADIUS_FACTOR]
+                * self.radius,
+                max(
+                    self._constants[Constants.DECREASE_RADIUS_FACTOR]
+                    * self.radius,
+                    self._constants[Constants.INCREASE_RADIUS_THRESHOLD]
+                    * s_norm,
+                ),
+            )
+
+    def enhance_resolution(self, options):
+        """
+        Enhance the resolution of the trust-region framework.
+
+        Parameters
+        ----------
+        options : dict
+            Options of the solver.
+        """
+        if (
+            self._constants[Constants.LARGE_RESOLUTION_THRESHOLD]
+            * options[Options.RHOEND]
+            < self.resolution
+        ):
+            self.resolution *= self._constants[
+                Constants.DECREASE_RESOLUTION_FACTOR
+            ]
+        elif (
+            self._constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
+            * options[Options.RHOEND]
+            < self.resolution
+        ):
+            self.resolution = np.sqrt(self.resolution
+                                      * options[Options.RHOEND])
+        else:
+            self.resolution = options[Options.RHOEND]
+
+        # Reduce the trust-region radius.
+        self._radius = max(
+            self._constants[Constants.DECREASE_RADIUS_FACTOR] * self._radius,
+            self.resolution,
+        )
+
+    def shift_x_base(self, options):
+        """
+        Shift the base point to `x_best`.
+
+        Parameters
+        ----------
+        options : dict
+            Options of the solver.
+        """
+        self.models.shift_x_base(np.copy(self.x_best), options)
+
+    def set_multipliers(self, x):
+        """
+        Set the Lagrange multipliers.
+
+        This method computes and set the Lagrange multipliers of the linear and
+        nonlinear constraints to be the QP multipliers.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the Lagrange multipliers are computed.
+        """
+        # Build the constraints of the least-squares problem.
+        incl_linear_ub = self._pb.linear.a_ub @ x >= self._pb.linear.b_ub
+        incl_nonlinear_ub = self.cub_best >= 0.0
+        incl_xl = self._pb.bounds.xl >= x
+        incl_xu = self._pb.bounds.xu <= x
+        m_linear_ub = np.count_nonzero(incl_linear_ub)
+        m_nonlinear_ub = np.count_nonzero(incl_nonlinear_ub)
+        m_xl = np.count_nonzero(incl_xl)
+        m_xu = np.count_nonzero(incl_xu)
+
+        if (
+            m_linear_ub + m_nonlinear_ub + self.m_linear_eq
+                + self.m_nonlinear_eq > 0
+        ):
+            identity = np.eye(self._pb.n)
+            c_jac = np.r_[
+                -identity[incl_xl, :],
+                identity[incl_xu, :],
+                self._pb.linear.a_ub[incl_linear_ub, :],
+                self.models.cub_grad(x, incl_nonlinear_ub),
+                self._pb.linear.a_eq,
+                self.models.ceq_grad(x),
+            ]
+
+            # Solve the least-squares problem.
+            g_best = self.models.fun_grad(x)
+            xl_lm = np.full(c_jac.shape[0], -np.inf)
+            xl_lm[: m_xl + m_xu + m_linear_ub + m_nonlinear_ub] = 0.0
+            res = lsq_linear(
+                c_jac.T,
+                -g_best,
+                bounds=(xl_lm, np.inf),
+                method="bvls",
+            )
+
+            # Extract the Lagrange multipliers.
+            self._lm_linear_ub[incl_linear_ub] = res.x[
+                m_xl + m_xu:m_xl + m_xu + m_linear_ub
+            ]
+            self._lm_linear_ub[~incl_linear_ub] = 0.0
+            self._lm_nonlinear_ub[incl_nonlinear_ub] = res.x[
+                m_xl
+                + m_xu
+                + m_linear_ub:m_xl
+                + m_xu
+                + m_linear_ub
+                + m_nonlinear_ub
+            ]
+            self._lm_nonlinear_ub[~incl_nonlinear_ub] = 0.0
+            self._lm_linear_eq[:] = res.x[
+                m_xl
+                + m_xu
+                + m_linear_ub
+                + m_nonlinear_ub:m_xl
+                + m_xu
+                + m_linear_ub
+                + m_nonlinear_ub
+                + self.m_linear_eq
+            ]
+            self._lm_nonlinear_eq[:] = res.x[
+                m_xl + m_xu + m_linear_ub + m_nonlinear_ub + self.m_linear_eq:
+            ]
+
+    def _get_low_penalty(self):
+        r_val_ub = np.c_[
+            (
+                self.models.interpolation.x_base[np.newaxis, :]
+                + self.models.interpolation.xpt.T
+            )
+            @ self._pb.linear.a_ub.T
+            - self._pb.linear.b_ub[np.newaxis, :],
+            self.models.cub_val,
+        ]
+        r_val_eq = (
+            self.models.interpolation.x_base[np.newaxis, :]
+            + self.models.interpolation.xpt.T
+        ) @ self._pb.linear.a_eq.T - self._pb.linear.b_eq[np.newaxis, :]
+        r_val_eq = np.block(
+            [
+                r_val_eq,
+                -r_val_eq,
+                self.models.ceq_val,
+                -self.models.ceq_val,
+            ]
+        )
+        r_val = np.block([r_val_ub, r_val_eq])
+        c_min = np.nanmin(r_val, axis=0)
+        c_max = np.nanmax(r_val, axis=0)
+        indices = (
+            c_min
+            < self._constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] * c_max
+        )
+        if np.any(indices):
+            f_min = np.nanmin(self.models.fun_val)
+            f_max = np.nanmax(self.models.fun_val)
+            c_min_neg = np.minimum(0.0, c_min[indices])
+            c_diff = np.min(c_max[indices] - c_min_neg)
+            if c_diff > TINY * (f_max - f_min):
+                penalty = (f_max - f_min) / c_diff
+            else:
+                penalty = np.inf
+        else:
+            penalty = 0.0
+        return penalty
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..01e5159e0dfebed9a78c6948cb99bfb1d744b6c7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py
@@ -0,0 +1,1506 @@
+import warnings
+
+import numpy as np
+from scipy.optimize import (
+    Bounds,
+    LinearConstraint,
+    NonlinearConstraint,
+    OptimizeResult,
+)
+
+from .framework import TrustRegion
+from .problem import (
+    ObjectiveFunction,
+    BoundConstraints,
+    LinearConstraints,
+    NonlinearConstraints,
+    Problem,
+)
+from .utils import (
+    MaxEvalError,
+    TargetSuccess,
+    CallbackSuccess,
+    FeasibleSuccess,
+    exact_1d_array,
+)
+from .settings import (
+    ExitStatus,
+    Options,
+    Constants,
+    DEFAULT_OPTIONS,
+    DEFAULT_CONSTANTS,
+    PRINT_OPTIONS,
+)
+
+
+def minimize(
+    fun,
+    x0,
+    args=(),
+    bounds=None,
+    constraints=(),
+    callback=None,
+    options=None,
+    **kwargs,
+):
+    r"""
+    Minimize a scalar function using the COBYQA method.
+
+    The Constrained Optimization BY Quadratic Approximations (COBYQA) method is
+    a derivative-free optimization method designed to solve general nonlinear
+    optimization problems. A complete description of COBYQA is given in [3]_.
+
+    Parameters
+    ----------
+    fun : {callable, None}
+        Objective function to be minimized.
+
+            ``fun(x, *args) -> float``
+
+        where ``x`` is an array with shape (n,) and `args` is a tuple. If `fun`
+        is ``None``, the objective function is assumed to be the zero function,
+        resulting in a feasibility problem.
+    x0 : array_like, shape (n,)
+        Initial guess.
+    args : tuple, optional
+        Extra arguments passed to the objective function.
+    bounds : {`scipy.optimize.Bounds`, array_like, shape (n, 2)}, optional
+        Bound constraints of the problem. It can be one of the cases below.
+
+        #. An instance of `scipy.optimize.Bounds`. For the time being, the
+           argument ``keep_feasible`` is disregarded, and all the constraints
+           are considered unrelaxable and will be enforced.
+        #. An array with shape (n, 2). The bound constraints for ``x[i]`` are
+           ``bounds[i][0] <= x[i] <= bounds[i][1]``. Set ``bounds[i][0]`` to
+           :math:`-\infty` if there is no lower bound, and set ``bounds[i][1]``
+           to :math:`\infty` if there is no upper bound.
+
+        The COBYQA method always respect the bound constraints.
+    constraints : {Constraint, list}, optional
+        General constraints of the problem. It can be one of the cases below.
+
+        #. An instance of `scipy.optimize.LinearConstraint`. The argument
+           ``keep_feasible`` is disregarded.
+        #. An instance of `scipy.optimize.NonlinearConstraint`. The arguments
+           ``jac``, ``hess``, ``keep_feasible``, ``finite_diff_rel_step``, and
+           ``finite_diff_jac_sparsity`` are disregarded.
+
+        #. A list, each of whose elements are described in the cases above.
+
+    callback : callable, optional
+        A callback executed at each objective function evaluation. The method
+        terminates if a ``StopIteration`` exception is raised by the callback
+        function. Its signature can be one of the following:
+
+            ``callback(intermediate_result)``
+
+        where ``intermediate_result`` is a keyword parameter that contains an
+        instance of `scipy.optimize.OptimizeResult`, with attributes ``x``
+        and ``fun``, being the point at which the objective function is
+        evaluated and the value of the objective function, respectively. The
+        name of the parameter must be ``intermediate_result`` for the callback
+        to be passed an instance of `scipy.optimize.OptimizeResult`.
+
+        Alternatively, the callback function can have the signature:
+
+            ``callback(xk)``
+
+        where ``xk`` is the point at which the objective function is evaluated.
+        Introspection is used to determine which of the signatures to invoke.
+    options : dict, optional
+        Options passed to the solver. Accepted keys are:
+
+            disp : bool, optional
+                Whether to print information about the optimization procedure.
+                Default is ``False``.
+            maxfev : int, optional
+                Maximum number of function evaluations. Default is ``500 * n``.
+            maxiter : int, optional
+                Maximum number of iterations. Default is ``1000 * n``.
+            target : float, optional
+                Target on the objective function value. The optimization
+                procedure is terminated when the objective function value of a
+                feasible point is less than or equal to this target. Default is
+                ``-numpy.inf``.
+            feasibility_tol : float, optional
+                Tolerance on the constraint violation. If the maximum
+                constraint violation at a point is less than or equal to this
+                tolerance, the point is considered feasible. Default is
+                ``numpy.sqrt(numpy.finfo(float).eps)``.
+            radius_init : float, optional
+                Initial trust-region radius. Typically, this value should be in
+                the order of one tenth of the greatest expected change to `x0`.
+                Default is ``1.0``.
+            radius_final : float, optional
+                Final trust-region radius. It should indicate the accuracy
+                required in the final values of the variables. Default is
+                ``1e-6``.
+            nb_points : int, optional
+                Number of interpolation points used to build the quadratic
+                models of the objective and constraint functions. Default is
+                ``2 * n + 1``.
+            scale : bool, optional
+                Whether to scale the variables according to the bounds. Default
+                is ``False``.
+            filter_size : int, optional
+                Maximum number of points in the filter. The filter is used to
+                select the best point returned by the optimization procedure.
+                Default is ``sys.maxsize``.
+            store_history : bool, optional
+                Whether to store the history of the function evaluations.
+                Default is ``False``.
+            history_size : int, optional
+                Maximum number of function evaluations to store in the history.
+                Default is ``sys.maxsize``.
+            debug : bool, optional
+                Whether to perform additional checks during the optimization
+                procedure. This option should be used only for debugging
+                purposes and is highly discouraged to general users. Default is
+                ``False``.
+
+        Other constants (from the keyword arguments) are described below. They
+        are not intended to be changed by general users. They should only be
+        changed by users with a deep understanding of the algorithm, who want
+        to experiment with different settings.
+
+    Returns
+    -------
+    `scipy.optimize.OptimizeResult`
+        Result of the optimization procedure, with the following fields:
+
+            message : str
+                Description of the cause of the termination.
+            success : bool
+                Whether the optimization procedure terminated successfully.
+            status : int
+                Termination status of the optimization procedure.
+            x : `numpy.ndarray`, shape (n,)
+                Solution point.
+            fun : float
+                Objective function value at the solution point.
+            maxcv : float
+                Maximum constraint violation at the solution point.
+            nfev : int
+                Number of function evaluations.
+            nit : int
+                Number of iterations.
+
+        If ``store_history`` is True, the result also has the following fields:
+
+            fun_history : `numpy.ndarray`, shape (nfev,)
+                History of the objective function values.
+            maxcv_history : `numpy.ndarray`, shape (nfev,)
+                History of the maximum constraint violations.
+
+        A description of the termination statuses is given below.
+
+        .. list-table::
+            :widths: 25 75
+            :header-rows: 1
+
+            * - Exit status
+              - Description
+            * - 0
+              - The lower bound for the trust-region radius has been reached.
+            * - 1
+              - The target objective function value has been reached.
+            * - 2
+              - All variables are fixed by the bound constraints.
+            * - 3
+              - The callback requested to stop the optimization procedure.
+            * - 4
+              - The feasibility problem received has been solved successfully.
+            * - 5
+              - The maximum number of function evaluations has been exceeded.
+            * - 6
+              - The maximum number of iterations has been exceeded.
+            * - -1
+              - The bound constraints are infeasible.
+            * - -2
+              - A linear algebra error occurred.
+
+    Other Parameters
+    ----------------
+    decrease_radius_factor : float, optional
+        Factor by which the trust-region radius is reduced when the reduction
+        ratio is low or negative. Default is ``0.5``.
+    increase_radius_factor : float, optional
+        Factor by which the trust-region radius is increased when the reduction
+        ratio is large. Default is ``numpy.sqrt(2.0)``.
+    increase_radius_threshold : float, optional
+        Threshold that controls the increase of the trust-region radius when
+        the reduction ratio is large. Default is ``2.0``.
+    decrease_radius_threshold : float, optional
+        Threshold used to determine whether the trust-region radius should be
+        reduced to the resolution. Default is ``1.4``.
+    decrease_resolution_factor : float, optional
+        Factor by which the resolution is reduced when the current value is far
+        from its final value. Default is ``0.1``.
+    large_resolution_threshold : float, optional
+        Threshold used to determine whether the resolution is far from its
+        final value. Default is ``250.0``.
+    moderate_resolution_threshold : float, optional
+        Threshold used to determine whether the resolution is close to its
+        final value. Default is ``16.0``.
+    low_ratio : float, optional
+        Threshold used to determine whether the reduction ratio is low. Default
+        is ``0.1``.
+    high_ratio : float, optional
+        Threshold used to determine whether the reduction ratio is high.
+        Default is ``0.7``.
+    very_low_ratio : float, optional
+        Threshold used to determine whether the reduction ratio is very low.
+        This is used to determine whether the models should be reset. Default
+        is ``0.01``.
+    penalty_increase_threshold : float, optional
+        Threshold used to determine whether the penalty parameter should be
+        increased. Default is ``1.5``.
+    penalty_increase_factor : float, optional
+        Factor by which the penalty parameter is increased. Default is ``2.0``.
+    short_step_threshold : float, optional
+        Factor used to determine whether the trial step is too short. Default
+        is ``0.5``.
+    low_radius_factor : float, optional
+        Factor used to determine which interpolation point should be removed
+        from the interpolation set at each iteration. Default is ``0.1``.
+    byrd_omojokun_factor : float, optional
+        Factor by which the trust-region radius is reduced for the computations
+        of the normal step in the Byrd-Omojokun composite-step approach.
+        Default is ``0.8``.
+    threshold_ratio_constraints : float, optional
+        Threshold used to determine which constraints should be taken into
+        account when decreasing the penalty parameter. Default is ``2.0``.
+    large_shift_factor : float, optional
+        Factor used to determine whether the point around which the quadratic
+        models are built should be updated. Default is ``10.0``.
+    large_gradient_factor : float, optional
+        Factor used to determine whether the models should be reset. Default is
+        ``10.0``.
+    resolution_factor : float, optional
+        Factor by which the resolution is decreased. Default is ``2.0``.
+    improve_tcg : bool, optional
+        Whether to improve the steps computed by the truncated conjugate
+        gradient method when the trust-region boundary is reached. Default is
+        ``True``.
+
+    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] M. J. D. Powell. A direct search optimization method that models the
+       objective and constraint functions by linear interpolation. In S. Gomez
+       and J.-P. Hennart, editors, *Advances in Optimization and Numerical
+       Analysis*, volume 275 of Math. Appl., pages 51--67. Springer, Dordrecht,
+       Netherlands, 1994. `doi:10.1007/978-94-015-8330-5_4
+       `_.
+    .. [3] T. M. Ragonneau. *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.
+
+    Examples
+    --------
+    To demonstrate how to use `minimize`, we first minimize the Rosenbrock
+    function implemented in `scipy.optimize` in an unconstrained setting.
+
+    .. testsetup::
+
+        import numpy as np
+        np.set_printoptions(precision=3, suppress=True)
+
+    >>> from cobyqa import minimize
+    >>> from scipy.optimize import rosen
+
+    To solve the problem using COBYQA, run:
+
+    >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+    >>> res = minimize(rosen, x0)
+    >>> res.x
+    array([1., 1., 1., 1., 1.])
+
+    To see how bound and constraints are handled using `minimize`, we solve
+    Example 16.4 of [1]_, defined as
+
+    .. math::
+
+        \begin{aligned}
+            \min_{x \in \mathbb{R}^2}   & \quad (x_1 - 1)^2 + (x_2 - 2.5)^2\\
+            \text{s.t.}                 & \quad -x_1 + 2x_2 \le 2,\\
+                                        & \quad x_1 + 2x_2 \le 6,\\
+                                        & \quad x_1 - 2x_2 \le 2,\\
+                                        & \quad x_1 \ge 0,\\
+                                        & \quad x_2 \ge 0.
+        \end{aligned}
+
+    >>> import numpy as np
+    >>> from scipy.optimize import Bounds, LinearConstraint
+
+    Its objective function can be implemented as:
+
+    >>> def fun(x):
+    ...     return (x[0] - 1.0)**2 + (x[1] - 2.5)**2
+
+    This problem can be solved using `minimize` as:
+
+    >>> x0 = [2.0, 0.0]
+    >>> bounds = Bounds([0.0, 0.0], np.inf)
+    >>> constraints = LinearConstraint([
+    ...     [-1.0, 2.0],
+    ...     [1.0, 2.0],
+    ...     [1.0, -2.0],
+    ... ], -np.inf, [2.0, 6.0, 2.0])
+    >>> res = minimize(fun, x0, bounds=bounds, constraints=constraints)
+    >>> res.x
+    array([1.4, 1.7])
+
+    To see how nonlinear constraints are handled, we solve Problem (F) of [2]_,
+    defined as
+
+    .. math::
+
+        \begin{aligned}
+            \min_{x \in \mathbb{R}^2}   & \quad -x_1 - x_2\\
+            \text{s.t.}                 & \quad x_1^2 - x_2 \le 0,\\
+                                        & \quad x_1^2 + x_2^2 \le 1.
+        \end{aligned}
+
+    >>> from scipy.optimize import NonlinearConstraint
+
+    Its objective and constraint functions can be implemented as:
+
+    >>> def fun(x):
+    ...     return -x[0] - x[1]
+    >>>
+    >>> def cub(x):
+    ...     return [x[0]**2 - x[1], x[0]**2 + x[1]**2]
+
+    This problem can be solved using `minimize` as:
+
+    >>> x0 = [1.0, 1.0]
+    >>> constraints = NonlinearConstraint(cub, -np.inf, [0.0, 1.0])
+    >>> res = minimize(fun, x0, constraints=constraints)
+    >>> res.x
+    array([0.707, 0.707])
+
+    Finally, to see how to supply linear and nonlinear constraints
+    simultaneously, we solve Problem (G) of [2]_, defined as
+
+    .. math::
+
+        \begin{aligned}
+            \min_{x \in \mathbb{R}^3}   & \quad x_3\\
+            \text{s.t.}                 & \quad 5x_1 - x_2 + x_3 \ge 0,\\
+                                        & \quad -5x_1 - x_2 + x_3 \ge 0,\\
+                                        & \quad x_1^2 + x_2^2 + 4x_2 \le x_3.
+        \end{aligned}
+
+    Its objective and nonlinear constraint functions can be implemented as:
+
+    >>> def fun(x):
+    ...     return x[2]
+    >>>
+    >>> def cub(x):
+    ...     return x[0]**2 + x[1]**2 + 4.0*x[1] - x[2]
+
+    This problem can be solved using `minimize` as:
+
+    >>> x0 = [1.0, 1.0, 1.0]
+    >>> constraints = [
+    ...     LinearConstraint(
+    ...         [[5.0, -1.0, 1.0], [-5.0, -1.0, 1.0]],
+    ...         [0.0, 0.0],
+    ...         np.inf,
+    ...     ),
+    ...     NonlinearConstraint(cub, -np.inf, 0.0),
+    ... ]
+    >>> res = minimize(fun, x0, constraints=constraints)
+    >>> res.x
+    array([ 0., -3., -3.])
+    """
+    # Get basic options that are needed for the initialization.
+    if options is None:
+        options = {}
+    else:
+        options = dict(options)
+    verbose = options.get(Options.VERBOSE, DEFAULT_OPTIONS[Options.VERBOSE])
+    verbose = bool(verbose)
+    feasibility_tol = options.get(
+        Options.FEASIBILITY_TOL,
+        DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
+    )
+    feasibility_tol = float(feasibility_tol)
+    scale = options.get(Options.SCALE, DEFAULT_OPTIONS[Options.SCALE])
+    scale = bool(scale)
+    store_history = options.get(
+        Options.STORE_HISTORY,
+        DEFAULT_OPTIONS[Options.STORE_HISTORY],
+    )
+    store_history = bool(store_history)
+    if Options.HISTORY_SIZE in options and options[Options.HISTORY_SIZE] <= 0:
+        raise ValueError("The size of the history must be positive.")
+    history_size = options.get(
+        Options.HISTORY_SIZE,
+        DEFAULT_OPTIONS[Options.HISTORY_SIZE],
+    )
+    history_size = int(history_size)
+    if Options.FILTER_SIZE in options and options[Options.FILTER_SIZE] <= 0:
+        raise ValueError("The size of the filter must be positive.")
+    filter_size = options.get(
+        Options.FILTER_SIZE,
+        DEFAULT_OPTIONS[Options.FILTER_SIZE],
+    )
+    filter_size = int(filter_size)
+    debug = options.get(Options.DEBUG, DEFAULT_OPTIONS[Options.DEBUG])
+    debug = bool(debug)
+
+    # Initialize the objective function.
+    if not isinstance(args, tuple):
+        args = (args,)
+    obj = ObjectiveFunction(fun, verbose, debug, *args)
+
+    # Initialize the bound constraints.
+    if not hasattr(x0, "__len__"):
+        x0 = [x0]
+    n_orig = len(x0)
+    bounds = BoundConstraints(_get_bounds(bounds, n_orig))
+
+    # Initialize the constraints.
+    linear_constraints, nonlinear_constraints = _get_constraints(constraints)
+    linear = LinearConstraints(linear_constraints, n_orig, debug)
+    nonlinear = NonlinearConstraints(nonlinear_constraints, verbose, debug)
+
+    # Initialize the problem (and remove the fixed variables).
+    pb = Problem(
+        obj,
+        x0,
+        bounds,
+        linear,
+        nonlinear,
+        callback,
+        feasibility_tol,
+        scale,
+        store_history,
+        history_size,
+        filter_size,
+        debug,
+    )
+
+    # Set the default options.
+    _set_default_options(options, pb.n)
+    constants = _set_default_constants(**kwargs)
+
+    # Initialize the models and skip the computations whenever possible.
+    if not pb.bounds.is_feasible:
+        # The bound constraints are infeasible.
+        return _build_result(
+            pb,
+            0.0,
+            False,
+            ExitStatus.INFEASIBLE_ERROR,
+            0,
+            options,
+        )
+    elif pb.n == 0:
+        # All variables are fixed by the bound constraints.
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.FIXED_SUCCESS,
+            0,
+            options,
+        )
+    if verbose:
+        print("Starting the optimization procedure.")
+        print(f"Initial trust-region radius: {options[Options.RHOBEG]}.")
+        print(f"Final trust-region radius: {options[Options.RHOEND]}.")
+        print(
+            f"Maximum number of function evaluations: "
+            f"{options[Options.MAX_EVAL]}."
+        )
+        print(f"Maximum number of iterations: {options[Options.MAX_ITER]}.")
+        print()
+    try:
+        framework = TrustRegion(pb, options, constants)
+    except TargetSuccess:
+        # The target on the objective function value has been reached
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.TARGET_SUCCESS,
+            0,
+            options,
+        )
+    except CallbackSuccess:
+        # The callback raised a StopIteration exception.
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.CALLBACK_SUCCESS,
+            0,
+            options,
+        )
+    except FeasibleSuccess:
+        # The feasibility problem has been solved successfully.
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.FEASIBLE_SUCCESS,
+            0,
+            options,
+        )
+    except MaxEvalError:
+        # The maximum number of function evaluations has been exceeded.
+        return _build_result(
+            pb,
+            0.0,
+            False,
+            ExitStatus.MAX_ITER_WARNING,
+            0,
+            options,
+        )
+    except np.linalg.LinAlgError:
+        # The construction of the initial interpolation set failed.
+        return _build_result(
+            pb,
+            0.0,
+            False,
+            ExitStatus.LINALG_ERROR,
+            0,
+            options,
+        )
+
+    # Start the optimization procedure.
+    success = False
+    n_iter = 0
+    k_new = None
+    n_short_steps = 0
+    n_very_short_steps = 0
+    n_alt_models = 0
+    while True:
+        # Stop the optimization procedure if the maximum number of iterations
+        # has been exceeded. We do not write the main loop as a for loop
+        # because we want to access the number of iterations outside the loop.
+        if n_iter >= options[Options.MAX_ITER]:
+            status = ExitStatus.MAX_ITER_WARNING
+            break
+        n_iter += 1
+
+        # Update the point around which the quadratic models are built.
+        if (
+            np.linalg.norm(
+                framework.x_best - framework.models.interpolation.x_base
+            )
+            >= constants[Constants.LARGE_SHIFT_FACTOR] * framework.radius
+        ):
+            framework.shift_x_base(options)
+
+        # Evaluate the trial step.
+        radius_save = framework.radius
+        normal_step, tangential_step = framework.get_trust_region_step(options)
+        step = normal_step + tangential_step
+        s_norm = np.linalg.norm(step)
+
+        # If the trial step is too short, we do not attempt to evaluate the
+        # objective and constraint functions. Instead, we reduce the
+        # trust-region radius and check whether the resolution should be
+        # enhanced and whether the geometry of the interpolation set should be
+        # improved. Otherwise, we entertain a classical iteration. The
+        # criterion for performing an exceptional jump is taken from NEWUOA.
+        if (
+            s_norm
+            <= constants[Constants.SHORT_STEP_THRESHOLD] * framework.resolution
+        ):
+            framework.radius *= constants[Constants.DECREASE_RESOLUTION_FACTOR]
+            if radius_save > framework.resolution:
+                n_short_steps = 0
+                n_very_short_steps = 0
+            else:
+                n_short_steps += 1
+                n_very_short_steps += 1
+                if s_norm > 0.1 * framework.resolution:
+                    n_very_short_steps = 0
+            enhance_resolution = n_short_steps >= 5 or n_very_short_steps >= 3
+            if enhance_resolution:
+                n_short_steps = 0
+                n_very_short_steps = 0
+                improve_geometry = False
+            else:
+                try:
+                    k_new, dist_new = framework.get_index_to_remove()
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+                improve_geometry = dist_new > max(
+                    framework.radius,
+                    constants[Constants.RESOLUTION_FACTOR]
+                    * framework.resolution,
+                )
+        else:
+            # Increase the penalty parameter if necessary.
+            same_best_point = framework.increase_penalty(step)
+            if same_best_point:
+                # Evaluate the objective and constraint functions.
+                try:
+                    fun_val, cub_val, ceq_val = _eval(
+                        pb,
+                        framework,
+                        step,
+                        options,
+                    )
+                except TargetSuccess:
+                    status = ExitStatus.TARGET_SUCCESS
+                    success = True
+                    break
+                except FeasibleSuccess:
+                    status = ExitStatus.FEASIBLE_SUCCESS
+                    success = True
+                    break
+                except CallbackSuccess:
+                    status = ExitStatus.CALLBACK_SUCCESS
+                    success = True
+                    break
+                except MaxEvalError:
+                    status = ExitStatus.MAX_EVAL_WARNING
+                    break
+
+                # Perform a second-order correction step if necessary.
+                merit_old = framework.merit(
+                    framework.x_best,
+                    framework.fun_best,
+                    framework.cub_best,
+                    framework.ceq_best,
+                )
+                merit_new = framework.merit(
+                    framework.x_best + step, fun_val, cub_val, ceq_val
+                )
+                if (
+                    pb.type == "nonlinearly constrained"
+                    and merit_new > merit_old
+                    and np.linalg.norm(normal_step)
+                    > constants[Constants.BYRD_OMOJOKUN_FACTOR] ** 2.0
+                    * framework.radius
+                ):
+                    soc_step = framework.get_second_order_correction_step(
+                        step, options
+                    )
+                    if np.linalg.norm(soc_step) > 0.0:
+                        step += soc_step
+
+                        # Evaluate the objective and constraint functions.
+                        try:
+                            fun_val, cub_val, ceq_val = _eval(
+                                pb,
+                                framework,
+                                step,
+                                options,
+                            )
+                        except TargetSuccess:
+                            status = ExitStatus.TARGET_SUCCESS
+                            success = True
+                            break
+                        except FeasibleSuccess:
+                            status = ExitStatus.FEASIBLE_SUCCESS
+                            success = True
+                            break
+                        except CallbackSuccess:
+                            status = ExitStatus.CALLBACK_SUCCESS
+                            success = True
+                            break
+                        except MaxEvalError:
+                            status = ExitStatus.MAX_EVAL_WARNING
+                            break
+
+                # Calculate the reduction ratio.
+                ratio = framework.get_reduction_ratio(
+                    step,
+                    fun_val,
+                    cub_val,
+                    ceq_val,
+                )
+
+                # Choose an interpolation point to remove.
+                try:
+                    k_new = framework.get_index_to_remove(
+                        framework.x_best + step
+                    )[0]
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+
+                # Update the interpolation set.
+                try:
+                    ill_conditioned = framework.models.update_interpolation(
+                        k_new, framework.x_best + step, fun_val, cub_val,
+                        ceq_val
+                    )
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+                framework.set_best_index()
+
+                # Update the trust-region radius.
+                framework.update_radius(step, ratio)
+
+                # Attempt to replace the models by the alternative ones.
+                if framework.radius <= framework.resolution:
+                    if ratio >= constants[Constants.VERY_LOW_RATIO]:
+                        n_alt_models = 0
+                    else:
+                        n_alt_models += 1
+                        grad = framework.models.fun_grad(framework.x_best)
+                        try:
+                            grad_alt = framework.models.fun_alt_grad(
+                                framework.x_best
+                            )
+                        except np.linalg.LinAlgError:
+                            status = ExitStatus.LINALG_ERROR
+                            break
+                        if np.linalg.norm(grad) < constants[
+                            Constants.LARGE_GRADIENT_FACTOR
+                        ] * np.linalg.norm(grad_alt):
+                            n_alt_models = 0
+                        if n_alt_models >= 3:
+                            try:
+                                framework.models.reset_models()
+                            except np.linalg.LinAlgError:
+                                status = ExitStatus.LINALG_ERROR
+                                break
+                            n_alt_models = 0
+
+                # Update the Lagrange multipliers.
+                framework.set_multipliers(framework.x_best + step)
+
+                # Check whether the resolution should be enhanced.
+                try:
+                    k_new, dist_new = framework.get_index_to_remove()
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+                improve_geometry = (
+                    ill_conditioned
+                    or ratio <= constants[Constants.LOW_RATIO]
+                    and dist_new
+                    > max(
+                        framework.radius,
+                        constants[Constants.RESOLUTION_FACTOR]
+                        * framework.resolution,
+                    )
+                )
+                enhance_resolution = (
+                    radius_save <= framework.resolution
+                    and ratio <= constants[Constants.LOW_RATIO]
+                    and not improve_geometry
+                )
+            else:
+                # When increasing the penalty parameter, the best point so far
+                # may change. In this case, we restart the iteration.
+                enhance_resolution = False
+                improve_geometry = False
+
+        # Reduce the resolution if necessary.
+        if enhance_resolution:
+            if framework.resolution <= options[Options.RHOEND]:
+                success = True
+                status = ExitStatus.RADIUS_SUCCESS
+                break
+            framework.enhance_resolution(options)
+            framework.decrease_penalty()
+
+            if verbose:
+                maxcv_val = pb.maxcv(
+                    framework.x_best, framework.cub_best, framework.ceq_best
+                )
+                _print_step(
+                    f"New trust-region radius: {framework.resolution}",
+                    pb,
+                    pb.build_x(framework.x_best),
+                    framework.fun_best,
+                    maxcv_val,
+                    pb.n_eval,
+                    n_iter,
+                )
+                print()
+
+        # Improve the geometry of the interpolation set if necessary.
+        if improve_geometry:
+            try:
+                step = framework.get_geometry_step(k_new, options)
+            except np.linalg.LinAlgError:
+                status = ExitStatus.LINALG_ERROR
+                break
+
+            # Evaluate the objective and constraint functions.
+            try:
+                fun_val, cub_val, ceq_val = _eval(pb, framework, step, options)
+            except TargetSuccess:
+                status = ExitStatus.TARGET_SUCCESS
+                success = True
+                break
+            except FeasibleSuccess:
+                status = ExitStatus.FEASIBLE_SUCCESS
+                success = True
+                break
+            except CallbackSuccess:
+                status = ExitStatus.CALLBACK_SUCCESS
+                success = True
+                break
+            except MaxEvalError:
+                status = ExitStatus.MAX_EVAL_WARNING
+                break
+
+            # Update the interpolation set.
+            try:
+                framework.models.update_interpolation(
+                    k_new,
+                    framework.x_best + step,
+                    fun_val,
+                    cub_val,
+                    ceq_val,
+                )
+            except np.linalg.LinAlgError:
+                status = ExitStatus.LINALG_ERROR
+                break
+            framework.set_best_index()
+
+    return _build_result(
+        pb,
+        framework.penalty,
+        success,
+        status,
+        n_iter,
+        options,
+    )
+
+
+def _get_bounds(bounds, n):
+    """
+    Uniformize the bounds.
+    """
+    if bounds is None:
+        return Bounds(np.full(n, -np.inf), np.full(n, np.inf))
+    elif isinstance(bounds, Bounds):
+        if bounds.lb.shape != (n,) or bounds.ub.shape != (n,):
+            raise ValueError(f"The bounds must have {n} elements.")
+        return Bounds(bounds.lb, bounds.ub)
+    elif hasattr(bounds, "__len__"):
+        bounds = np.asarray(bounds)
+        if bounds.shape != (n, 2):
+            raise ValueError(
+                "The shape of the bounds is not compatible with "
+                "the number of variables."
+            )
+        return Bounds(bounds[:, 0], bounds[:, 1])
+    else:
+        raise TypeError(
+            "The bounds must be an instance of "
+            "scipy.optimize.Bounds or an array-like object."
+        )
+
+
+def _get_constraints(constraints):
+    """
+    Extract the linear and nonlinear constraints.
+    """
+    if isinstance(constraints, dict) or not hasattr(constraints, "__len__"):
+        constraints = (constraints,)
+
+    # Extract the linear and nonlinear constraints.
+    linear_constraints = []
+    nonlinear_constraints = []
+    for constraint in constraints:
+        if isinstance(constraint, LinearConstraint):
+            lb = exact_1d_array(
+                constraint.lb,
+                "The lower bound of the linear constraints must be a vector.",
+            )
+            ub = exact_1d_array(
+                constraint.ub,
+                "The upper bound of the linear constraints must be a vector.",
+            )
+            linear_constraints.append(
+                LinearConstraint(
+                    constraint.A,
+                    *np.broadcast_arrays(lb, ub),
+                )
+            )
+        elif isinstance(constraint, NonlinearConstraint):
+            lb = exact_1d_array(
+                constraint.lb,
+                "The lower bound of the "
+                "nonlinear constraints must be a "
+                "vector.",
+            )
+            ub = exact_1d_array(
+                constraint.ub,
+                "The upper bound of the "
+                "nonlinear constraints must be a "
+                "vector.",
+            )
+            nonlinear_constraints.append(
+                NonlinearConstraint(
+                    constraint.fun,
+                    *np.broadcast_arrays(lb, ub),
+                )
+            )
+        elif isinstance(constraint, dict):
+            if "type" not in constraint or constraint["type"] not in (
+                "eq",
+                "ineq",
+            ):
+                raise ValueError('The constraint type must be "eq" or "ineq".')
+            if "fun" not in constraint or not callable(constraint["fun"]):
+                raise ValueError("The constraint function must be callable.")
+            nonlinear_constraints.append(
+                {
+                    "fun": constraint["fun"],
+                    "type": constraint["type"],
+                    "args": constraint.get("args", ()),
+                }
+            )
+        else:
+            raise TypeError(
+                "The constraints must be instances of "
+                "scipy.optimize.LinearConstraint, "
+                "scipy.optimize.NonlinearConstraint, or dict."
+            )
+    return linear_constraints, nonlinear_constraints
+
+
+def _set_default_options(options, n):
+    """
+    Set the default options.
+    """
+    if Options.RHOBEG in options and options[Options.RHOBEG] <= 0.0:
+        raise ValueError("The initial trust-region radius must be positive.")
+    if Options.RHOEND in options and options[Options.RHOEND] < 0.0:
+        raise ValueError("The final trust-region radius must be nonnegative.")
+    if Options.RHOBEG in options and Options.RHOEND in options:
+        if options[Options.RHOBEG] < options[Options.RHOEND]:
+            raise ValueError(
+                "The initial trust-region radius must be greater "
+                "than or equal to the final trust-region radius."
+            )
+    elif Options.RHOBEG in options:
+        options[Options.RHOEND.value] = np.min(
+            [
+                DEFAULT_OPTIONS[Options.RHOEND],
+                options[Options.RHOBEG],
+            ]
+        )
+    elif Options.RHOEND in options:
+        options[Options.RHOBEG.value] = np.max(
+            [
+                DEFAULT_OPTIONS[Options.RHOBEG],
+                options[Options.RHOEND],
+            ]
+        )
+    else:
+        options[Options.RHOBEG.value] = DEFAULT_OPTIONS[Options.RHOBEG]
+        options[Options.RHOEND.value] = DEFAULT_OPTIONS[Options.RHOEND]
+    options[Options.RHOBEG.value] = float(options[Options.RHOBEG])
+    options[Options.RHOEND.value] = float(options[Options.RHOEND])
+    if Options.NPT in options and options[Options.NPT] <= 0:
+        raise ValueError("The number of interpolation points must be "
+                         "positive.")
+    if (
+        Options.NPT in options
+        and options[Options.NPT] > ((n + 1) * (n + 2)) // 2
+    ):
+        raise ValueError(
+            f"The number of interpolation points must be at most "
+            f"{((n + 1) * (n + 2)) // 2}."
+        )
+    options.setdefault(Options.NPT.value, DEFAULT_OPTIONS[Options.NPT](n))
+    options[Options.NPT.value] = int(options[Options.NPT])
+    if Options.MAX_EVAL in options and options[Options.MAX_EVAL] <= 0:
+        raise ValueError(
+            "The maximum number of function evaluations must be positive."
+        )
+    options.setdefault(
+        Options.MAX_EVAL.value,
+        np.max(
+            [
+                DEFAULT_OPTIONS[Options.MAX_EVAL](n),
+                options[Options.NPT] + 1,
+            ]
+        ),
+    )
+    options[Options.MAX_EVAL.value] = int(options[Options.MAX_EVAL])
+    if Options.MAX_ITER in options and options[Options.MAX_ITER] <= 0:
+        raise ValueError("The maximum number of iterations must be positive.")
+    options.setdefault(
+        Options.MAX_ITER.value,
+        DEFAULT_OPTIONS[Options.MAX_ITER](n),
+    )
+    options[Options.MAX_ITER.value] = int(options[Options.MAX_ITER])
+    options.setdefault(Options.TARGET.value, DEFAULT_OPTIONS[Options.TARGET])
+    options[Options.TARGET.value] = float(options[Options.TARGET])
+    options.setdefault(
+        Options.FEASIBILITY_TOL.value,
+        DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
+    )
+    options[Options.FEASIBILITY_TOL.value] = float(
+        options[Options.FEASIBILITY_TOL]
+    )
+    options.setdefault(Options.VERBOSE.value, DEFAULT_OPTIONS[Options.VERBOSE])
+    options[Options.VERBOSE.value] = bool(options[Options.VERBOSE])
+    options.setdefault(Options.SCALE.value, DEFAULT_OPTIONS[Options.SCALE])
+    options[Options.SCALE.value] = bool(options[Options.SCALE])
+    options.setdefault(
+        Options.FILTER_SIZE.value,
+        DEFAULT_OPTIONS[Options.FILTER_SIZE],
+    )
+    options[Options.FILTER_SIZE.value] = int(options[Options.FILTER_SIZE])
+    options.setdefault(
+        Options.STORE_HISTORY.value,
+        DEFAULT_OPTIONS[Options.STORE_HISTORY],
+    )
+    options[Options.STORE_HISTORY.value] = bool(options[Options.STORE_HISTORY])
+    options.setdefault(
+        Options.HISTORY_SIZE.value,
+        DEFAULT_OPTIONS[Options.HISTORY_SIZE],
+    )
+    options[Options.HISTORY_SIZE.value] = int(options[Options.HISTORY_SIZE])
+    options.setdefault(Options.DEBUG.value, DEFAULT_OPTIONS[Options.DEBUG])
+    options[Options.DEBUG.value] = bool(options[Options.DEBUG])
+
+    # Check whether they are any unknown options.
+    for key in options:
+        if key not in Options.__members__.values():
+            warnings.warn(f"Unknown option: {key}.", RuntimeWarning, 3)
+
+
+def _set_default_constants(**kwargs):
+    """
+    Set the default constants.
+    """
+    constants = dict(kwargs)
+    constants.setdefault(
+        Constants.DECREASE_RADIUS_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_FACTOR],
+    )
+    constants[Constants.DECREASE_RADIUS_FACTOR.value] = float(
+        constants[Constants.DECREASE_RADIUS_FACTOR]
+    )
+    if (
+        constants[Constants.DECREASE_RADIUS_FACTOR] <= 0.0
+        or constants[Constants.DECREASE_RADIUS_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant decrease_radius_factor must be in the interval "
+            "(0, 1)."
+        )
+    constants.setdefault(
+        Constants.INCREASE_RADIUS_THRESHOLD.value,
+        DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_THRESHOLD],
+    )
+    constants[Constants.INCREASE_RADIUS_THRESHOLD.value] = float(
+        constants[Constants.INCREASE_RADIUS_THRESHOLD]
+    )
+    if constants[Constants.INCREASE_RADIUS_THRESHOLD] <= 1.0:
+        raise ValueError(
+            "The constant increase_radius_threshold must be greater than 1."
+        )
+    if (
+        Constants.INCREASE_RADIUS_FACTOR in constants
+        and constants[Constants.INCREASE_RADIUS_FACTOR] <= 1.0
+    ):
+        raise ValueError(
+            "The constant increase_radius_factor must be greater than 1."
+        )
+    if (
+        Constants.DECREASE_RADIUS_THRESHOLD in constants
+        and constants[Constants.DECREASE_RADIUS_THRESHOLD] <= 1.0
+    ):
+        raise ValueError(
+            "The constant decrease_radius_threshold must be greater than 1."
+        )
+    if (
+        Constants.INCREASE_RADIUS_FACTOR in constants
+        and Constants.DECREASE_RADIUS_THRESHOLD in constants
+    ):
+        if (
+            constants[Constants.DECREASE_RADIUS_THRESHOLD]
+            >= constants[Constants.INCREASE_RADIUS_FACTOR]
+        ):
+            raise ValueError(
+                "The constant decrease_radius_threshold must be "
+                "less than increase_radius_factor."
+            )
+    elif Constants.INCREASE_RADIUS_FACTOR in constants:
+        constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD],
+                0.5 * (1.0 + constants[Constants.INCREASE_RADIUS_FACTOR]),
+            ]
+        )
+    elif Constants.DECREASE_RADIUS_THRESHOLD in constants:
+        constants[Constants.INCREASE_RADIUS_FACTOR.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_FACTOR],
+                2.0 * constants[Constants.DECREASE_RADIUS_THRESHOLD],
+            ]
+        )
+    else:
+        constants[Constants.INCREASE_RADIUS_FACTOR.value] = DEFAULT_CONSTANTS[
+            Constants.INCREASE_RADIUS_FACTOR
+        ]
+        constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD])
+    constants.setdefault(
+        Constants.DECREASE_RESOLUTION_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.DECREASE_RESOLUTION_FACTOR],
+    )
+    constants[Constants.DECREASE_RESOLUTION_FACTOR.value] = float(
+        constants[Constants.DECREASE_RESOLUTION_FACTOR]
+    )
+    if (
+        constants[Constants.DECREASE_RESOLUTION_FACTOR] <= 0.0
+        or constants[Constants.DECREASE_RESOLUTION_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant decrease_resolution_factor must be in the interval "
+            "(0, 1)."
+        )
+    if (
+        Constants.LARGE_RESOLUTION_THRESHOLD in constants
+        and constants[Constants.LARGE_RESOLUTION_THRESHOLD] <= 1.0
+    ):
+        raise ValueError(
+            "The constant large_resolution_threshold must be greater than 1."
+        )
+    if (
+        Constants.MODERATE_RESOLUTION_THRESHOLD in constants
+        and constants[Constants.MODERATE_RESOLUTION_THRESHOLD] <= 1.0
+    ):
+        raise ValueError(
+            "The constant moderate_resolution_threshold must be greater than "
+            "1."
+        )
+    if (
+        Constants.LARGE_RESOLUTION_THRESHOLD in constants
+        and Constants.MODERATE_RESOLUTION_THRESHOLD in constants
+    ):
+        if (
+            constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
+            > constants[Constants.LARGE_RESOLUTION_THRESHOLD]
+        ):
+            raise ValueError(
+                "The constant moderate_resolution_threshold "
+                "must be at most large_resolution_threshold."
+            )
+    elif Constants.LARGE_RESOLUTION_THRESHOLD in constants:
+        constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD],
+                constants[Constants.LARGE_RESOLUTION_THRESHOLD],
+            ]
+        )
+    elif Constants.MODERATE_RESOLUTION_THRESHOLD in constants:
+        constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD],
+                constants[Constants.MODERATE_RESOLUTION_THRESHOLD],
+            ]
+        )
+    else:
+        constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD]
+        )
+        constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD]
+        )
+    if Constants.LOW_RATIO in constants and (
+        constants[Constants.LOW_RATIO] <= 0.0
+        or constants[Constants.LOW_RATIO] >= 1.0
+    ):
+        raise ValueError(
+            "The constant low_ratio must be in the interval (0, 1)."
+        )
+    if Constants.HIGH_RATIO in constants and (
+        constants[Constants.HIGH_RATIO] <= 0.0
+        or constants[Constants.HIGH_RATIO] >= 1.0
+    ):
+        raise ValueError(
+            "The constant high_ratio must be in the interval (0, 1)."
+        )
+    if Constants.LOW_RATIO in constants and Constants.HIGH_RATIO in constants:
+        if constants[Constants.LOW_RATIO] > constants[Constants.HIGH_RATIO]:
+            raise ValueError(
+                "The constant low_ratio must be at most high_ratio."
+            )
+    elif Constants.LOW_RATIO in constants:
+        constants[Constants.HIGH_RATIO.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.HIGH_RATIO],
+                constants[Constants.LOW_RATIO],
+            ]
+        )
+    elif Constants.HIGH_RATIO in constants:
+        constants[Constants.LOW_RATIO.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.LOW_RATIO],
+                constants[Constants.HIGH_RATIO],
+            ]
+        )
+    else:
+        constants[Constants.LOW_RATIO.value] = DEFAULT_CONSTANTS[
+            Constants.LOW_RATIO
+        ]
+        constants[Constants.HIGH_RATIO.value] = DEFAULT_CONSTANTS[
+            Constants.HIGH_RATIO
+        ]
+    constants.setdefault(
+        Constants.VERY_LOW_RATIO.value,
+        DEFAULT_CONSTANTS[Constants.VERY_LOW_RATIO],
+    )
+    constants[Constants.VERY_LOW_RATIO.value] = float(
+        constants[Constants.VERY_LOW_RATIO]
+    )
+    if (
+        constants[Constants.VERY_LOW_RATIO] <= 0.0
+        or constants[Constants.VERY_LOW_RATIO] >= 1.0
+    ):
+        raise ValueError(
+            "The constant very_low_ratio must be in the interval (0, 1)."
+        )
+    if (
+        Constants.PENALTY_INCREASE_THRESHOLD in constants
+        and constants[Constants.PENALTY_INCREASE_THRESHOLD] < 1.0
+    ):
+        raise ValueError(
+            "The constant penalty_increase_threshold must be "
+            "greater than or equal to 1."
+        )
+    if (
+        Constants.PENALTY_INCREASE_FACTOR in constants
+        and constants[Constants.PENALTY_INCREASE_FACTOR] <= 1.0
+    ):
+        raise ValueError(
+            "The constant penalty_increase_factor must be greater than 1."
+        )
+    if (
+        Constants.PENALTY_INCREASE_THRESHOLD in constants
+        and Constants.PENALTY_INCREASE_FACTOR in constants
+    ):
+        if (
+            constants[Constants.PENALTY_INCREASE_FACTOR]
+            < constants[Constants.PENALTY_INCREASE_THRESHOLD]
+        ):
+            raise ValueError(
+                "The constant penalty_increase_factor must be "
+                "greater than or equal to "
+                "penalty_increase_threshold."
+            )
+    elif Constants.PENALTY_INCREASE_THRESHOLD in constants:
+        constants[Constants.PENALTY_INCREASE_FACTOR.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_FACTOR],
+                constants[Constants.PENALTY_INCREASE_THRESHOLD],
+            ]
+        )
+    elif Constants.PENALTY_INCREASE_FACTOR in constants:
+        constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD],
+                constants[Constants.PENALTY_INCREASE_FACTOR],
+            ]
+        )
+    else:
+        constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD]
+        )
+        constants[Constants.PENALTY_INCREASE_FACTOR.value] = DEFAULT_CONSTANTS[
+            Constants.PENALTY_INCREASE_FACTOR
+        ]
+    constants.setdefault(
+        Constants.SHORT_STEP_THRESHOLD.value,
+        DEFAULT_CONSTANTS[Constants.SHORT_STEP_THRESHOLD],
+    )
+    constants[Constants.SHORT_STEP_THRESHOLD.value] = float(
+        constants[Constants.SHORT_STEP_THRESHOLD]
+    )
+    if (
+        constants[Constants.SHORT_STEP_THRESHOLD] <= 0.0
+        or constants[Constants.SHORT_STEP_THRESHOLD] >= 1.0
+    ):
+        raise ValueError(
+            "The constant short_step_threshold must be in the interval (0, 1)."
+        )
+    constants.setdefault(
+        Constants.LOW_RADIUS_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.LOW_RADIUS_FACTOR],
+    )
+    constants[Constants.LOW_RADIUS_FACTOR.value] = float(
+        constants[Constants.LOW_RADIUS_FACTOR]
+    )
+    if (
+        constants[Constants.LOW_RADIUS_FACTOR] <= 0.0
+        or constants[Constants.LOW_RADIUS_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant low_radius_factor must be in the interval (0, 1)."
+        )
+    constants.setdefault(
+        Constants.BYRD_OMOJOKUN_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.BYRD_OMOJOKUN_FACTOR],
+    )
+    constants[Constants.BYRD_OMOJOKUN_FACTOR.value] = float(
+        constants[Constants.BYRD_OMOJOKUN_FACTOR]
+    )
+    if (
+        constants[Constants.BYRD_OMOJOKUN_FACTOR] <= 0.0
+        or constants[Constants.BYRD_OMOJOKUN_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant byrd_omojokun_factor must be in the interval (0, 1)."
+        )
+    constants.setdefault(
+        Constants.THRESHOLD_RATIO_CONSTRAINTS.value,
+        DEFAULT_CONSTANTS[Constants.THRESHOLD_RATIO_CONSTRAINTS],
+    )
+    constants[Constants.THRESHOLD_RATIO_CONSTRAINTS.value] = float(
+        constants[Constants.THRESHOLD_RATIO_CONSTRAINTS]
+    )
+    if constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] <= 1.0:
+        raise ValueError(
+            "The constant threshold_ratio_constraints must be greater than 1."
+        )
+    constants.setdefault(
+        Constants.LARGE_SHIFT_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.LARGE_SHIFT_FACTOR],
+    )
+    constants[Constants.LARGE_SHIFT_FACTOR.value] = float(
+        constants[Constants.LARGE_SHIFT_FACTOR]
+    )
+    if constants[Constants.LARGE_SHIFT_FACTOR] < 0.0:
+        raise ValueError("The constant large_shift_factor must be "
+                         "nonnegative.")
+    constants.setdefault(
+        Constants.LARGE_GRADIENT_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.LARGE_GRADIENT_FACTOR],
+    )
+    constants[Constants.LARGE_GRADIENT_FACTOR.value] = float(
+        constants[Constants.LARGE_GRADIENT_FACTOR]
+    )
+    if constants[Constants.LARGE_GRADIENT_FACTOR] <= 1.0:
+        raise ValueError(
+            "The constant large_gradient_factor must be greater than 1."
+        )
+    constants.setdefault(
+        Constants.RESOLUTION_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.RESOLUTION_FACTOR],
+    )
+    constants[Constants.RESOLUTION_FACTOR.value] = float(
+        constants[Constants.RESOLUTION_FACTOR]
+    )
+    if constants[Constants.RESOLUTION_FACTOR] <= 1.0:
+        raise ValueError(
+            "The constant resolution_factor must be greater than 1."
+        )
+    constants.setdefault(
+        Constants.IMPROVE_TCG.value,
+        DEFAULT_CONSTANTS[Constants.IMPROVE_TCG],
+    )
+    constants[Constants.IMPROVE_TCG.value] = bool(
+        constants[Constants.IMPROVE_TCG]
+    )
+
+    # Check whether they are any unknown options.
+    for key in kwargs:
+        if key not in Constants.__members__.values():
+            warnings.warn(f"Unknown constant: {key}.", RuntimeWarning, 3)
+    return constants
+
+
+def _eval(pb, framework, step, options):
+    """
+    Evaluate the objective and constraint functions.
+    """
+    if pb.n_eval >= options[Options.MAX_EVAL]:
+        raise MaxEvalError
+    x_eval = framework.x_best + step
+    fun_val, cub_val, ceq_val = pb(x_eval, framework.penalty)
+    r_val = pb.maxcv(x_eval, cub_val, ceq_val)
+    if (
+        fun_val <= options[Options.TARGET]
+        and r_val <= options[Options.FEASIBILITY_TOL]
+    ):
+        raise TargetSuccess
+    if pb.is_feasibility and r_val <= options[Options.FEASIBILITY_TOL]:
+        raise FeasibleSuccess
+    return fun_val, cub_val, ceq_val
+
+
+def _build_result(pb, penalty, success, status, n_iter, options):
+    """
+    Build the result of the optimization process.
+    """
+    # Build the result.
+    x, fun, maxcv = pb.best_eval(penalty)
+    success = success and np.isfinite(fun) and np.isfinite(maxcv)
+    if status not in [ExitStatus.TARGET_SUCCESS, ExitStatus.FEASIBLE_SUCCESS]:
+        success = success and maxcv <= options[Options.FEASIBILITY_TOL]
+    result = OptimizeResult()
+    result.message = {
+        ExitStatus.RADIUS_SUCCESS: "The lower bound for the trust-region "
+                                   "radius has been reached",
+        ExitStatus.TARGET_SUCCESS: "The target objective function value has "
+                                   "been reached",
+        ExitStatus.FIXED_SUCCESS: "All variables are fixed by the bound "
+                                  "constraints",
+        ExitStatus.CALLBACK_SUCCESS: "The callback requested to stop the "
+                                     "optimization procedure",
+        ExitStatus.FEASIBLE_SUCCESS: "The feasibility problem received has "
+                                     "been solved successfully",
+        ExitStatus.MAX_EVAL_WARNING: "The maximum number of function "
+                                     "evaluations has been exceeded",
+        ExitStatus.MAX_ITER_WARNING: "The maximum number of iterations has "
+                                     "been exceeded",
+        ExitStatus.INFEASIBLE_ERROR: "The bound constraints are infeasible",
+        ExitStatus.LINALG_ERROR: "A linear algebra error occurred",
+    }.get(status, "Unknown exit status")
+    result.success = success
+    result.status = status.value
+    result.x = pb.build_x(x)
+    result.fun = fun
+    result.maxcv = maxcv
+    result.nfev = pb.n_eval
+    result.nit = n_iter
+    if options[Options.STORE_HISTORY]:
+        result.fun_history = pb.fun_history
+        result.maxcv_history = pb.maxcv_history
+
+    # Print the result if requested.
+    if options[Options.VERBOSE]:
+        _print_step(
+            result.message,
+            pb,
+            result.x,
+            result.fun,
+            result.maxcv,
+            result.nfev,
+            result.nit,
+        )
+    return result
+
+
+def _print_step(message, pb, x, fun_val, r_val, n_eval, n_iter):
+    """
+    Print information about the current state of the optimization process.
+    """
+    print()
+    print(f"{message}.")
+    print(f"Number of function evaluations: {n_eval}.")
+    print(f"Number of iterations: {n_iter}.")
+    if not pb.is_feasibility:
+        print(f"Least value of {pb.fun_name}: {fun_val}.")
+    print(f"Maximum constraint violation: {r_val}.")
+    with np.printoptions(**PRINT_OPTIONS):
+        print(f"Corresponding point: {x}.")
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..4891b074bfd6dd3f7d43fa95b0b845a764cac114
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py
@@ -0,0 +1,1529 @@
+import warnings
+
+import numpy as np
+from scipy.linalg import eigh
+
+from .settings import Options
+from .utils import MaxEvalError, TargetSuccess, FeasibleSuccess
+
+
+EPS = np.finfo(float).eps
+
+
+class Interpolation:
+    """
+    Interpolation set.
+
+    This class stores a base point around which the models are expanded and the
+    interpolation points. The coordinates of the interpolation points are
+    relative to the base point.
+    """
+
+    def __init__(self, pb, options):
+        """
+        Initialize the interpolation set.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to be solved.
+        options : dict
+            Options of the solver.
+        """
+        # Reduce the initial trust-region radius if necessary.
+        self._debug = options[Options.DEBUG]
+        max_radius = 0.5 * np.min(pb.bounds.xu - pb.bounds.xl)
+        if options[Options.RHOBEG] > max_radius:
+            options[Options.RHOBEG.value] = max_radius
+            options[Options.RHOEND.value] = np.min(
+                [
+                    options[Options.RHOEND],
+                    max_radius,
+                ]
+            )
+
+        # Set the initial point around which the models are expanded.
+        self._x_base = np.copy(pb.x0)
+        very_close_xl_idx = (
+            self.x_base <= pb.bounds.xl + 0.5 * options[Options.RHOBEG]
+        )
+        self.x_base[very_close_xl_idx] = pb.bounds.xl[very_close_xl_idx]
+        close_xl_idx = (
+            pb.bounds.xl + 0.5 * options[Options.RHOBEG] < self.x_base
+        ) & (self.x_base <= pb.bounds.xl + options[Options.RHOBEG])
+        self.x_base[close_xl_idx] = np.minimum(
+            pb.bounds.xl[close_xl_idx] + options[Options.RHOBEG],
+            pb.bounds.xu[close_xl_idx],
+        )
+        very_close_xu_idx = (
+            self.x_base >= pb.bounds.xu - 0.5 * options[Options.RHOBEG]
+        )
+        self.x_base[very_close_xu_idx] = pb.bounds.xu[very_close_xu_idx]
+        close_xu_idx = (
+            self.x_base < pb.bounds.xu - 0.5 * options[Options.RHOBEG]
+        ) & (pb.bounds.xu - options[Options.RHOBEG] <= self.x_base)
+        self.x_base[close_xu_idx] = np.maximum(
+            pb.bounds.xu[close_xu_idx] - options[Options.RHOBEG],
+            pb.bounds.xl[close_xu_idx],
+        )
+
+        # Set the initial interpolation set.
+        self._xpt = np.zeros((pb.n, options[Options.NPT]))
+        for k in range(1, options[Options.NPT]):
+            if k <= pb.n:
+                if very_close_xu_idx[k - 1]:
+                    self.xpt[k - 1, k] = -options[Options.RHOBEG]
+                else:
+                    self.xpt[k - 1, k] = options[Options.RHOBEG]
+            elif k <= 2 * pb.n:
+                if very_close_xl_idx[k - pb.n - 1]:
+                    self.xpt[k - pb.n - 1, k] = 2.0 * options[Options.RHOBEG]
+                elif very_close_xu_idx[k - pb.n - 1]:
+                    self.xpt[k - pb.n - 1, k] = -2.0 * options[Options.RHOBEG]
+                else:
+                    self.xpt[k - pb.n - 1, k] = -options[Options.RHOBEG]
+            else:
+                spread = (k - pb.n - 1) // pb.n
+                k1 = k - (1 + spread) * pb.n - 1
+                k2 = (k1 + spread) % pb.n
+                self.xpt[k1, k] = self.xpt[k1, k1 + 1]
+                self.xpt[k2, k] = self.xpt[k2, k2 + 1]
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self.xpt.shape[0]
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points.
+
+        Returns
+        -------
+        int
+            Number of interpolation points.
+        """
+        return self.xpt.shape[1]
+
+    @property
+    def xpt(self):
+        """
+        Interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, npt)
+            Interpolation points.
+        """
+        return self._xpt
+
+    @xpt.setter
+    def xpt(self, xpt):
+        """
+        Set the interpolation points.
+
+        Parameters
+        ----------
+        xpt : `numpy.ndarray`, shape (n, npt)
+            New interpolation points.
+        """
+        if self._debug:
+            assert xpt.shape == (
+                self.n,
+                self.npt,
+            ), "The shape of `xpt` is not valid."
+        self._xpt = xpt
+
+    @property
+    def x_base(self):
+        """
+        Base point around which the models are expanded.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Base point around which the models are expanded.
+        """
+        return self._x_base
+
+    @x_base.setter
+    def x_base(self, x_base):
+        """
+        Set the base point around which the models are expanded.
+
+        Parameters
+        ----------
+        x_base : `numpy.ndarray`, shape (n,)
+            New base point around which the models are expanded.
+        """
+        if self._debug:
+            assert x_base.shape == (
+                self.n,
+            ), "The shape of `x_base` is not valid."
+        self._x_base = x_base
+
+    def point(self, k):
+        """
+        Get the `k`-th interpolation point.
+
+        The return point is relative to the origin.
+
+        Parameters
+        ----------
+        k : int
+            Index of the interpolation point.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            `k`-th interpolation point.
+        """
+        if self._debug:
+            assert 0 <= k < self.npt, "The index `k` is not valid."
+        return self.x_base + self.xpt[:, k]
+
+
+_cache = {"xpt": None, "a": None, "right_scaling": None, "eigh": None}
+
+
+def build_system(interpolation):
+    """
+    Build the left-hand side matrix of the interpolation system. The
+    matrix below stores W * diag(right_scaling),
+    where W is the theoretical matrix of the interpolation system. The
+    right scaling matrices is chosen to keep the elements in
+    the matrix well-balanced.
+
+    Parameters
+    ----------
+    interpolation : `cobyqa.models.Interpolation`
+        Interpolation set.
+    """
+
+    # Compute the scaled directions from the base point to the
+    # interpolation points. We scale the directions to avoid numerical
+    # difficulties.
+    if _cache["xpt"] is not None and np.array_equal(
+        interpolation.xpt, _cache["xpt"]
+    ):
+        return _cache["a"], _cache["right_scaling"], _cache["eigh"]
+
+    scale = np.max(np.linalg.norm(interpolation.xpt, axis=0), initial=EPS)
+    xpt_scale = interpolation.xpt / scale
+
+    n, npt = xpt_scale.shape
+    a = np.zeros((npt + n + 1, npt + n + 1))
+    a[:npt, :npt] = 0.5 * (xpt_scale.T @ xpt_scale) ** 2.0
+    a[:npt, npt] = 1.0
+    a[:npt, npt + 1:] = xpt_scale.T
+    a[npt, :npt] = 1.0
+    a[npt + 1:, :npt] = xpt_scale
+
+    # Build the left and right scaling diagonal matrices.
+    right_scaling = np.empty(npt + n + 1)
+    right_scaling[:npt] = 1.0 / scale**2.0
+    right_scaling[npt] = scale**2.0
+    right_scaling[npt + 1:] = scale
+
+    eig_values, eig_vectors = eigh(a, check_finite=False)
+
+    _cache["xpt"] = np.copy(interpolation.xpt)
+    _cache["a"] = np.copy(a)
+    _cache["right_scaling"] = np.copy(right_scaling)
+    _cache["eigh"] = (eig_values, eig_vectors)
+
+    return a, right_scaling, (eig_values, eig_vectors)
+
+
+class Quadratic:
+    """
+    Quadratic model.
+
+    This class stores the Hessian matrix of the quadratic model using the
+    implicit/explicit representation designed by Powell for NEWUOA [1]_.
+
+    References
+    ----------
+    .. [1] M. J. D. Powell. The NEWUOA software for unconstrained optimization
+       without derivatives. In G. Di Pillo and M. Roma, editors, *Large-Scale
+       Nonlinear Optimization*, volume 83 of Nonconvex Optim. Appl., pages
+       255--297. Springer, Boston, MA, USA, 2006. `doi:10.1007/0-387-30065-1_16
+       `_.
+    """
+
+    def __init__(self, interpolation, values, debug):
+        """
+        Initialize the quadratic model.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        values : `numpy.ndarray`, shape (npt,)
+            Values of the interpolated function at the interpolation points.
+        debug : bool
+            Whether to make debugging tests during the execution.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        self._debug = debug
+        if self._debug:
+            assert values.shape == (
+                interpolation.npt,
+            ), "The shape of `values` is not valid."
+        if interpolation.npt < interpolation.n + 1:
+            raise ValueError(
+                f"The number of interpolation points must be at least "
+                f"{interpolation.n + 1}."
+            )
+        self._const, self._grad, self._i_hess, _ = self._get_model(
+            interpolation,
+            values,
+        )
+        self._e_hess = np.zeros((self.n, self.n))
+
+    def __call__(self, x, interpolation):
+        """
+        Evaluate the quadratic model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the quadratic model is evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        float
+            Value of the quadratic model at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        x_diff = x - interpolation.x_base
+        return (
+            self._const
+            + self._grad @ x_diff
+            + 0.5
+            * (
+                self._i_hess @ (interpolation.xpt.T @ x_diff) ** 2.0
+                + x_diff @ self._e_hess @ x_diff
+            )
+        )
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self._grad.size
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points used to define the quadratic model.
+
+        Returns
+        -------
+        int
+            Number of interpolation points used to define the quadratic model.
+        """
+        return self._i_hess.size
+
+    def grad(self, x, interpolation):
+        """
+        Evaluate the gradient of the quadratic model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the gradient of the quadratic model is evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        x_diff = x - interpolation.x_base
+        return self._grad + self.hess_prod(x_diff, interpolation)
+
+    def hess(self, interpolation):
+        """
+        Evaluate the Hessian matrix of the quadratic model.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the quadratic model.
+        """
+        return self._e_hess + interpolation.xpt @ (
+            self._i_hess[:, np.newaxis] * interpolation.xpt.T
+        )
+
+    def hess_prod(self, v, interpolation):
+        """
+        Evaluate the right product of the Hessian matrix of the quadratic model
+        with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the quadratic model is
+            multiplied from the right.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the quadratic model with
+            `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._e_hess @ v + interpolation.xpt @ (
+            self._i_hess * (interpolation.xpt.T @ v)
+        )
+
+    def curv(self, v, interpolation):
+        """
+        Evaluate the curvature of the quadratic model along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic model is
+            evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        float
+            Curvature of the quadratic model along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return (
+            v @ self._e_hess @ v
+            + self._i_hess @ (interpolation.xpt.T @ v) ** 2.0
+        )
+
+    def update(self, interpolation, k_new, dir_old, values_diff):
+        """
+        Update the quadratic model.
+
+        This method applies the derivative-free symmetric Broyden update to the
+        quadratic model. The `knew`-th interpolation point must be updated
+        before calling this method.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Updated interpolation set.
+        k_new : int
+            Index of the updated interpolation point.
+        dir_old : `numpy.ndarray`, shape (n,)
+            Value of ``interpolation.xpt[:, k_new]`` before the update.
+        values_diff : `numpy.ndarray`, shape (npt,)
+            Differences between the values of the interpolated nonlinear
+            function and the previous quadratic model at the updated
+            interpolation points.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
+            assert dir_old.shape == (
+                self.n,
+            ), "The shape of `dir_old` is not valid."
+            assert values_diff.shape == (
+                self.npt,
+            ), "The shape of `values_diff` is not valid."
+
+        # Forward the k_new-th element of the implicit Hessian matrix to the
+        # explicit Hessian matrix. This must be done because the implicit
+        # Hessian matrix is related to the interpolation points, and the
+        # k_new-th interpolation point is modified.
+        self._e_hess += self._i_hess[k_new] * np.outer(dir_old, dir_old)
+        self._i_hess[k_new] = 0.0
+
+        # Update the quadratic model.
+        const, grad, i_hess, ill_conditioned = self._get_model(
+            interpolation,
+            values_diff,
+        )
+        self._const += const
+        self._grad += grad
+        self._i_hess += i_hess
+        return ill_conditioned
+
+    def shift_x_base(self, interpolation, new_x_base):
+        """
+        Shift the point around which the quadratic model is defined.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Previous interpolation set.
+        new_x_base : `numpy.ndarray`, shape (n,)
+            Point that will replace ``interpolation.x_base``.
+        """
+        if self._debug:
+            assert new_x_base.shape == (
+                self.n,
+            ), "The shape of `new_x_base` is not valid."
+        self._const = self(new_x_base, interpolation)
+        self._grad = self.grad(new_x_base, interpolation)
+        shift = new_x_base - interpolation.x_base
+        update = np.outer(
+            shift,
+            (interpolation.xpt - 0.5 * shift[:, np.newaxis]) @ self._i_hess,
+        )
+        self._e_hess += update + update.T
+
+    @staticmethod
+    def solve_systems(interpolation, rhs):
+        """
+        Solve the interpolation systems.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        rhs : `numpy.ndarray`, shape (npt + n + 1, m)
+            Right-hand side vectors of the ``m`` interpolation systems.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt + n + 1, m)
+            Solutions of the interpolation systems.
+        `numpy.ndarray`, shape (m, )
+            Whether the interpolation systems are ill-conditioned.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation systems are ill-defined.
+        """
+        n, npt = interpolation.xpt.shape
+        assert (
+            rhs.ndim == 2 and rhs.shape[0] == npt + n + 1
+        ), "The shape of `rhs` is not valid."
+
+        # Build the left-hand side matrix of the interpolation system. The
+        # matrix below stores diag(left_scaling) * W * diag(right_scaling),
+        # where W is the theoretical matrix of the interpolation system. The
+        # left and right scaling matrices are chosen to keep the elements in
+        # the matrix well-balanced.
+        a, right_scaling, eig = build_system(interpolation)
+
+        # Build the solution. After a discussion with Mike Saunders and Alexis
+        # Montoison during their visit to the Hong Kong Polytechnic University
+        # in 2024, we decided to use the eigendecomposition of the symmetric
+        # matrix a. This is more stable than the previously employed LBL
+        # decomposition, and allows us to directly detect ill-conditioning of
+        # the system and to build the least-squares solution if necessary.
+        # Numerical experiments have shown that this strategy improves the
+        # performance of the solver.
+        rhs_scaled = rhs * right_scaling[:, np.newaxis]
+        if not (np.all(np.isfinite(a)) and np.all(np.isfinite(rhs_scaled))):
+            raise np.linalg.LinAlgError(
+                "The interpolation system is ill-defined."
+            )
+
+        # calculated in build_system
+        eig_values, eig_vectors = eig
+
+        large_eig_values = np.abs(eig_values) > EPS
+        eig_vectors = eig_vectors[:, large_eig_values]
+        inv_eig_values = 1.0 / eig_values[large_eig_values]
+        ill_conditioned = ~np.all(large_eig_values, 0)
+        left_scaled_solutions = eig_vectors @ (
+            (eig_vectors.T @ rhs_scaled) * inv_eig_values[:, np.newaxis]
+        )
+        return (
+            left_scaled_solutions * right_scaling[:, np.newaxis],
+            ill_conditioned,
+        )
+
+    @staticmethod
+    def _get_model(interpolation, values):
+        """
+        Solve the interpolation system.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        values : `numpy.ndarray`, shape (npt,)
+            Values of the interpolated function at the interpolation points.
+
+        Returns
+        -------
+        float
+            Constant term of the quadratic model.
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model at ``interpolation.x_base``.
+        `numpy.ndarray`, shape (npt,)
+            Implicit Hessian matrix of the quadratic model.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        assert values.shape == (
+            interpolation.npt,
+        ), "The shape of `values` is not valid."
+        n, npt = interpolation.xpt.shape
+        x, ill_conditioned = Quadratic.solve_systems(
+            interpolation,
+            np.block(
+                [
+                    [
+                        values,
+                        np.zeros(n + 1),
+                    ]
+                ]
+            ).T,
+        )
+        return x[npt, 0], x[npt + 1:, 0], x[:npt, 0], ill_conditioned
+
+
+class Models:
+    """
+    Models for a nonlinear optimization problem.
+    """
+
+    def __init__(self, pb, options, penalty):
+        """
+        Initialize the models.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to be solved.
+        options : dict
+            Options of the solver.
+        penalty : float
+            Penalty parameter used to select the point in the filter to forward
+            to the callback function.
+
+        Raises
+        ------
+        `cobyqa.utils.MaxEvalError`
+            If the maximum number of evaluations is reached.
+        `cobyqa.utils.TargetSuccess`
+            If a nearly feasible point has been found with an objective
+            function value below the target.
+        `cobyqa.utils.FeasibleSuccess`
+            If a feasible point has been found for a feasibility problem.
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        # Set the initial interpolation set.
+        self._debug = options[Options.DEBUG]
+        self._interpolation = Interpolation(pb, options)
+
+        # Evaluate the nonlinear functions at the initial interpolation points.
+        x_eval = self.interpolation.point(0)
+        fun_init, cub_init, ceq_init = pb(x_eval, penalty)
+        self._fun_val = np.full(options[Options.NPT], np.nan)
+        self._cub_val = np.full((options[Options.NPT], cub_init.size), np.nan)
+        self._ceq_val = np.full((options[Options.NPT], ceq_init.size), np.nan)
+        for k in range(options[Options.NPT]):
+            if k >= options[Options.MAX_EVAL]:
+                raise MaxEvalError
+            if k == 0:
+                self.fun_val[k] = fun_init
+                self.cub_val[k, :] = cub_init
+                self.ceq_val[k, :] = ceq_init
+            else:
+                x_eval = self.interpolation.point(k)
+                self.fun_val[k], self.cub_val[k, :], self.ceq_val[k, :] = pb(
+                    x_eval,
+                    penalty,
+                )
+
+            # Stop the iterations if the problem is a feasibility problem and
+            # the current interpolation point is feasible.
+            if (
+                pb.is_feasibility
+                and pb.maxcv(
+                    self.interpolation.point(k),
+                    self.cub_val[k, :],
+                    self.ceq_val[k, :],
+                )
+                <= options[Options.FEASIBILITY_TOL]
+            ):
+                raise FeasibleSuccess
+
+            # Stop the iterations if the current interpolation point is nearly
+            # feasible and has an objective function value below the target.
+            if (
+                self._fun_val[k] <= options[Options.TARGET]
+                and pb.maxcv(
+                    self.interpolation.point(k),
+                    self.cub_val[k, :],
+                    self.ceq_val[k, :],
+                )
+                <= options[Options.FEASIBILITY_TOL]
+            ):
+                raise TargetSuccess
+
+        # Build the initial quadratic models.
+        self._fun = Quadratic(
+            self.interpolation,
+            self._fun_val,
+            options[Options.DEBUG],
+        )
+        self._cub = np.empty(self.m_nonlinear_ub, dtype=Quadratic)
+        self._ceq = np.empty(self.m_nonlinear_eq, dtype=Quadratic)
+        for i in range(self.m_nonlinear_ub):
+            self._cub[i] = Quadratic(
+                self.interpolation,
+                self.cub_val[:, i],
+                options[Options.DEBUG],
+            )
+        for i in range(self.m_nonlinear_eq):
+            self._ceq[i] = Quadratic(
+                self.interpolation,
+                self.ceq_val[:, i],
+                options[Options.DEBUG],
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+
+    @property
+    def n(self):
+        """
+        Dimension of the problem.
+
+        Returns
+        -------
+        int
+            Dimension of the problem.
+        """
+        return self.interpolation.n
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points.
+
+        Returns
+        -------
+        int
+            Number of interpolation points.
+        """
+        return self.interpolation.npt
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+        """
+        return self.cub_val.shape[1]
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+        """
+        return self.ceq_val.shape[1]
+
+    @property
+    def interpolation(self):
+        """
+        Interpolation set.
+
+        Returns
+        -------
+        `cobyqa.models.Interpolation`
+            Interpolation set.
+        """
+        return self._interpolation
+
+    @property
+    def fun_val(self):
+        """
+        Values of the objective function at the interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt,)
+            Values of the objective function at the interpolation points.
+        """
+        return self._fun_val
+
+    @property
+    def cub_val(self):
+        """
+        Values of the nonlinear inequality constraint functions at the
+        interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt, m_nonlinear_ub)
+            Values of the nonlinear inequality constraint functions at the
+            interpolation points.
+        """
+        return self._cub_val
+
+    @property
+    def ceq_val(self):
+        """
+        Values of the nonlinear equality constraint functions at the
+        interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt, m_nonlinear_eq)
+            Values of the nonlinear equality constraint functions at the
+            interpolation points.
+        """
+        return self._ceq_val
+
+    def fun(self, x):
+        """
+        Evaluate the quadratic model of the objective function at a given
+        point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic model of the objective
+            function.
+
+        Returns
+        -------
+        float
+            Value of the quadratic model of the objective function at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        return self._fun(x, self.interpolation)
+
+    def fun_grad(self, x):
+        """
+        Evaluate the gradient of the quadratic model of the objective function
+        at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradient of the quadratic model of
+            the objective function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model of the objective function at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        return self._fun.grad(x, self.interpolation)
+
+    def fun_hess(self):
+        """
+        Evaluate the Hessian matrix of the quadratic model of the objective
+        function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the quadratic model of the objective function.
+        """
+        return self._fun.hess(self.interpolation)
+
+    def fun_hess_prod(self, v):
+        """
+        Evaluate the right product of the Hessian matrix of the quadratic model
+        of the objective function with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the quadratic model of the
+            objective function is multiplied from the right.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the quadratic model of the
+            objective function with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._fun.hess_prod(v, self.interpolation)
+
+    def fun_curv(self, v):
+        """
+        Evaluate the curvature of the quadratic model of the objective function
+        along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic model of the
+            objective function is evaluated.
+
+        Returns
+        -------
+        float
+            Curvature of the quadratic model of the objective function along
+            `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._fun.curv(v, self.interpolation)
+
+    def fun_alt_grad(self, x):
+        """
+        Evaluate the gradient of the alternative quadratic model of the
+        objective function at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradient of the alternative
+            quadratic model of the objective function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the alternative quadratic model of the objective
+            function at `x`.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        model = Quadratic(self.interpolation, self.fun_val, self._debug)
+        return model.grad(x, self.interpolation)
+
+    def cub(self, x, mask=None):
+        """
+        Evaluate the quadratic models of the nonlinear inequality functions at
+        a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic models of the nonlinear
+            inequality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Values of the quadratic model of the nonlinear inequality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model(x, self.interpolation) for model in self._get_cub(mask)]
+        )
+
+    def cub_grad(self, x, mask=None):
+        """
+        Evaluate the gradients of the quadratic models of the nonlinear
+        inequality functions at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradients of the quadratic models of
+            the nonlinear inequality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Gradients of the quadratic model of the nonlinear inequality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.grad(x, self.interpolation)
+             for model in self._get_cub(mask)],
+            (-1, self.n),
+        )
+
+    def cub_hess(self, mask=None):
+        """
+        Evaluate the Hessian matrices of the quadratic models of the nonlinear
+        inequality functions.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Hessian matrices of the quadratic models of the nonlinear
+            inequality functions.
+        """
+        if self._debug:
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.hess(self.interpolation) for model in self._get_cub(mask)],
+            (-1, self.n, self.n),
+        )
+
+    def cub_hess_prod(self, v, mask=None):
+        """
+        Evaluate the right product of the Hessian matrices of the quadratic
+        models of the nonlinear inequality functions with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrices of the quadratic models of
+            the nonlinear inequality functions are multiplied from the right.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Right products of the Hessian matrices of the quadratic models of
+            the nonlinear inequality functions with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [
+                model.hess_prod(v, self.interpolation)
+                for model in self._get_cub(mask)
+            ],
+            (-1, self.n),
+        )
+
+    def cub_curv(self, v, mask=None):
+        """
+        Evaluate the curvature of the quadratic models of the nonlinear
+        inequality functions along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic models of the
+            nonlinear inequality functions is evaluated.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Curvature of the quadratic models of the nonlinear inequality
+            functions along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model.curv(v, self.interpolation)
+             for model in self._get_cub(mask)]
+        )
+
+    def ceq(self, x, mask=None):
+        """
+        Evaluate the quadratic models of the nonlinear equality functions at a
+        given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic models of the nonlinear
+            equality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Values of the quadratic model of the nonlinear equality functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model(x, self.interpolation) for model in self._get_ceq(mask)]
+        )
+
+    def ceq_grad(self, x, mask=None):
+        """
+        Evaluate the gradients of the quadratic models of the nonlinear
+        equality functions at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradients of the quadratic models of
+            the nonlinear equality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Gradients of the quadratic model of the nonlinear equality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.grad(x, self.interpolation)
+             for model in self._get_ceq(mask)],
+            (-1, self.n),
+        )
+
+    def ceq_hess(self, mask=None):
+        """
+        Evaluate the Hessian matrices of the quadratic models of the nonlinear
+        equality functions.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Hessian matrices of the quadratic models of the nonlinear equality
+            functions.
+        """
+        if self._debug:
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.hess(self.interpolation) for model in self._get_ceq(mask)],
+            (-1, self.n, self.n),
+        )
+
+    def ceq_hess_prod(self, v, mask=None):
+        """
+        Evaluate the right product of the Hessian matrices of the quadratic
+        models of the nonlinear equality functions with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrices of the quadratic models of
+            the nonlinear equality functions are multiplied from the right.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Right products of the Hessian matrices of the quadratic models of
+            the nonlinear equality functions with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [
+                model.hess_prod(v, self.interpolation)
+                for model in self._get_ceq(mask)
+            ],
+            (-1, self.n),
+        )
+
+    def ceq_curv(self, v, mask=None):
+        """
+        Evaluate the curvature of the quadratic models of the nonlinear
+        equality functions along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic models of the
+            nonlinear equality functions is evaluated.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Curvature of the quadratic models of the nonlinear equality
+            functions along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model.curv(v, self.interpolation)
+             for model in self._get_ceq(mask)]
+        )
+
+    def reset_models(self):
+        """
+        Set the quadratic models of the objective function, nonlinear
+        inequality constraints, and nonlinear equality constraints to the
+        alternative quadratic models.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        self._fun = Quadratic(self.interpolation, self.fun_val, self._debug)
+        for i in range(self.m_nonlinear_ub):
+            self._cub[i] = Quadratic(
+                self.interpolation,
+                self.cub_val[:, i],
+                self._debug,
+            )
+        for i in range(self.m_nonlinear_eq):
+            self._ceq[i] = Quadratic(
+                self.interpolation,
+                self.ceq_val[:, i],
+                self._debug,
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+
+    def update_interpolation(self, k_new, x_new, fun_val, cub_val, ceq_val):
+        """
+        Update the interpolation set.
+
+        This method updates the interpolation set by replacing the `knew`-th
+        interpolation point with `xnew`. It also updates the function values
+        and the quadratic models.
+
+        Parameters
+        ----------
+        k_new : int
+            Index of the updated interpolation point.
+        x_new : `numpy.ndarray`, shape (n,)
+            New interpolation point. Its value is interpreted as relative to
+            the origin, not the base point.
+        fun_val : float
+            Value of the objective function at `x_new`.
+            Objective function value at `x_new`.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Values of the nonlinear inequality constraints at `x_new`.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Values of the nonlinear equality constraints at `x_new`.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
+            assert x_new.shape == (self.n,), \
+                "The shape of `x_new` is not valid."
+            assert isinstance(fun_val, float), \
+                "The function value is not valid."
+            assert cub_val.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `cub_val` is not valid."
+            assert ceq_val.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `ceq_val` is not valid."
+
+        # Compute the updates in the interpolation conditions.
+        fun_diff = np.zeros(self.npt)
+        cub_diff = np.zeros(self.cub_val.shape)
+        ceq_diff = np.zeros(self.ceq_val.shape)
+        fun_diff[k_new] = fun_val - self.fun(x_new)
+        cub_diff[k_new, :] = cub_val - self.cub(x_new)
+        ceq_diff[k_new, :] = ceq_val - self.ceq(x_new)
+
+        # Update the function values.
+        self.fun_val[k_new] = fun_val
+        self.cub_val[k_new, :] = cub_val
+        self.ceq_val[k_new, :] = ceq_val
+
+        # Update the interpolation set.
+        dir_old = np.copy(self.interpolation.xpt[:, k_new])
+        self.interpolation.xpt[:, k_new] = x_new - self.interpolation.x_base
+
+        # Update the quadratic models.
+        ill_conditioned = self._fun.update(
+            self.interpolation,
+            k_new,
+            dir_old,
+            fun_diff,
+        )
+        for i in range(self.m_nonlinear_ub):
+            ill_conditioned = ill_conditioned or self._cub[i].update(
+                self.interpolation,
+                k_new,
+                dir_old,
+                cub_diff[:, i],
+            )
+        for i in range(self.m_nonlinear_eq):
+            ill_conditioned = ill_conditioned or self._ceq[i].update(
+                self.interpolation,
+                k_new,
+                dir_old,
+                ceq_diff[:, i],
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+        return ill_conditioned
+
+    def determinants(self, x_new, k_new=None):
+        """
+        Compute the normalized determinants of the new interpolation systems.
+
+        Parameters
+        ----------
+        x_new : `numpy.ndarray`, shape (n,)
+            New interpolation point. Its value is interpreted as relative to
+            the origin, not the base point.
+        k_new : int, optional
+            Index of the updated interpolation point. If `k_new` is not
+            specified, all the possible determinants are computed.
+
+        Returns
+        -------
+        {float, `numpy.ndarray`, shape (npt,)}
+            Determinant(s) of the new interpolation system.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+
+        Notes
+        -----
+        The determinants are normalized by the determinant of the current
+        interpolation system. For stability reasons, the calculations are done
+        using the formula (2.12) in [1]_.
+
+        References
+        ----------
+        .. [1] M. J. D. Powell. On updating the inverse of a KKT matrix.
+           Technical Report DAMTP 2004/NA01, Department of Applied Mathematics
+           and Theoretical Physics, University of Cambridge, Cambridge, UK,
+           2004.
+        """
+        if self._debug:
+            assert x_new.shape == (self.n,), \
+                "The shape of `x_new` is not valid."
+            assert (
+                k_new is None or 0 <= k_new < self.npt
+            ), "The index `k_new` is not valid."
+
+        # Compute the values independent of k_new.
+        shift = x_new - self.interpolation.x_base
+        new_col = np.empty((self.npt + self.n + 1, 1))
+        new_col[: self.npt, 0] = (
+                0.5 * (self.interpolation.xpt.T @ shift) ** 2.0)
+        new_col[self.npt, 0] = 1.0
+        new_col[self.npt + 1:, 0] = shift
+        inv_new_col = Quadratic.solve_systems(self.interpolation, new_col)[0]
+        beta = 0.5 * (shift @ shift) ** 2.0 - new_col[:, 0] @ inv_new_col[:, 0]
+
+        # Compute the values that depend on k.
+        if k_new is None:
+            coord_vec = np.eye(self.npt + self.n + 1, self.npt)
+            alpha = np.diag(
+                Quadratic.solve_systems(
+                    self.interpolation,
+                    coord_vec,
+                )[0]
+            )
+            tau = inv_new_col[: self.npt, 0]
+        else:
+            coord_vec = np.eye(self.npt + self.n + 1, 1, -k_new)
+            alpha = Quadratic.solve_systems(
+                self.interpolation,
+                coord_vec,
+            )[
+                0
+            ][k_new, 0]
+            tau = inv_new_col[k_new, 0]
+        return alpha * beta + tau**2.0
+
+    def shift_x_base(self, new_x_base, options):
+        """
+        Shift the base point without changing the interpolation set.
+
+        Parameters
+        ----------
+        new_x_base : `numpy.ndarray`, shape (n,)
+            New base point.
+        options : dict
+            Options of the solver.
+        """
+        if self._debug:
+            assert new_x_base.shape == (
+                self.n,
+            ), "The shape of `new_x_base` is not valid."
+
+        # Update the models.
+        self._fun.shift_x_base(self.interpolation, new_x_base)
+        for model in self._cub:
+            model.shift_x_base(self.interpolation, new_x_base)
+        for model in self._ceq:
+            model.shift_x_base(self.interpolation, new_x_base)
+
+        # Update the base point and the interpolation points.
+        shift = new_x_base - self.interpolation.x_base
+        self.interpolation.x_base += shift
+        self.interpolation.xpt -= shift[:, np.newaxis]
+        if options[Options.DEBUG]:
+            self._check_interpolation_conditions()
+
+    def _get_cub(self, mask=None):
+        """
+        Get the quadratic models of the nonlinear inequality constraints.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to return.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Quadratic models of the nonlinear inequality constraints.
+        """
+        return self._cub if mask is None else self._cub[mask]
+
+    def _get_ceq(self, mask=None):
+        """
+        Get the quadratic models of the nonlinear equality constraints.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to return.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Quadratic models of the nonlinear equality constraints.
+        """
+        return self._ceq if mask is None else self._ceq[mask]
+
+    def _check_interpolation_conditions(self):
+        """
+        Check the interpolation conditions of all quadratic models.
+        """
+        error_fun = 0.0
+        error_cub = 0.0
+        error_ceq = 0.0
+        for k in range(self.npt):
+            error_fun = np.max(
+                [
+                    error_fun,
+                    np.abs(
+                        self.fun(self.interpolation.point(k)) - self.fun_val[k]
+                    ),
+                ]
+            )
+            error_cub = np.max(
+                np.abs(
+                    self.cub(self.interpolation.point(k)) - self.cub_val[k, :]
+                ),
+                initial=error_cub,
+            )
+            error_ceq = np.max(
+                np.abs(
+                    self.ceq(self.interpolation.point(k)) - self.ceq_val[k, :]
+                ),
+                initial=error_ceq,
+            )
+        tol = 10.0 * np.sqrt(EPS) * max(self.n, self.npt)
+        if error_fun > tol * np.max(np.abs(self.fun_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the objective function are "
+                "not satisfied.",
+                RuntimeWarning,
+                2,
+            )
+        if error_cub > tol * np.max(np.abs(self.cub_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the inequality constraint "
+                "function are not satisfied.",
+                RuntimeWarning,
+                2,
+            )
+        if error_ceq > tol * np.max(np.abs(self.ceq_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the equality constraint "
+                "function are not satisfied.",
+                RuntimeWarning,
+                2,
+            )
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dbebce3a48067e97da2b75bd2cdd609e01029b2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py
@@ -0,0 +1,1296 @@
+from contextlib import suppress
+from inspect import signature
+import copy
+
+import numpy as np
+from scipy.optimize import (
+    Bounds,
+    LinearConstraint,
+    NonlinearConstraint,
+    OptimizeResult,
+)
+from scipy.optimize._constraints import PreparedConstraint
+
+
+from .settings import PRINT_OPTIONS, BARRIER
+from .utils import CallbackSuccess, get_arrays_tol
+from .utils import exact_1d_array
+
+
+class ObjectiveFunction:
+    """
+    Real-valued objective function.
+    """
+
+    def __init__(self, fun, verbose, debug, *args):
+        """
+        Initialize the objective function.
+
+        Parameters
+        ----------
+        fun : {callable, None}
+            Function to evaluate, or None.
+
+                ``fun(x, *args) -> float``
+
+            where ``x`` is an array with shape (n,) and `args` is a tuple.
+        verbose : bool
+            Whether to print the function evaluations.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        *args : tuple
+            Additional arguments to be passed to the function.
+        """
+        if debug:
+            assert fun is None or callable(fun)
+            assert isinstance(verbose, bool)
+            assert isinstance(debug, bool)
+
+        self._fun = fun
+        self._verbose = verbose
+        self._args = args
+        self._n_eval = 0
+
+    def __call__(self, x):
+        """
+        Evaluate the objective function.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the objective function is evaluated.
+
+        Returns
+        -------
+        float
+            Function value at `x`.
+        """
+        x = np.array(x, dtype=float)
+        if self._fun is None:
+            f = 0.0
+        else:
+            f = float(np.squeeze(self._fun(x, *self._args)))
+            self._n_eval += 1
+            if self._verbose:
+                with np.printoptions(**PRINT_OPTIONS):
+                    print(f"{self.name}({x}) = {f}")
+        return f
+
+    @property
+    def n_eval(self):
+        """
+        Number of function evaluations.
+
+        Returns
+        -------
+        int
+            Number of function evaluations.
+        """
+        return self._n_eval
+
+    @property
+    def name(self):
+        """
+        Name of the objective function.
+
+        Returns
+        -------
+        str
+            Name of the objective function.
+        """
+        name = ""
+        if self._fun is not None:
+            try:
+                name = self._fun.__name__
+            except AttributeError:
+                name = "fun"
+        return name
+
+
+class BoundConstraints:
+    """
+    Bound constraints ``xl <= x <= xu``.
+    """
+
+    def __init__(self, bounds):
+        """
+        Initialize the bound constraints.
+
+        Parameters
+        ----------
+        bounds : scipy.optimize.Bounds
+            Bound constraints.
+        """
+        self._xl = np.array(bounds.lb, float)
+        self._xu = np.array(bounds.ub, float)
+
+        # Remove the ill-defined bounds.
+        self.xl[np.isnan(self.xl)] = -np.inf
+        self.xu[np.isnan(self.xu)] = np.inf
+
+        self.is_feasible = (
+            np.all(self.xl <= self.xu)
+            and np.all(self.xl < np.inf)
+            and np.all(self.xu > -np.inf)
+        )
+        self.m = np.count_nonzero(self.xl > -np.inf) + np.count_nonzero(
+            self.xu < np.inf
+        )
+        self.pcs = PreparedConstraint(bounds, np.ones(bounds.lb.size))
+
+    @property
+    def xl(self):
+        """
+        Lower bound.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Lower bound.
+        """
+        return self._xl
+
+    @property
+    def xu(self):
+        """
+        Upper bound.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Upper bound.
+        """
+        return self._xu
+
+    def maxcv(self, x):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        x = np.asarray(x, dtype=float)
+        return self.violation(x)
+
+    def violation(self, x):
+        # shortcut for no bounds
+        if self.is_feasible:
+            return np.array([0])
+        else:
+            return self.pcs.violation(x)
+
+    def project(self, x):
+        """
+        Project a point onto the feasible set.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point to be projected.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Projection of `x` onto the feasible set.
+        """
+        return np.clip(x, self.xl, self.xu) if self.is_feasible else x
+
+
+class LinearConstraints:
+    """
+    Linear constraints ``a_ub @ x <= b_ub`` and ``a_eq @ x == b_eq``.
+    """
+
+    def __init__(self, constraints, n, debug):
+        """
+        Initialize the linear constraints.
+
+        Parameters
+        ----------
+        constraints : list of LinearConstraint
+            Linear constraints.
+        n : int
+            Number of variables.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        """
+        if debug:
+            assert isinstance(constraints, list)
+            for constraint in constraints:
+                assert isinstance(constraint, LinearConstraint)
+            assert isinstance(debug, bool)
+
+        self._a_ub = np.empty((0, n))
+        self._b_ub = np.empty(0)
+        self._a_eq = np.empty((0, n))
+        self._b_eq = np.empty(0)
+        for constraint in constraints:
+            is_equality = np.abs(
+                constraint.ub - constraint.lb
+            ) <= get_arrays_tol(constraint.lb, constraint.ub)
+            if np.any(is_equality):
+                self._a_eq = np.vstack((self.a_eq, constraint.A[is_equality]))
+                self._b_eq = np.concatenate(
+                    (
+                        self.b_eq,
+                        0.5
+                        * (
+                            constraint.lb[is_equality]
+                            + constraint.ub[is_equality]
+                        ),
+                    )
+                )
+            if not np.all(is_equality):
+                self._a_ub = np.vstack(
+                    (
+                        self.a_ub,
+                        constraint.A[~is_equality],
+                        -constraint.A[~is_equality],
+                    )
+                )
+                self._b_ub = np.concatenate(
+                    (
+                        self.b_ub,
+                        constraint.ub[~is_equality],
+                        -constraint.lb[~is_equality],
+                    )
+                )
+
+        # Remove the ill-defined constraints.
+        self.a_ub[np.isnan(self.a_ub)] = 0.0
+        self.a_eq[np.isnan(self.a_eq)] = 0.0
+        undef_ub = np.isnan(self.b_ub) | np.isinf(self.b_ub)
+        undef_eq = np.isnan(self.b_eq)
+        self._a_ub = self.a_ub[~undef_ub, :]
+        self._b_ub = self.b_ub[~undef_ub]
+        self._a_eq = self.a_eq[~undef_eq, :]
+        self._b_eq = self.b_eq[~undef_eq]
+        self.pcs = [
+            PreparedConstraint(c, np.ones(n)) for c in constraints if c.A.size
+        ]
+
+    @property
+    def a_ub(self):
+        """
+        Left-hand side matrix of the linear inequality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Left-hand side matrix of the linear inequality constraints.
+        """
+        return self._a_ub
+
+    @property
+    def b_ub(self):
+        """
+        Right-hand side vector of the linear inequality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Right-hand side vector of the linear inequality constraints.
+        """
+        return self._b_ub
+
+    @property
+    def a_eq(self):
+        """
+        Left-hand side matrix of the linear equality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Left-hand side matrix of the linear equality constraints.
+        """
+        return self._a_eq
+
+    @property
+    def b_eq(self):
+        """
+        Right-hand side vector of the linear equality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Right-hand side vector of the linear equality constraints.
+        """
+        return self._b_eq
+
+    @property
+    def m_ub(self):
+        """
+        Number of linear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear inequality constraints.
+        """
+        return self.b_ub.size
+
+    @property
+    def m_eq(self):
+        """
+        Number of linear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear equality constraints.
+        """
+        return self.b_eq.size
+
+    def maxcv(self, x):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        return np.max(self.violation(x), initial=0.0)
+
+    def violation(self, x):
+        if len(self.pcs):
+            return np.concatenate([pc.violation(x) for pc in self.pcs])
+        return np.array([])
+
+
+class NonlinearConstraints:
+    """
+    Nonlinear constraints ``c_ub(x) <= 0`` and ``c_eq(x) == b_eq``.
+    """
+
+    def __init__(self, constraints, verbose, debug):
+        """
+        Initialize the nonlinear constraints.
+
+        Parameters
+        ----------
+        constraints : list
+            Nonlinear constraints.
+        verbose : bool
+            Whether to print the function evaluations.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        """
+        if debug:
+            assert isinstance(constraints, list)
+            for constraint in constraints:
+                assert isinstance(constraint, NonlinearConstraint)
+            assert isinstance(verbose, bool)
+            assert isinstance(debug, bool)
+
+        self._constraints = constraints
+        self.pcs = []
+        self._verbose = verbose
+
+        # map of indexes for equality and inequality constraints
+        self._map_ub = None
+        self._map_eq = None
+        self._m_ub = self._m_eq = None
+
+    def __call__(self, x):
+        """
+        Calculates the residual (slack) for the constraints.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the constraints are evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Nonlinear inequality constraint slack values.
+        `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Nonlinear equality constraint slack values.
+        """
+        if not len(self._constraints):
+            self._m_eq = self._m_ub = 0
+            return np.array([]), np.array([])
+
+        x = np.array(x, dtype=float)
+        # first time around the constraints haven't been prepared
+        if not len(self.pcs):
+            self._map_ub = []
+            self._map_eq = []
+            self._m_eq = 0
+            self._m_ub = 0
+
+            for constraint in self._constraints:
+                if not callable(constraint.jac):
+                    # having a callable constraint function prevents
+                    # constraint.fun from being evaluated when preparing
+                    # constraint
+                    c = copy.copy(constraint)
+                    c.jac = lambda x0: x0
+                    c.hess = lambda x0, v: 0.0
+                    pc = PreparedConstraint(c, x)
+                else:
+                    pc = PreparedConstraint(constraint, x)
+                # we're going to be using the same x value again immediately
+                # after this initialisation
+                pc.fun.f_updated = True
+
+                self.pcs.append(pc)
+                idx = np.arange(pc.fun.m)
+
+                # figure out equality and inequality maps
+                lb, ub = pc.bounds[0], pc.bounds[1]
+                arr_tol = get_arrays_tol(lb, ub)
+                is_equality = np.abs(ub - lb) <= arr_tol
+                self._map_eq.append(idx[is_equality])
+                self._map_ub.append(idx[~is_equality])
+
+                # these values will be corrected to their proper values later
+                self._m_eq += np.count_nonzero(is_equality)
+                self._m_ub += np.count_nonzero(~is_equality)
+
+        c_ub = []
+        c_eq = []
+        for i, pc in enumerate(self.pcs):
+            val = pc.fun.fun(x)
+            if self._verbose:
+                with np.printoptions(**PRINT_OPTIONS):
+                    with suppress(AttributeError):
+                        fun_name = self._constraints[i].fun.__name__
+                        print(f"{fun_name}({x}) = {val}")
+
+            # separate violations into c_eq and c_ub
+            eq_idx = self._map_eq[i]
+            ub_idx = self._map_ub[i]
+
+            ub_val = val[ub_idx]
+            if len(ub_idx):
+                xl = pc.bounds[0][ub_idx]
+                xu = pc.bounds[1][ub_idx]
+
+                # calculate slack within lower bound
+                finite_xl = xl > -np.inf
+                _v = xl[finite_xl] - ub_val[finite_xl]
+                c_ub.append(_v)
+
+                # calculate slack within lower bound
+                finite_xu = xu < np.inf
+                _v = ub_val[finite_xu] - xu[finite_xu]
+                c_ub.append(_v)
+
+            # equality constraints taken from midpoint between lb and ub
+            eq_val = val[eq_idx]
+            if len(eq_idx):
+                midpoint = 0.5 * (pc.bounds[1][eq_idx] + pc.bounds[0][eq_idx])
+                eq_val -= midpoint
+            c_eq.append(eq_val)
+
+        if self._m_eq:
+            c_eq = np.concatenate(c_eq)
+        else:
+            c_eq = np.array([])
+
+        if self._m_ub:
+            c_ub = np.concatenate(c_ub)
+        else:
+            c_ub = np.array([])
+
+        self._m_ub = c_ub.size
+        self._m_eq = c_eq.size
+
+        return c_ub, c_eq
+
+    @property
+    def m_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear inequality constraints is unknown.
+        """
+        if self._m_ub is None:
+            raise ValueError(
+                "The number of nonlinear inequality constraints is unknown."
+            )
+        else:
+            return self._m_ub
+
+    @property
+    def m_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear equality constraints is unknown.
+        """
+        if self._m_eq is None:
+            raise ValueError(
+                "The number of nonlinear equality constraints is unknown."
+            )
+        else:
+            return self._m_eq
+
+    @property
+    def n_eval(self):
+        """
+        Number of function evaluations.
+
+        Returns
+        -------
+        int
+            Number of function evaluations.
+        """
+        if len(self.pcs):
+            return self.pcs[0].fun.nfev
+        else:
+            return 0
+
+    def maxcv(self, x, cub_val=None, ceq_val=None):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+        cub_val : array_like, shape (m_nonlinear_ub,), optional
+            Values of the nonlinear inequality constraints. If not provided,
+            the nonlinear inequality constraints are evaluated at `x`.
+        ceq_val : array_like, shape (m_nonlinear_eq,), optional
+            Values of the nonlinear equality constraints. If not provided,
+            the nonlinear equality constraints are evaluated at `x`.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        return np.max(
+            self.violation(x, cub_val=cub_val, ceq_val=ceq_val), initial=0.0
+        )
+
+    def violation(self, x, cub_val=None, ceq_val=None):
+        return np.concatenate([pc.violation(x) for pc in self.pcs])
+
+
+class Problem:
+    """
+    Optimization problem.
+    """
+
+    def __init__(
+        self,
+        obj,
+        x0,
+        bounds,
+        linear,
+        nonlinear,
+        callback,
+        feasibility_tol,
+        scale,
+        store_history,
+        history_size,
+        filter_size,
+        debug,
+    ):
+        """
+        Initialize the nonlinear problem.
+
+        The problem is preprocessed to remove all the variables that are fixed
+        by the bound constraints.
+
+        Parameters
+        ----------
+        obj : ObjectiveFunction
+            Objective function.
+        x0 : array_like, shape (n,)
+            Initial guess.
+        bounds : BoundConstraints
+            Bound constraints.
+        linear : LinearConstraints
+            Linear constraints.
+        nonlinear : NonlinearConstraints
+            Nonlinear constraints.
+        callback : {callable, None}
+            Callback function.
+        feasibility_tol : float
+            Tolerance on the constraint violation.
+        scale : bool
+            Whether to scale the problem according to the bounds.
+        store_history : bool
+            Whether to store the function evaluations.
+        history_size : int
+            Maximum number of function evaluations to store.
+        filter_size : int
+            Maximum number of points in the filter.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        """
+        if debug:
+            assert isinstance(obj, ObjectiveFunction)
+            assert isinstance(bounds, BoundConstraints)
+            assert isinstance(linear, LinearConstraints)
+            assert isinstance(nonlinear, NonlinearConstraints)
+            assert isinstance(feasibility_tol, float)
+            assert isinstance(scale, bool)
+            assert isinstance(store_history, bool)
+            assert isinstance(history_size, int)
+            if store_history:
+                assert history_size > 0
+            assert isinstance(filter_size, int)
+            assert filter_size > 0
+            assert isinstance(debug, bool)
+
+        self._obj = obj
+        self._linear = linear
+        self._nonlinear = nonlinear
+        if callback is not None:
+            if not callable(callback):
+                raise TypeError("The callback must be a callable function.")
+        self._callback = callback
+
+        # Check the consistency of the problem.
+        x0 = exact_1d_array(x0, "The initial guess must be a vector.")
+        n = x0.size
+        if bounds.xl.size != n:
+            raise ValueError(f"The bounds must have {n} elements.")
+        if linear.a_ub.shape[1] != n:
+            raise ValueError(
+                f"The left-hand side matrices of the linear constraints must "
+                f"have {n} columns."
+            )
+
+        # Check which variables are fixed.
+        tol = get_arrays_tol(bounds.xl, bounds.xu)
+        self._fixed_idx = (bounds.xl <= bounds.xu) & (
+            np.abs(bounds.xl - bounds.xu) < tol
+        )
+        self._fixed_val = 0.5 * (
+            bounds.xl[self._fixed_idx] + bounds.xu[self._fixed_idx]
+        )
+        self._fixed_val = np.clip(
+            self._fixed_val,
+            bounds.xl[self._fixed_idx],
+            bounds.xu[self._fixed_idx],
+        )
+
+        # Set the bound constraints.
+        self._orig_bounds = bounds
+        self._bounds = BoundConstraints(
+            Bounds(bounds.xl[~self._fixed_idx], bounds.xu[~self._fixed_idx])
+        )
+
+        # Set the initial guess.
+        self._x0 = self._bounds.project(x0[~self._fixed_idx])
+
+        # Set the linear constraints.
+        b_eq = linear.b_eq - linear.a_eq[:, self._fixed_idx] @ self._fixed_val
+        self._linear = LinearConstraints(
+            [
+                LinearConstraint(
+                    linear.a_ub[:, ~self._fixed_idx],
+                    -np.inf,
+                    linear.b_ub
+                    - linear.a_ub[:, self._fixed_idx] @ self._fixed_val,
+                ),
+                LinearConstraint(linear.a_eq[:, ~self._fixed_idx], b_eq, b_eq),
+            ],
+            self.n,
+            debug,
+        )
+
+        # Scale the problem if necessary.
+        scale = (
+            scale
+            and self._bounds.is_feasible
+            and np.all(np.isfinite(self._bounds.xl))
+            and np.all(np.isfinite(self._bounds.xu))
+        )
+        if scale:
+            self._scaling_factor = 0.5 * (self._bounds.xu - self._bounds.xl)
+            self._scaling_shift = 0.5 * (self._bounds.xu + self._bounds.xl)
+            self._bounds = BoundConstraints(
+                Bounds(-np.ones(self.n), np.ones(self.n))
+            )
+            b_eq = self._linear.b_eq - self._linear.a_eq @ self._scaling_shift
+            self._linear = LinearConstraints(
+                [
+                    LinearConstraint(
+                        self._linear.a_ub @ np.diag(self._scaling_factor),
+                        -np.inf,
+                        self._linear.b_ub
+                        - self._linear.a_ub @ self._scaling_shift,
+                    ),
+                    LinearConstraint(
+                        self._linear.a_eq @ np.diag(self._scaling_factor),
+                        b_eq,
+                        b_eq,
+                    ),
+                ],
+                self.n,
+                debug,
+            )
+            self._x0 = (self._x0 - self._scaling_shift) / self._scaling_factor
+        else:
+            self._scaling_factor = np.ones(self.n)
+            self._scaling_shift = np.zeros(self.n)
+
+        # Set the initial filter.
+        self._feasibility_tol = feasibility_tol
+        self._filter_size = filter_size
+        self._fun_filter = []
+        self._maxcv_filter = []
+        self._x_filter = []
+
+        # Set the initial history.
+        self._store_history = store_history
+        self._history_size = history_size
+        self._fun_history = []
+        self._maxcv_history = []
+        self._x_history = []
+
+    def __call__(self, x, penalty=0.0):
+        """
+        Evaluate the objective and nonlinear constraint functions.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the functions are evaluated.
+        penalty : float, optional
+            Penalty parameter used to select the point in the filter to forward
+            to the callback function.
+
+        Returns
+        -------
+        float
+            Objective function value.
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Nonlinear inequality constraint function values.
+        `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Nonlinear equality constraint function values.
+
+        Raises
+        ------
+        `cobyqa.utils.CallbackSuccess`
+            If the callback function raises a ``StopIteration``.
+        """
+        # Evaluate the objective and nonlinear constraint functions.
+        x = np.asarray(x, dtype=float)
+        x_full = self.build_x(x)
+        fun_val = self._obj(x_full)
+        cub_val, ceq_val = self._nonlinear(x_full)
+        maxcv_val = self.maxcv(x, cub_val, ceq_val)
+        if self._store_history:
+            self._fun_history.append(fun_val)
+            self._maxcv_history.append(maxcv_val)
+            self._x_history.append(x)
+            if len(self._fun_history) > self._history_size:
+                self._fun_history.pop(0)
+                self._maxcv_history.pop(0)
+                self._x_history.pop(0)
+
+        # Add the point to the filter if it is not dominated by any point.
+        if np.isnan(fun_val) and np.isnan(maxcv_val):
+            include_point = len(self._fun_filter) == 0
+        elif np.isnan(fun_val):
+            include_point = all(
+                np.isnan(fun_filter)
+                and maxcv_val < maxcv_filter
+                or np.isnan(maxcv_filter)
+                for fun_filter, maxcv_filter in zip(
+                    self._fun_filter,
+                    self._maxcv_filter,
+                )
+            )
+        elif np.isnan(maxcv_val):
+            include_point = all(
+                np.isnan(maxcv_filter)
+                and fun_val < fun_filter
+                or np.isnan(fun_filter)
+                for fun_filter, maxcv_filter in zip(
+                    self._fun_filter,
+                    self._maxcv_filter,
+                )
+            )
+        else:
+            include_point = all(
+                fun_val < fun_filter or maxcv_val < maxcv_filter
+                for fun_filter, maxcv_filter in zip(
+                    self._fun_filter,
+                    self._maxcv_filter,
+                )
+            )
+        if include_point:
+            self._fun_filter.append(fun_val)
+            self._maxcv_filter.append(maxcv_val)
+            self._x_filter.append(x)
+
+            # Remove the points in the filter that are dominated by the new
+            # point. We must iterate in reverse order to avoid problems when
+            # removing elements from the list.
+            for k in range(len(self._fun_filter) - 2, -1, -1):
+                if np.isnan(fun_val):
+                    remove_point = np.isnan(self._fun_filter[k])
+                elif np.isnan(maxcv_val):
+                    remove_point = np.isnan(self._maxcv_filter[k])
+                else:
+                    remove_point = (
+                        np.isnan(self._fun_filter[k])
+                        or np.isnan(self._maxcv_filter[k])
+                        or fun_val <= self._fun_filter[k]
+                        and maxcv_val <= self._maxcv_filter[k]
+                    )
+                if remove_point:
+                    self._fun_filter.pop(k)
+                    self._maxcv_filter.pop(k)
+                    self._x_filter.pop(k)
+
+            # Keep only the most recent points in the filter.
+            if len(self._fun_filter) > self._filter_size:
+                self._fun_filter.pop(0)
+                self._maxcv_filter.pop(0)
+                self._x_filter.pop(0)
+
+        # Evaluate the callback function after updating the filter to ensure
+        # that the current point can be returned by the method.
+        if self._callback is not None:
+            sig = signature(self._callback)
+            try:
+                x_best, fun_best, _ = self.best_eval(penalty)
+                x_best = self.build_x(x_best)
+                if set(sig.parameters) == {"intermediate_result"}:
+                    intermediate_result = OptimizeResult(
+                        x=x_best,
+                        fun=fun_best,
+                        # maxcv=maxcv_best,
+                    )
+                    self._callback(intermediate_result=intermediate_result)
+                else:
+                    self._callback(x_best)
+            except StopIteration as exc:
+                raise CallbackSuccess from exc
+
+        # Apply the extreme barriers and return.
+        if np.isnan(fun_val):
+            fun_val = BARRIER
+        cub_val[np.isnan(cub_val)] = BARRIER
+        ceq_val[np.isnan(ceq_val)] = BARRIER
+        fun_val = max(min(fun_val, BARRIER), -BARRIER)
+        cub_val = np.maximum(np.minimum(cub_val, BARRIER), -BARRIER)
+        ceq_val = np.maximum(np.minimum(ceq_val, BARRIER), -BARRIER)
+        return fun_val, cub_val, ceq_val
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self.x0.size
+
+    @property
+    def n_orig(self):
+        """
+        Number of variables in the original problem (with fixed variables).
+
+        Returns
+        -------
+        int
+            Number of variables in the original problem (with fixed variables).
+        """
+        return self._fixed_idx.size
+
+    @property
+    def x0(self):
+        """
+        Initial guess.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Initial guess.
+        """
+        return self._x0
+
+    @property
+    def n_eval(self):
+        """
+        Number of function evaluations.
+
+        Returns
+        -------
+        int
+            Number of function evaluations.
+        """
+        return self._obj.n_eval
+
+    @property
+    def fun_name(self):
+        """
+        Name of the objective function.
+
+        Returns
+        -------
+        str
+            Name of the objective function.
+        """
+        return self._obj.name
+
+    @property
+    def bounds(self):
+        """
+        Bound constraints.
+
+        Returns
+        -------
+        BoundConstraints
+            Bound constraints.
+        """
+        return self._bounds
+
+    @property
+    def linear(self):
+        """
+        Linear constraints.
+
+        Returns
+        -------
+        LinearConstraints
+            Linear constraints.
+        """
+        return self._linear
+
+    @property
+    def m_bounds(self):
+        """
+        Number of bound constraints.
+
+        Returns
+        -------
+        int
+            Number of bound constraints.
+        """
+        return self.bounds.m
+
+    @property
+    def m_linear_ub(self):
+        """
+        Number of linear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear inequality constraints.
+        """
+        return self.linear.m_ub
+
+    @property
+    def m_linear_eq(self):
+        """
+        Number of linear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear equality constraints.
+        """
+        return self.linear.m_eq
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear inequality constraints is not known.
+        """
+        return self._nonlinear.m_ub
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear equality constraints is not known.
+        """
+        return self._nonlinear.m_eq
+
+    @property
+    def fun_history(self):
+        """
+        History of objective function evaluations.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n_eval,)
+            History of objective function evaluations.
+        """
+        return np.array(self._fun_history, dtype=float)
+
+    @property
+    def maxcv_history(self):
+        """
+        History of maximum constraint violations.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n_eval,)
+            History of maximum constraint violations.
+        """
+        return np.array(self._maxcv_history, dtype=float)
+
+    @property
+    def type(self):
+        """
+        Type of the problem.
+
+        The problem can be either 'unconstrained', 'bound-constrained',
+        'linearly constrained', or 'nonlinearly constrained'.
+
+        Returns
+        -------
+        str
+            Type of the problem.
+        """
+        try:
+            if self.m_nonlinear_ub > 0 or self.m_nonlinear_eq > 0:
+                return "nonlinearly constrained"
+            elif self.m_linear_ub > 0 or self.m_linear_eq > 0:
+                return "linearly constrained"
+            elif self.m_bounds > 0:
+                return "bound-constrained"
+            else:
+                return "unconstrained"
+        except ValueError:
+            # The number of nonlinear constraints is not known. It may be zero
+            # if the user provided a nonlinear inequality and/or equality
+            # constraint function that returns an empty array. However, as this
+            # is not known before the first call to the function, we assume
+            # that the problem is nonlinearly constrained.
+            return "nonlinearly constrained"
+
+    @property
+    def is_feasibility(self):
+        """
+        Whether the problem is a feasibility problem.
+
+        Returns
+        -------
+        bool
+            Whether the problem is a feasibility problem.
+        """
+        return self.fun_name == ""
+
+    def build_x(self, x):
+        """
+        Build the full vector of variables from the reduced vector.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Reduced vector of variables.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n_orig,)
+            Full vector of variables.
+        """
+        x_full = np.empty(self.n_orig)
+        x_full[self._fixed_idx] = self._fixed_val
+        x_full[~self._fixed_idx] = (x * self._scaling_factor
+                                    + self._scaling_shift)
+        return self._orig_bounds.project(x_full)
+
+    def maxcv(self, x, cub_val=None, ceq_val=None):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+        cub_val : array_like, shape (m_nonlinear_ub,), optional
+            Values of the nonlinear inequality constraints. If not provided,
+            the nonlinear inequality constraints are evaluated at `x`.
+        ceq_val : array_like, shape (m_nonlinear_eq,), optional
+            Values of the nonlinear equality constraints. If not provided,
+            the nonlinear equality constraints are evaluated at `x`.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        violation = self.violation(x, cub_val=cub_val, ceq_val=ceq_val)
+        if np.count_nonzero(violation):
+            return np.max(violation, initial=0.0)
+        else:
+            return 0.0
+
+    def violation(self, x, cub_val=None, ceq_val=None):
+        violation = []
+        if not self.bounds.is_feasible:
+            b = self.bounds.violation(x)
+            violation.append(b)
+
+        if len(self.linear.pcs):
+            lc = self.linear.violation(x)
+            violation.append(lc)
+        if len(self._nonlinear.pcs):
+            nlc = self._nonlinear.violation(x, cub_val, ceq_val)
+            violation.append(nlc)
+
+        if len(violation):
+            return np.concatenate(violation)
+
+    def best_eval(self, penalty):
+        """
+        Return the best point in the filter and the corresponding objective and
+        nonlinear constraint function evaluations.
+
+        Parameters
+        ----------
+        penalty : float
+            Penalty parameter
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Best point.
+        float
+            Corresponding objective function value.
+        float
+            Corresponding maximum constraint violation.
+        """
+        # If the filter is empty, i.e., if no function evaluation has been
+        # performed, we evaluate the objective and nonlinear constraint
+        # functions at the initial guess.
+        if len(self._fun_filter) == 0:
+            self(self.x0)
+
+        # Find the best point in the filter.
+        fun_filter = np.array(self._fun_filter)
+        maxcv_filter = np.array(self._maxcv_filter)
+        x_filter = np.array(self._x_filter)
+        finite_idx = np.isfinite(maxcv_filter)
+        if np.any(finite_idx):
+            # At least one point has a finite maximum constraint violation.
+            feasible_idx = maxcv_filter <= self._feasibility_tol
+            if np.any(feasible_idx) and not np.all(
+                np.isnan(fun_filter[feasible_idx])
+            ):
+                # At least one point is feasible and has a well-defined
+                # objective function value. We select the point with the least
+                # objective function value. If there is a tie, we select the
+                # point with the least maximum constraint violation. If there
+                # is still a tie, we select the most recent point.
+                fun_min_idx = feasible_idx & (
+                    fun_filter <= np.nanmin(fun_filter[feasible_idx])
+                )
+                if np.count_nonzero(fun_min_idx) > 1:
+                    fun_min_idx &= maxcv_filter <= np.min(
+                        maxcv_filter[fun_min_idx]
+                    )
+                i = np.flatnonzero(fun_min_idx)[-1]
+            elif np.any(feasible_idx):
+                # At least one point is feasible but no feasible point has a
+                # well-defined objective function value. We select the most
+                # recent feasible point.
+                i = np.flatnonzero(feasible_idx)[-1]
+            else:
+                # No point is feasible. We first compute the merit function
+                # value for each point.
+                merit_filter = np.full_like(fun_filter, np.nan)
+                merit_filter[finite_idx] = (
+                    fun_filter[finite_idx] + penalty * maxcv_filter[finite_idx]
+                )
+                if np.all(np.isnan(merit_filter)):
+                    # No point has a well-defined merit function value. In
+                    # other words, among the points with a well-defined maximum
+                    # constraint violation, none has a well-defined objective
+                    # function value. We select the point with the least
+                    # maximum constraint violation. If there is a tie, we
+                    # select the most recent point.
+                    min_maxcv_idx = maxcv_filter <= np.nanmin(maxcv_filter)
+                    i = np.flatnonzero(min_maxcv_idx)[-1]
+                else:
+                    # At least one point has a well-defined merit function
+                    # value. We select the point with the least merit function
+                    # value. If there is a tie, we select the point with the
+                    # least maximum constraint violation. If there is still a
+                    # tie, we select the point with the least objective
+                    # function value. If there is still a tie, we select the
+                    # most recent point.
+                    merit_min_idx = merit_filter <= np.nanmin(merit_filter)
+                    if np.count_nonzero(merit_min_idx) > 1:
+                        merit_min_idx &= maxcv_filter <= np.min(
+                            maxcv_filter[merit_min_idx]
+                        )
+
+                    if np.count_nonzero(merit_min_idx) > 1:
+                        merit_min_idx &= fun_filter <= np.min(
+                            fun_filter[merit_min_idx]
+                        )
+                    i = np.flatnonzero(merit_min_idx)[-1]
+        elif not np.all(np.isnan(fun_filter)):
+            # No maximum constraint violation is well-defined but at least one
+            # point has a well-defined objective function value. We select the
+            # point with the least objective function value. If there is a tie,
+            # we select the most recent point.
+            fun_min_idx = fun_filter <= np.nanmin(fun_filter)
+            i = np.flatnonzero(fun_min_idx)[-1]
+        else:
+            # No point has a well-defined maximum constraint violation or
+            # objective function value. We select the most recent point.
+            i = len(fun_filter) - 1
+        return (
+            self.bounds.project(x_filter[i, :]),
+            fun_filter[i],
+            maxcv_filter[i],
+        )
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..6394822826e094a803a485556a298e342bf260ac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py
@@ -0,0 +1,132 @@
+import sys
+from enum import Enum
+
+import numpy as np
+
+
+# Exit status.
+class ExitStatus(Enum):
+    """
+    Exit statuses.
+    """
+
+    RADIUS_SUCCESS = 0
+    TARGET_SUCCESS = 1
+    FIXED_SUCCESS = 2
+    CALLBACK_SUCCESS = 3
+    FEASIBLE_SUCCESS = 4
+    MAX_EVAL_WARNING = 5
+    MAX_ITER_WARNING = 6
+    INFEASIBLE_ERROR = -1
+    LINALG_ERROR = -2
+
+
+class Options(str, Enum):
+    """
+    Options.
+    """
+
+    DEBUG = "debug"
+    FEASIBILITY_TOL = "feasibility_tol"
+    FILTER_SIZE = "filter_size"
+    HISTORY_SIZE = "history_size"
+    MAX_EVAL = "maxfev"
+    MAX_ITER = "maxiter"
+    NPT = "nb_points"
+    RHOBEG = "radius_init"
+    RHOEND = "radius_final"
+    SCALE = "scale"
+    STORE_HISTORY = "store_history"
+    TARGET = "target"
+    VERBOSE = "disp"
+
+
+class Constants(str, Enum):
+    """
+    Constants.
+    """
+
+    DECREASE_RADIUS_FACTOR = "decrease_radius_factor"
+    INCREASE_RADIUS_FACTOR = "increase_radius_factor"
+    INCREASE_RADIUS_THRESHOLD = "increase_radius_threshold"
+    DECREASE_RADIUS_THRESHOLD = "decrease_radius_threshold"
+    DECREASE_RESOLUTION_FACTOR = "decrease_resolution_factor"
+    LARGE_RESOLUTION_THRESHOLD = "large_resolution_threshold"
+    MODERATE_RESOLUTION_THRESHOLD = "moderate_resolution_threshold"
+    LOW_RATIO = "low_ratio"
+    HIGH_RATIO = "high_ratio"
+    VERY_LOW_RATIO = "very_low_ratio"
+    PENALTY_INCREASE_THRESHOLD = "penalty_increase_threshold"
+    PENALTY_INCREASE_FACTOR = "penalty_increase_factor"
+    SHORT_STEP_THRESHOLD = "short_step_threshold"
+    LOW_RADIUS_FACTOR = "low_radius_factor"
+    BYRD_OMOJOKUN_FACTOR = "byrd_omojokun_factor"
+    THRESHOLD_RATIO_CONSTRAINTS = "threshold_ratio_constraints"
+    LARGE_SHIFT_FACTOR = "large_shift_factor"
+    LARGE_GRADIENT_FACTOR = "large_gradient_factor"
+    RESOLUTION_FACTOR = "resolution_factor"
+    IMPROVE_TCG = "improve_tcg"
+
+
+# Default options.
+DEFAULT_OPTIONS = {
+    Options.DEBUG.value: False,
+    Options.FEASIBILITY_TOL.value: np.sqrt(np.finfo(float).eps),
+    Options.FILTER_SIZE.value: sys.maxsize,
+    Options.HISTORY_SIZE.value: sys.maxsize,
+    Options.MAX_EVAL.value: lambda n: 500 * n,
+    Options.MAX_ITER.value: lambda n: 1000 * n,
+    Options.NPT.value: lambda n: 2 * n + 1,
+    Options.RHOBEG.value: 1.0,
+    Options.RHOEND.value: 1e-6,
+    Options.SCALE.value: False,
+    Options.STORE_HISTORY.value: False,
+    Options.TARGET.value: -np.inf,
+    Options.VERBOSE.value: False,
+}
+
+# Default constants.
+DEFAULT_CONSTANTS = {
+    Constants.DECREASE_RADIUS_FACTOR.value: 0.5,
+    Constants.INCREASE_RADIUS_FACTOR.value: np.sqrt(2.0),
+    Constants.INCREASE_RADIUS_THRESHOLD.value: 2.0,
+    Constants.DECREASE_RADIUS_THRESHOLD.value: 1.4,
+    Constants.DECREASE_RESOLUTION_FACTOR.value: 0.1,
+    Constants.LARGE_RESOLUTION_THRESHOLD.value: 250.0,
+    Constants.MODERATE_RESOLUTION_THRESHOLD.value: 16.0,
+    Constants.LOW_RATIO.value: 0.1,
+    Constants.HIGH_RATIO.value: 0.7,
+    Constants.VERY_LOW_RATIO.value: 0.01,
+    Constants.PENALTY_INCREASE_THRESHOLD.value: 1.5,
+    Constants.PENALTY_INCREASE_FACTOR.value: 2.0,
+    Constants.SHORT_STEP_THRESHOLD.value: 0.5,
+    Constants.LOW_RADIUS_FACTOR.value: 0.1,
+    Constants.BYRD_OMOJOKUN_FACTOR.value: 0.8,
+    Constants.THRESHOLD_RATIO_CONSTRAINTS.value: 2.0,
+    Constants.LARGE_SHIFT_FACTOR.value: 10.0,
+    Constants.LARGE_GRADIENT_FACTOR.value: 10.0,
+    Constants.RESOLUTION_FACTOR.value: 2.0,
+    Constants.IMPROVE_TCG.value: True,
+}
+
+# Printing options.
+PRINT_OPTIONS = {
+    "threshold": 6,
+    "edgeitems": 2,
+    "linewidth": sys.maxsize,
+    "formatter": {
+        "float_kind": lambda x: np.format_float_scientific(
+            x,
+            precision=3,
+            unique=False,
+            pad_left=2,
+        )
+    },
+}
+
+# Constants.
+BARRIER = 2.0 ** min(
+    100,
+    np.finfo(float).maxexp // 2,
+    -np.finfo(float).minexp // 2,
+)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01a1ad3c6f4cb5c0c9b99d1ce35fea92e7618ff5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
@@ -0,0 +1,14 @@
+from .geometry import cauchy_geometry, spider_geometry
+from .optim import (
+    tangential_byrd_omojokun,
+    constrained_tangential_byrd_omojokun,
+    normal_byrd_omojokun,
+)
+
+__all__ = [
+    "cauchy_geometry",
+    "spider_geometry",
+    "tangential_byrd_omojokun",
+    "constrained_tangential_byrd_omojokun",
+    "normal_byrd_omojokun",
+]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d782a33fbdd81fd2fc698365df908d808270fad2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a58a2a1c7e572f4d008732a2a7b533c8d78ff371
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ceee486804590def945484c88d3628f087a672a8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b67fd7c813ee493b18720d1daf71324d72330b6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
@@ -0,0 +1,387 @@
+import inspect
+
+import numpy as np
+
+from ..utils import get_arrays_tol
+
+
+TINY = np.finfo(float).tiny
+
+
+def cauchy_geometry(const, grad, curv, xl, xu, delta, debug):
+    r"""
+    Maximize approximately the absolute value of a quadratic function subject
+    to bound constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s +
+        \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    by maximizing the objective function along the constrained Cauchy
+    direction.
+
+    Parameters
+    ----------
+    const : float
+        Constant :math:`c` as shown above.
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    curv : callable
+        Curvature of :math:`H` along any vector.
+
+            ``curv(s) -> float``
+
+        returns :math:`s^{\mathsf{T}} H s`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Notes
+    -----
+    This function is described as the first alternative in Section 6.5 of [1]_.
+    It is assumed that the origin is feasible with respect to the bound
+    constraints and that `delta` is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *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.
+    """
+    if debug:
+        assert isinstance(const, float)
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(curv).bind(grad)
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # To maximize the absolute value of a quadratic function, we maximize the
+    # function itself or its negative, and we choose the solution that provides
+    # the largest function value.
+    step1, q_val1 = _cauchy_geom(const, grad, curv, xl, xu, delta, debug)
+    step2, q_val2 = _cauchy_geom(
+        -const,
+        -grad,
+        lambda x: -curv(x),
+        xl,
+        xu,
+        delta,
+        debug,
+    )
+    step = step1 if abs(q_val1) >= abs(q_val2) else step2
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def spider_geometry(const, grad, curv, xpt, xl, xu, delta, debug):
+    r"""
+    Maximize approximately the absolute value of a quadratic function subject
+    to bound constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s +
+        \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    by maximizing the objective function along given straight lines.
+
+    Parameters
+    ----------
+    const : float
+        Constant :math:`c` as shown above.
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    curv : callable
+        Curvature of :math:`H` along any vector.
+
+            ``curv(s) -> float``
+
+        returns :math:`s^{\mathsf{T}} H s`.
+    xpt : `numpy.ndarray`, shape (n, npt)
+        Points defining the straight lines. The straight lines considered are
+        the ones passing through the origin and the points in `xpt`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Notes
+    -----
+    This function is described as the second alternative in Section 6.5 of
+    [1]_. It is assumed that the origin is feasible with respect to the bound
+    constraints and that `delta` is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *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.
+    """
+    if debug:
+        assert isinstance(const, float)
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(curv).bind(grad)
+        assert (
+            isinstance(xpt, np.ndarray)
+            and xpt.ndim == 2
+            and xpt.shape[0] == grad.size
+        )
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # Iterate through the straight lines.
+    step = np.zeros_like(grad)
+    q_val = const
+    s_norm = np.linalg.norm(xpt, axis=0)
+
+    # Set alpha_xl to the step size for the lower-bound constraint and
+    # alpha_xu to the step size for the upper-bound constraint.
+
+    # xl.shape = (N,)
+    # xpt.shape = (N, M)
+    # i_xl_pos.shape = (M, N)
+    i_xl_pos = (xl > -np.inf) & (xpt.T > -TINY * xl)
+    i_xl_neg = (xl > -np.inf) & (xpt.T < TINY * xl)
+    i_xu_pos = (xu < np.inf) & (xpt.T > TINY * xu)
+    i_xu_neg = (xu < np.inf) & (xpt.T < -TINY * xu)
+
+    # (M, N)
+    alpha_xl_pos = np.atleast_2d(
+        np.broadcast_to(xl, i_xl_pos.shape)[i_xl_pos] / xpt.T[i_xl_pos]
+    )
+    # (M,)
+    alpha_xl_pos = np.max(alpha_xl_pos, axis=1, initial=-np.inf)
+    # make sure it's (M,)
+    alpha_xl_pos = np.broadcast_to(np.atleast_1d(alpha_xl_pos), xpt.shape[1])
+
+    alpha_xl_neg = np.atleast_2d(
+        np.broadcast_to(xl, i_xl_neg.shape)[i_xl_neg] / xpt.T[i_xl_neg]
+    )
+    alpha_xl_neg = np.max(alpha_xl_neg, axis=1, initial=np.inf)
+    alpha_xl_neg = np.broadcast_to(np.atleast_1d(alpha_xl_neg), xpt.shape[1])
+
+    alpha_xu_neg = np.atleast_2d(
+        np.broadcast_to(xu, i_xu_neg.shape)[i_xu_neg] / xpt.T[i_xu_neg]
+    )
+    alpha_xu_neg = np.max(alpha_xu_neg, axis=1, initial=-np.inf)
+    alpha_xu_neg = np.broadcast_to(np.atleast_1d(alpha_xu_neg), xpt.shape[1])
+
+    alpha_xu_pos = np.atleast_2d(
+        np.broadcast_to(xu, i_xu_pos.shape)[i_xu_pos] / xpt.T[i_xu_pos]
+    )
+    alpha_xu_pos = np.max(alpha_xu_pos, axis=1, initial=np.inf)
+    alpha_xu_pos = np.broadcast_to(np.atleast_1d(alpha_xu_pos), xpt.shape[1])
+
+    for k in range(xpt.shape[1]):
+        # Set alpha_tr to the step size for the trust-region constraint.
+        if s_norm[k] > TINY * delta:
+            alpha_tr = max(delta / s_norm[k], 0.0)
+        else:
+            # The current straight line is basically zero.
+            continue
+
+        alpha_bd_pos = max(min(alpha_xu_pos[k], alpha_xl_neg[k]), 0.0)
+        alpha_bd_neg = min(max(alpha_xl_pos[k], alpha_xu_neg[k]), 0.0)
+
+        # Set alpha_quad_pos and alpha_quad_neg to the step size to the extrema
+        # of the quadratic function along the positive and negative directions.
+        grad_step = grad @ xpt[:, k]
+        curv_step = curv(xpt[:, k])
+        if (
+            grad_step >= 0.0
+            and curv_step < -TINY * grad_step
+            or grad_step <= 0.0
+            and curv_step > -TINY * grad_step
+        ):
+            alpha_quad_pos = max(-grad_step / curv_step, 0.0)
+        else:
+            alpha_quad_pos = np.inf
+        if (
+            grad_step >= 0.0
+            and curv_step > TINY * grad_step
+            or grad_step <= 0.0
+            and curv_step < TINY * grad_step
+        ):
+            alpha_quad_neg = min(-grad_step / curv_step, 0.0)
+        else:
+            alpha_quad_neg = -np.inf
+
+        # Select the step that provides the largest value of the objective
+        # function if it improves the current best. The best positive step is
+        # either the one that reaches the constraints or the one that reaches
+        # the extremum of the objective function along the current direction
+        # (only possible if the resulting step is feasible). We test both, and
+        # we perform similar calculations along the negative step.
+        # N.B.: we select the largest possible step among all the ones that
+        # maximize the objective function. This is to avoid returning the zero
+        # step in some extreme cases.
+        alpha_pos = min(alpha_tr, alpha_bd_pos)
+        alpha_neg = max(-alpha_tr, alpha_bd_neg)
+        q_val_pos = (
+            const + alpha_pos * grad_step + 0.5 * alpha_pos**2.0 * curv_step
+        )
+        q_val_neg = (
+            const + alpha_neg * grad_step + 0.5 * alpha_neg**2.0 * curv_step
+        )
+        if alpha_quad_pos < alpha_pos:
+            q_val_quad_pos = (
+                const
+                + alpha_quad_pos * grad_step
+                + 0.5 * alpha_quad_pos**2.0 * curv_step
+            )
+            if abs(q_val_quad_pos) > abs(q_val_pos):
+                alpha_pos = alpha_quad_pos
+                q_val_pos = q_val_quad_pos
+        if alpha_quad_neg > alpha_neg:
+            q_val_quad_neg = (
+                const
+                + alpha_quad_neg * grad_step
+                + 0.5 * alpha_quad_neg**2.0 * curv_step
+            )
+            if abs(q_val_quad_neg) > abs(q_val_neg):
+                alpha_neg = alpha_quad_neg
+                q_val_neg = q_val_quad_neg
+        if abs(q_val_pos) >= abs(q_val_neg) and abs(q_val_pos) > abs(q_val):
+            step = np.clip(alpha_pos * xpt[:, k], xl, xu)
+            q_val = q_val_pos
+        elif abs(q_val_neg) > abs(q_val_pos) and abs(q_val_neg) > abs(q_val):
+            step = np.clip(alpha_neg * xpt[:, k], xl, xu)
+            q_val = q_val_neg
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def _cauchy_geom(const, grad, curv, xl, xu, delta, debug):
+    """
+    Same as `bound_constrained_cauchy_step` without the absolute value.
+    """
+    # Calculate the initial active set.
+    fixed_xl = (xl < 0.0) & (grad > 0.0)
+    fixed_xu = (xu > 0.0) & (grad < 0.0)
+
+    # Calculate the Cauchy step.
+    cauchy_step = np.zeros_like(grad)
+    cauchy_step[fixed_xl] = xl[fixed_xl]
+    cauchy_step[fixed_xu] = xu[fixed_xu]
+    if np.linalg.norm(cauchy_step) > delta:
+        working = fixed_xl | fixed_xu
+        while True:
+            # Calculate the Cauchy step for the directions in the working set.
+            g_norm = np.linalg.norm(grad[working])
+            delta_reduced = np.sqrt(
+                delta**2.0 - cauchy_step[~working] @ cauchy_step[~working]
+            )
+            if g_norm > TINY * abs(delta_reduced):
+                mu = max(delta_reduced / g_norm, 0.0)
+            else:
+                break
+            cauchy_step[working] = mu * grad[working]
+
+            # Update the working set.
+            fixed_xl = working & (cauchy_step < xl)
+            fixed_xu = working & (cauchy_step > xu)
+            if not np.any(fixed_xl) and not np.any(fixed_xu):
+                # Stop the calculations as the Cauchy step is now feasible.
+                break
+            cauchy_step[fixed_xl] = xl[fixed_xl]
+            cauchy_step[fixed_xu] = xu[fixed_xu]
+            working = working & ~(fixed_xl | fixed_xu)
+
+    # Calculate the step that maximizes the quadratic along the Cauchy step.
+    grad_step = grad @ cauchy_step
+    if grad_step >= 0.0:
+        # Set alpha_tr to the step size for the trust-region constraint.
+        s_norm = np.linalg.norm(cauchy_step)
+        if s_norm > TINY * delta:
+            alpha_tr = max(delta / s_norm, 0.0)
+        else:
+            # The Cauchy step is basically zero.
+            alpha_tr = 0.0
+
+        # Set alpha_quad to the step size for the maximization problem.
+        curv_step = curv(cauchy_step)
+        if curv_step < -TINY * grad_step:
+            alpha_quad = max(-grad_step / curv_step, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = (xl > -np.inf) & (cauchy_step < TINY * xl)
+        i_xu = (xu < np.inf) & (cauchy_step > TINY * xu)
+        alpha_xl = np.min(xl[i_xl] / cauchy_step[i_xl], initial=np.inf)
+        alpha_xu = np.min(xu[i_xu] / cauchy_step[i_xu], initial=np.inf)
+        alpha_bd = min(alpha_xl, alpha_xu)
+
+        # Calculate the solution and the corresponding function value.
+        alpha = min(alpha_tr, alpha_quad, alpha_bd)
+        step = np.clip(alpha * cauchy_step, xl, xu)
+        q_val = const + alpha * grad_step + 0.5 * alpha**2.0 * curv_step
+    else:
+        # This case is never reached in exact arithmetic. It prevents this
+        # function to return a step that decreases the objective function.
+        step = np.zeros_like(grad)
+        q_val = const
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step, q_val
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a960396fb2e992cf76bac0baf171b5af9b7717
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
@@ -0,0 +1,1203 @@
+import inspect
+
+import numpy as np
+from scipy.linalg import qr
+
+from ..utils import get_arrays_tol
+
+
+TINY = np.finfo(float).tiny
+EPS = np.finfo(float).eps
+
+
+def tangential_byrd_omojokun(grad, hess_prod, xl, xu, delta, debug, **kwargs):
+    r"""
+    Minimize approximately a quadratic function subject to bound constraints in
+    a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2}
+        s^{\mathsf{T}} H s \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    using an active-set variation of the truncated conjugate gradient method.
+
+    Parameters
+    ----------
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    hess_prod : callable
+        Product of the Hessian matrix :math:`H` with any vector.
+
+            ``hess_prod(s) -> `numpy.ndarray`, shape (n,)``
+
+        returns the product :math:`H s`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Other Parameters
+    ----------------
+    improve_tcg : bool, optional
+        If True, a solution generated by the truncated conjugate gradient
+        method that is on the boundary of the trust region is improved by
+        moving around the trust-region boundary on the two-dimensional space
+        spanned by the solution and the gradient of the quadratic function at
+        the solution (default is True).
+
+    Notes
+    -----
+    This function implements Algorithm 6.2 of [1]_. It is assumed that the
+    origin is feasible with respect to the bound constraints and that `delta`
+    is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *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.
+    """
+    if debug:
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(hess_prod).bind(grad)
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # Copy the arrays that may be modified by the code below.
+    n = grad.size
+    grad = np.copy(grad)
+    grad_orig = np.copy(grad)
+
+    # Calculate the initial active set.
+    free_bd = ((xl < 0.0) | (grad < 0.0)) & ((xu > 0.0) | (grad > 0.0))
+
+    # Set the initial iterate and the initial search direction.
+    step = np.zeros_like(grad)
+    sd = np.zeros_like(step)
+    sd[free_bd] = -grad[free_bd]
+
+    k = 0
+    reduct = 0.0
+    boundary_reached = False
+    while k < np.count_nonzero(free_bd):
+        # Stop the computations if sd is not a descent direction.
+        grad_sd = grad @ sd
+        if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
+            break
+
+        # Set alpha_tr to the step size for the trust-region constraint.
+        try:
+            alpha_tr = _alpha_tr(step, sd, delta)
+        except ZeroDivisionError:
+            break
+
+        # Stop the computations if a step along sd is expected to give a
+        # relatively small reduction in the objective function.
+        if -alpha_tr * grad_sd <= 1e-8 * reduct:
+            break
+
+        # Set alpha_quad to the step size for the minimization problem.
+        hess_sd = hess_prod(sd)
+        curv_sd = sd @ hess_sd
+        if curv_sd > TINY * abs(grad_sd):
+            alpha_quad = max(-grad_sd / curv_sd, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Stop the computations if the reduction in the objective function
+        # provided by an unconstrained step is small.
+        alpha = min(alpha_tr, alpha_quad)
+        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
+            break
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = (xl > -np.inf) & (sd < -TINY * np.abs(xl - step))
+        i_xu = (xu < np.inf) & (sd > TINY * np.abs(xu - step))
+        all_alpha_xl = np.full_like(step, np.inf)
+        all_alpha_xu = np.full_like(step, np.inf)
+        all_alpha_xl[i_xl] = np.maximum(
+            (xl[i_xl] - step[i_xl]) / sd[i_xl],
+            0.0,
+        )
+        all_alpha_xu[i_xu] = np.maximum(
+            (xu[i_xu] - step[i_xu]) / sd[i_xu],
+            0.0,
+        )
+        alpha_xl = np.min(all_alpha_xl)
+        alpha_xu = np.min(all_alpha_xu)
+        alpha_bd = min(alpha_xl, alpha_xu)
+
+        # Update the iterate.
+        alpha = min(alpha, alpha_bd)
+        if alpha > 0.0:
+            step[free_bd] = np.clip(
+                step[free_bd] + alpha * sd[free_bd],
+                xl[free_bd],
+                xu[free_bd],
+            )
+            grad += alpha * hess_sd
+            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
+
+        if alpha < min(alpha_tr, alpha_bd):
+            # The current iteration is a conjugate gradient iteration. Update
+            # the search direction so that it is conjugate (with respect to H)
+            # to all the previous search directions.
+            beta = (grad[free_bd] @ hess_sd[free_bd]) / curv_sd
+            sd[free_bd] = beta * sd[free_bd] - grad[free_bd]
+            sd[~free_bd] = 0.0
+            k += 1
+        elif alpha < alpha_tr:
+            # The iterate is restricted by a bound constraint. Add this bound
+            # constraint to the active set, and restart the calculations.
+            if alpha_xl <= alpha:
+                i_new = np.argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+            else:
+                i_new = np.argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+            free_bd[i_new] = False
+            sd[free_bd] = -grad[free_bd]
+            sd[~free_bd] = 0.0
+            k = 0
+        else:
+            # The current iterate is on the trust-region boundary. Add all the
+            # active bounds to the working set to prepare for the improvement
+            # of the solution, and stop the iterations.
+            if alpha_xl <= alpha:
+                i_new = _argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_bd[i_new] = False
+            if alpha_xu <= alpha:
+                i_new = _argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_bd[i_new] = False
+            boundary_reached = True
+            break
+
+    # Attempt to improve the solution on the trust-region boundary.
+    if kwargs.get("improve_tcg", True) and boundary_reached:
+        step_base = np.copy(step)
+        step_comparator = grad_orig @ step_base + 0.5 * step_base @ hess_prod(
+            step_base
+        )
+
+        while np.count_nonzero(free_bd) > 0:
+            # Check whether a substantial reduction in the objective function
+            # is possible, and set the search direction.
+            step_sq = step[free_bd] @ step[free_bd]
+            grad_sq = grad[free_bd] @ grad[free_bd]
+            grad_step = grad[free_bd] @ step[free_bd]
+            grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
+            sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd]
+            sd[~free_bd] = 0.0
+            if grad_sd >= -1e-8 * reduct or np.any(
+                grad_sd >= -TINY * np.abs(sd[free_bd])
+            ):
+                break
+            sd[free_bd] /= -grad_sd
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration. The step will be updated as:
+            # step = cos(theta) * step + sin(theta) * sd.
+            temp_xl = np.zeros(n)
+            temp_xu = np.zeros(n)
+            temp_xl[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0
+            )
+            temp_xu[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0
+            )
+            temp_xl[temp_xl > 0.0] = (
+                np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
+            )
+            temp_xu[temp_xu > 0.0] = (
+                np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
+            )
+            dist_xl = np.maximum(step - xl, 0.0)
+            dist_xu = np.maximum(xu - step, 0.0)
+            i_xl = temp_xl > TINY * dist_xl
+            i_xu = temp_xu > TINY * dist_xu
+            all_t_xl = np.ones(n)
+            all_t_xu = np.ones(n)
+            all_t_xl[i_xl] = np.minimum(
+                all_t_xl[i_xl],
+                dist_xl[i_xl] / temp_xl[i_xl],
+            )
+            all_t_xu[i_xu] = np.minimum(
+                all_t_xu[i_xu],
+                dist_xu[i_xu] / temp_xu[i_xu],
+            )
+            t_xl = np.min(all_t_xl)
+            t_xu = np.min(all_t_xu)
+            t_bd = min(t_xl, t_xu)
+
+            # Calculate some curvature information.
+            hess_step = hess_prod(step)
+            hess_sd = hess_prod(sd)
+            curv_step = step @ hess_step
+            curv_sd = sd @ hess_sd
+            curv_step_sd = step @ hess_sd
+
+            # For a range of equally spaced values of tan(0.5 * theta),
+            # calculate the reduction in the objective function that would be
+            # obtained by accepting the corresponding angle.
+            n_samples = 20
+            n_samples = int((n_samples - 3) * t_bd + 3)
+            t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples)
+            sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0)
+            all_reduct = sin_values * (
+                grad_step * t_samples
+                - grad_sd
+                - t_samples * curv_step
+                + sin_values
+                * (t_samples * curv_step_sd - 0.5 * (curv_sd - curv_step))
+            )
+            if np.all(all_reduct <= 0.0):
+                # No reduction in the objective function is obtained.
+                break
+
+            # Accept the angle that provides the largest reduction in the
+            # objective function, and update the iterate.
+            i_max = np.argmax(all_reduct)
+            cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
+                1.0 + t_samples[i_max] ** 2.0
+            )
+            step[free_bd] = (
+                cos_value * step[free_bd] + sin_values[i_max] * sd[free_bd]
+            )
+            grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd
+            reduct += all_reduct[i_max]
+
+            # If the above angle is restricted by bound constraints, add them
+            # to the working set, and restart the alternative iteration.
+            # Otherwise, the calculations are terminated.
+            if t_bd < 1.0 and i_max == n_samples - 1:
+                if t_xl <= t_bd:
+                    i_new = _argmin(all_t_xl)
+                    step[i_new] = xl[i_new]
+                    free_bd[i_new] = False
+                if t_xu <= t_bd:
+                    i_new = _argmin(all_t_xu)
+                    step[i_new] = xu[i_new]
+                    free_bd[i_new] = False
+            else:
+                break
+
+        # Ensure that the alternative iteration improves the objective
+        # function.
+        if grad_orig @ step + 0.5 * step @ hess_prod(step) > step_comparator:
+            step = step_base
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def constrained_tangential_byrd_omojokun(
+    grad,
+    hess_prod,
+    xl,
+    xu,
+    aub,
+    bub,
+    aeq,
+    delta,
+    debug,
+    **kwargs,
+):
+    r"""
+    Minimize approximately a quadratic function subject to bound and linear
+    constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2}
+        s^{\mathsf{T}} H s \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            A_{\scriptscriptstyle I} s \le b_{\scriptscriptstyle I},\\
+            A_{\scriptscriptstyle E} s = 0,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    using an active-set variation of the truncated conjugate gradient method.
+
+    Parameters
+    ----------
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    hess_prod : callable
+        Product of the Hessian matrix :math:`H` with any vector.
+
+            ``hess_prod(s) -> `numpy.ndarray`, shape (n,)``
+
+        returns the product :math:`H s`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    aub : `numpy.ndarray`, shape (m_linear_ub, n)
+        Coefficient matrix :math:`A_{\scriptscriptstyle I}` as shown above.
+    bub : `numpy.ndarray`, shape (m_linear_ub,)
+        Right-hand side :math:`b_{\scriptscriptstyle I}` as shown above.
+    aeq : `numpy.ndarray`, shape (m_linear_eq, n)
+        Coefficient matrix :math:`A_{\scriptscriptstyle E}` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Other Parameters
+    ----------------
+    improve_tcg : bool, optional
+        If True, a solution generated by the truncated conjugate gradient
+        method that is on the boundary of the trust region is improved by
+        moving around the trust-region boundary on the two-dimensional space
+        spanned by the solution and the gradient of the quadratic function at
+        the solution (default is True).
+
+    Notes
+    -----
+    This function implements Algorithm 6.3 of [1]_. It is assumed that the
+    origin is feasible with respect to the bound and linear constraints, and
+    that `delta` is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *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.
+    """
+    if debug:
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(hess_prod).bind(grad)
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert (
+            isinstance(aub, np.ndarray)
+            and aub.ndim == 2
+            and aub.shape[1] == grad.size
+        )
+        assert (
+            isinstance(bub, np.ndarray)
+            and bub.ndim == 1
+            and bub.size == aub.shape[0]
+        )
+        assert (
+            isinstance(aeq, np.ndarray)
+            and aeq.ndim == 2
+            and aeq.shape[1] == grad.size
+        )
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.all(bub >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+    bub = np.maximum(bub, 0.0)
+
+    # Copy the arrays that may be modified by the code below.
+    n = grad.size
+    grad = np.copy(grad)
+    grad_orig = np.copy(grad)
+
+    # Calculate the initial active set.
+    free_xl = (xl < 0.0) | (grad < 0.0)
+    free_xu = (xu > 0.0) | (grad > 0.0)
+    free_ub = (bub > 0.0) | (aub @ grad > 0.0)
+    n_act, q = qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub)
+
+    # Set the initial iterate and the initial search direction.
+    step = np.zeros_like(grad)
+    sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+    resid = np.copy(bub)
+
+    k = 0
+    reduct = 0.0
+    boundary_reached = False
+    while k < n - n_act:
+        # Stop the computations if sd is not a descent direction.
+        grad_sd = grad @ sd
+        if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
+            break
+
+        # Set alpha_tr to the step size for the trust-region constraint.
+        try:
+            alpha_tr = _alpha_tr(step, sd, delta)
+        except ZeroDivisionError:
+            break
+
+        # Stop the computations if a step along sd is expected to give a
+        # relatively small reduction in the objective function.
+        if -alpha_tr * grad_sd <= 1e-8 * reduct:
+            break
+
+        # Set alpha_quad to the step size for the minimization problem.
+        hess_sd = hess_prod(sd)
+        curv_sd = sd @ hess_sd
+        if curv_sd > TINY * abs(grad_sd):
+            alpha_quad = max(-grad_sd / curv_sd, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Stop the computations if the reduction in the objective function
+        # provided by an unconstrained step is small.
+        alpha = min(alpha_tr, alpha_quad)
+        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
+            break
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = free_xl & (xl > -np.inf) & (sd < -TINY * np.abs(xl - step))
+        i_xu = free_xu & (xu < np.inf) & (sd > TINY * np.abs(xu - step))
+        all_alpha_xl = np.full_like(step, np.inf)
+        all_alpha_xu = np.full_like(step, np.inf)
+        all_alpha_xl[i_xl] = np.maximum(
+            (xl[i_xl] - step[i_xl]) / sd[i_xl],
+            0.0,
+        )
+        all_alpha_xu[i_xu] = np.maximum(
+            (xu[i_xu] - step[i_xu]) / sd[i_xu],
+            0.0,
+        )
+        alpha_xl = np.min(all_alpha_xl)
+        alpha_xu = np.min(all_alpha_xu)
+        alpha_bd = min(alpha_xl, alpha_xu)
+
+        # Set alpha_ub to the step size for the linear constraints.
+        aub_sd = aub @ sd
+        i_ub = free_ub & (aub_sd > TINY * np.abs(resid))
+        all_alpha_ub = np.full_like(bub, np.inf)
+        all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub]
+        alpha_ub = np.min(all_alpha_ub, initial=np.inf)
+
+        # Update the iterate.
+        alpha = min(alpha, alpha_bd, alpha_ub)
+        if alpha > 0.0:
+            step = np.clip(step + alpha * sd, xl, xu)
+            grad += alpha * hess_sd
+            resid = np.maximum(0.0, resid - alpha * aub_sd)
+            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
+
+        if alpha < min(alpha_tr, alpha_bd, alpha_ub):
+            # The current iteration is a conjugate gradient iteration. Update
+            # the search direction so that it is conjugate (with respect to H)
+            # to all the previous search directions.
+            grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            beta = (grad_proj @ hess_sd) / curv_sd
+            sd = beta * sd - grad_proj
+            k += 1
+        elif alpha < alpha_tr:
+            # The iterate is restricted by a bound/linear constraint. Add this
+            # constraint to the active set, and restart the calculations.
+            if alpha_xl <= alpha:
+                i_new = np.argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            elif alpha_xu <= alpha:
+                i_new = np.argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            else:
+                i_new = np.argmin(all_alpha_ub)
+                free_ub[i_new] = False
+            n_act, q = qr_tangential_byrd_omojokun(
+                aub,
+                aeq,
+                free_xl,
+                free_xu,
+                free_ub,
+            )
+            sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            k = 0
+        else:
+            # The current iterate is on the trust-region boundary. Add all the
+            # active bound/linear constraints to the working set to prepare for
+            # the improvement of the solution, and stop the iterations.
+            if alpha_xl <= alpha:
+                i_new = _argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            if alpha_xu <= alpha:
+                i_new = _argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            if alpha_ub <= alpha:
+                i_new = _argmin(all_alpha_ub)
+                free_ub[i_new] = False
+            n_act, q = qr_tangential_byrd_omojokun(
+                aub,
+                aeq,
+                free_xl,
+                free_xu,
+                free_ub,
+            )
+            boundary_reached = True
+            break
+
+    # Attempt to improve the solution on the trust-region boundary.
+    if kwargs.get("improve_tcg", True) and boundary_reached and n_act < n:
+        step_base = np.copy(step)
+        while n_act < n:
+            # Check whether a substantial reduction in the objective function
+            # is possible, and set the search direction.
+            step_proj = q[:, n_act:] @ (q[:, n_act:].T @ step)
+            grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            step_sq = step_proj @ step_proj
+            grad_sq = grad_proj @ grad_proj
+            grad_step = grad_proj @ step_proj
+            grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
+            sd = q[:, n_act:] @ (
+                q[:, n_act:].T @ (grad_step * step - step_sq * grad)
+            )
+            if grad_sd >= -1e-8 * reduct or np.any(
+                grad_sd >= -TINY * np.abs(sd)
+            ):
+                break
+            sd /= -grad_sd
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration for the bound constraints. The step
+            # will be updated as:
+            # step += (cos(theta) - 1) * step_proj + sin(theta) * sd.
+            temp_xl = np.zeros(n)
+            temp_xu = np.zeros(n)
+            dist_xl = np.maximum(step - xl, 0.0)
+            dist_xu = np.maximum(xu - step, 0.0)
+            temp_xl[free_xl] = sd[free_xl] ** 2.0 - dist_xl[free_xl] * (
+                dist_xl[free_xl] - 2.0 * step_proj[free_xl]
+            )
+            temp_xu[free_xu] = sd[free_xu] ** 2.0 - dist_xu[free_xu] * (
+                dist_xu[free_xu] + 2.0 * step_proj[free_xu]
+            )
+            temp_xl[temp_xl > 0.0] = (
+                np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
+            )
+            temp_xu[temp_xu > 0.0] = (
+                np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
+            )
+            i_xl = temp_xl > TINY * dist_xl
+            i_xu = temp_xu > TINY * dist_xu
+            all_t_xl = np.ones(n)
+            all_t_xu = np.ones(n)
+            all_t_xl[i_xl] = np.minimum(
+                all_t_xl[i_xl],
+                dist_xl[i_xl] / temp_xl[i_xl],
+            )
+            all_t_xu[i_xu] = np.minimum(
+                all_t_xu[i_xu],
+                dist_xu[i_xu] / temp_xu[i_xu],
+            )
+            t_xl = np.min(all_t_xl)
+            t_xu = np.min(all_t_xu)
+            t_bd = min(t_xl, t_xu)
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration for the linear constraints.
+            temp_ub = np.zeros_like(resid)
+            aub_step = aub @ step_proj
+            aub_sd = aub @ sd
+            temp_ub[free_ub] = aub_sd[free_ub] ** 2.0 - resid[free_ub] * (
+                resid[free_ub] + 2.0 * aub_step[free_ub]
+            )
+            temp_ub[temp_ub > 0.0] = (
+                np.sqrt(temp_ub[temp_ub > 0.0]) + aub_sd[temp_ub > 0.0]
+            )
+            i_ub = temp_ub > TINY * resid
+            all_t_ub = np.ones_like(resid)
+            all_t_ub[i_ub] = np.minimum(
+                all_t_ub[i_ub],
+                resid[i_ub] / temp_ub[i_ub],
+            )
+            t_ub = np.min(all_t_ub, initial=1.0)
+            t_min = min(t_bd, t_ub)
+
+            # Calculate some curvature information.
+            hess_step = hess_prod(step_proj)
+            hess_sd = hess_prod(sd)
+            curv_step = step_proj @ hess_step
+            curv_sd = sd @ hess_sd
+            curv_step_sd = step_proj @ hess_sd
+
+            # For a range of equally spaced values of tan(0.5 * theta),
+            # calculate the reduction in the objective function that would be
+            # obtained by accepting the corresponding angle.
+            n_samples = 20
+            n_samples = int((n_samples - 3) * t_min + 3)
+            t_samples = np.linspace(t_min / n_samples, t_min, n_samples)
+            sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0)
+            all_reduct = sin_values * (
+                grad_step * t_samples
+                - grad_sd
+                - sin_values
+                * (
+                    0.5 * t_samples**2.0 * curv_step
+                    - 2.0 * t_samples * curv_step_sd
+                    + 0.5 * curv_sd
+                )
+            )
+            if np.all(all_reduct <= 0.0):
+                # No reduction in the objective function is obtained.
+                break
+
+            # Accept the angle that provides the largest reduction in the
+            # objective function, and update the iterate.
+            i_max = np.argmax(all_reduct)
+            cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
+                1.0 + t_samples[i_max] ** 2.0
+            )
+            step = np.clip(
+                step + (cos_value - 1.0) * step_proj + sin_values[i_max] * sd,
+                xl,
+                xu,
+            )
+            grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd
+            resid = np.maximum(
+                0.0,
+                resid
+                - (cos_value - 1.0) * aub_step
+                - sin_values[i_max] * aub_sd,
+            )
+            reduct += all_reduct[i_max]
+
+            # If the above angle is restricted by bound constraints, add them
+            # to the working set, and restart the alternative iteration.
+            # Otherwise, the calculations are terminated.
+            if t_min < 1.0 and i_max == n_samples - 1:
+                if t_xl <= t_min:
+                    i_new = _argmin(all_t_xl)
+                    step[i_new] = xl[i_new]
+                    free_xl[i_new] = False
+                if t_xu <= t_min:
+                    i_new = _argmin(all_t_xu)
+                    step[i_new] = xu[i_new]
+                    free_xl[i_new] = False
+                if t_ub <= t_min:
+                    i_new = _argmin(all_t_ub)
+                    free_ub[i_new] = False
+                n_act, q = qr_tangential_byrd_omojokun(
+                    aub,
+                    aeq,
+                    free_xl,
+                    free_xu,
+                    free_ub,
+                )
+            else:
+                break
+
+        # Ensure that the alternative iteration improves the objective
+        # function.
+        if grad_orig @ step + 0.5 * step @ hess_prod(
+            step
+        ) > grad_orig @ step_base + 0.5 * step_base @ hess_prod(step_base):
+            step = step_base
+
+    if debug:
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.all(aub @ step <= bub + tol)
+        assert np.all(np.abs(aeq @ step) <= tol)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def normal_byrd_omojokun(aub, bub, aeq, beq, xl, xu, delta, debug, **kwargs):
+    r"""
+    Minimize approximately a linear constraint violation subject to bound
+    constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \min_{s \in \mathbb{R}^n} \quad \frac{1}{2} \big( \lVert \max \{
+        A_{\scriptscriptstyle I} s - b_{\scriptscriptstyle I}, 0 \} \rVert^2 +
+        \lVert A_{\scriptscriptstyle E} s - b_{\scriptscriptstyle E} \rVert^2
+        \big) \quad \text{s.t.}
+        \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    using a variation of the truncated conjugate gradient method.
+
+    Parameters
+    ----------
+    aub : `numpy.ndarray`, shape (m_linear_ub, n)
+        Matrix :math:`A_{\scriptscriptstyle I}` as shown above.
+    bub : `numpy.ndarray`, shape (m_linear_ub,)
+        Vector :math:`b_{\scriptscriptstyle I}` as shown above.
+    aeq : `numpy.ndarray`, shape (m_linear_eq, n)
+        Matrix :math:`A_{\scriptscriptstyle E}` as shown above.
+    beq : `numpy.ndarray`, shape (m_linear_eq,)
+        Vector :math:`b_{\scriptscriptstyle E}` as shown above.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Other Parameters
+    ----------------
+    improve_tcg : bool, optional
+        If True, a solution generated by the truncated conjugate gradient
+        method that is on the boundary of the trust region is improved by
+        moving around the trust-region boundary on the two-dimensional space
+        spanned by the solution and the gradient of the quadratic function at
+        the solution (default is True).
+
+    Notes
+    -----
+    This function implements Algorithm 6.4 of [1]_. It is assumed that the
+    origin is feasible with respect to the bound constraints and that `delta`
+    is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *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.
+    """
+    if debug:
+        assert isinstance(aub, np.ndarray) and aub.ndim == 2
+        assert (
+            isinstance(bub, np.ndarray)
+            and bub.ndim == 1
+            and bub.size == aub.shape[0]
+        )
+        assert (
+            isinstance(aeq, np.ndarray)
+            and aeq.ndim == 2
+            and aeq.shape[1] == aub.shape[1]
+        )
+        assert (
+            isinstance(beq, np.ndarray)
+            and beq.ndim == 1
+            and beq.size == aeq.shape[0]
+        )
+        assert isinstance(xl, np.ndarray) and xl.shape == (aub.shape[1],)
+        assert isinstance(xu, np.ndarray) and xu.shape == (aub.shape[1],)
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # Calculate the initial active set.
+    m_linear_ub, n = aub.shape
+    grad = np.r_[aeq.T @ -beq, np.maximum(0.0, -bub)]
+    free_xl = (xl < 0.0) | (grad[:n] < 0.0)
+    free_xu = (xu > 0.0) | (grad[:n] > 0.0)
+    free_slack = bub < 0.0
+    free_ub = (bub > 0.0) | (aub @ grad[:n] - grad[n:] > 0.0)
+    n_act, q = qr_normal_byrd_omojokun(
+        aub,
+        free_xl,
+        free_xu,
+        free_slack,
+        free_ub,
+    )
+
+    # Calculate an upper bound on the norm of the slack variables. It is not
+    # used in the original algorithm, but it may prevent undesired behaviors
+    # engendered by computer rounding errors.
+    delta_slack = np.sqrt(beq @ beq + grad[n:] @ grad[n:])
+
+    # Set the initial iterate and the initial search direction.
+    step = np.zeros(n)
+    sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+    resid = bub + grad[n:]
+
+    k = 0
+    reduct = 0.0
+    boundary_reached = False
+    while k < n + m_linear_ub - n_act:
+        # Stop the computations if sd is not a descent direction.
+        grad_sd = grad @ sd
+        if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
+            break
+
+        # Set alpha_tr to the step size for the trust-region constraint.
+        try:
+            alpha_tr = _alpha_tr(step, sd[:n], delta)
+        except ZeroDivisionError:
+            alpha_tr = np.inf
+
+        # Prevent undesired behaviors engendered by computer rounding errors by
+        # considering the trust-region constraint on the slack variables.
+        try:
+            alpha_tr = min(alpha_tr, _alpha_tr(grad[n:], sd[n:], delta_slack))
+        except ZeroDivisionError:
+            pass
+
+        # Stop the computations if a step along sd is expected to give a
+        # relatively small reduction in the objective function.
+        if -alpha_tr * grad_sd <= 1e-8 * reduct:
+            break
+
+        # Set alpha_quad to the step size for the minimization problem.
+        hess_sd = np.r_[aeq.T @ (aeq @ sd[:n]), sd[n:]]
+        curv_sd = sd @ hess_sd
+        if curv_sd > TINY * abs(grad_sd):
+            alpha_quad = max(-grad_sd / curv_sd, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Stop the computations if the reduction in the objective function
+        # provided by an unconstrained step is small.
+        alpha = min(alpha_tr, alpha_quad)
+        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
+            break
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = free_xl & (xl > -np.inf) & (sd[:n] < -TINY * np.abs(xl - step))
+        i_xu = free_xu & (xu < np.inf) & (sd[:n] > TINY * np.abs(xu - step))
+        i_slack = free_slack & (sd[n:] < -TINY * np.abs(grad[n:]))
+        all_alpha_xl = np.full_like(step, np.inf)
+        all_alpha_xu = np.full_like(step, np.inf)
+        all_alpha_slack = np.full_like(bub, np.inf)
+        all_alpha_xl[i_xl] = np.maximum(
+            (xl[i_xl] - step[i_xl]) / sd[:n][i_xl],
+            0.0,
+        )
+        all_alpha_xu[i_xu] = np.maximum(
+            (xu[i_xu] - step[i_xu]) / sd[:n][i_xu],
+            0.0,
+        )
+        all_alpha_slack[i_slack] = np.maximum(
+            -grad[n:][i_slack] / sd[n:][i_slack],
+            0.0,
+        )
+        alpha_xl = np.min(all_alpha_xl)
+        alpha_xu = np.min(all_alpha_xu)
+        alpha_slack = np.min(all_alpha_slack, initial=np.inf)
+        alpha_bd = min(alpha_xl, alpha_xu, alpha_slack)
+
+        # Set alpha_ub to the step size for the linear constraints.
+        aub_sd = aub @ sd[:n] - sd[n:]
+        i_ub = free_ub & (aub_sd > TINY * np.abs(resid))
+        all_alpha_ub = np.full_like(bub, np.inf)
+        all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub]
+        alpha_ub = np.min(all_alpha_ub, initial=np.inf)
+
+        # Update the iterate.
+        alpha = min(alpha, alpha_bd, alpha_ub)
+        if alpha > 0.0:
+            step = np.clip(step + alpha * sd[:n], xl, xu)
+            grad += alpha * hess_sd
+            resid = np.maximum(0.0, resid - alpha * aub_sd)
+            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
+
+        if alpha < min(alpha_tr, alpha_bd, alpha_ub):
+            # The current iteration is a conjugate gradient iteration. Update
+            # the search direction so that it is conjugate (with respect to H)
+            # to all the previous search directions.
+            grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            beta = (grad_proj @ hess_sd) / curv_sd
+            sd = beta * sd - grad_proj
+            k += 1
+        elif alpha < alpha_tr:
+            # The iterate is restricted by a bound/linear constraint. Add this
+            # constraint to the active set, and restart the calculations.
+            if alpha_xl <= alpha:
+                i_new = np.argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            elif alpha_xu <= alpha:
+                i_new = np.argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            elif alpha_slack <= alpha:
+                i_new = np.argmin(all_alpha_slack)
+                free_slack[i_new] = False
+            else:
+                i_new = np.argmin(all_alpha_ub)
+                free_ub[i_new] = False
+            n_act, q = qr_normal_byrd_omojokun(
+                aub, free_xl, free_xu, free_slack, free_ub
+            )
+            sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            k = 0
+        else:
+            # The current iterate is on the trust-region boundary. Add all the
+            # active bound constraints to the working set to prepare for the
+            # improvement of the solution, and stop the iterations.
+            if alpha_xl <= alpha:
+                i_new = _argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            if alpha_xu <= alpha:
+                i_new = _argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            boundary_reached = True
+            break
+
+    # Attempt to improve the solution on the trust-region boundary.
+    if kwargs.get("improve_tcg", True) and boundary_reached:
+        step_base = np.copy(step)
+        free_bd = free_xl & free_xu
+        grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ (
+            aeq @ step - beq
+        )
+        sd = np.zeros(n)
+        while np.count_nonzero(free_bd) > 0:
+            # Check whether a substantial reduction in the objective function
+            # is possible, and set the search direction.
+            step_sq = step[free_bd] @ step[free_bd]
+            grad_sq = grad[free_bd] @ grad[free_bd]
+            grad_step = grad[free_bd] @ step[free_bd]
+            grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
+            sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd]
+            sd[~free_bd] = 0.0
+            if grad_sd >= -1e-8 * reduct or np.any(
+                grad_sd >= -TINY * np.abs(sd[free_bd])
+            ):
+                break
+            sd[free_bd] /= -grad_sd
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration. The step will be updated as:
+            # step = cos(theta) * step + sin(theta) * sd.
+            temp_xl = np.zeros(n)
+            temp_xu = np.zeros(n)
+            temp_xl[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0
+            )
+            temp_xu[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0
+            )
+            temp_xl[temp_xl > 0.0] = (
+                np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
+            )
+            temp_xu[temp_xu > 0.0] = (
+                np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
+            )
+            dist_xl = np.maximum(step - xl, 0.0)
+            dist_xu = np.maximum(xu - step, 0.0)
+            i_xl = temp_xl > TINY * dist_xl
+            i_xu = temp_xu > TINY * dist_xu
+            all_t_xl = np.ones(n)
+            all_t_xu = np.ones(n)
+            all_t_xl[i_xl] = np.minimum(
+                all_t_xl[i_xl],
+                dist_xl[i_xl] / temp_xl[i_xl],
+            )
+            all_t_xu[i_xu] = np.minimum(
+                all_t_xu[i_xu],
+                dist_xu[i_xu] / temp_xu[i_xu],
+            )
+            t_xl = np.min(all_t_xl)
+            t_xu = np.min(all_t_xu)
+            t_bd = min(t_xl, t_xu)
+
+            # For a range of equally spaced values of tan(0.5 * theta),
+            # calculate the reduction in the objective function that would be
+            # obtained by accepting the corresponding angle.
+            n_samples = 20
+            n_samples = int((n_samples - 3) * t_bd + 3)
+            t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples)
+            resid_ub = np.maximum(aub @ step - bub, 0.0)
+            resid_eq = aeq @ step - beq
+            step_proj = np.copy(step)
+            step_proj[~free_bd] = 0.0
+            all_reduct = np.empty(n_samples)
+            for i in range(n_samples):
+                sin_value = 2.0 * t_samples[i] / (1.0 + t_samples[i] ** 2.0)
+                step_alt = np.clip(
+                    step + sin_value * (sd - t_samples[i] * step_proj),
+                    xl,
+                    xu,
+                )
+                resid_ub_alt = np.maximum(aub @ step_alt - bub, 0.0)
+                resid_eq_alt = aeq @ step_alt - beq
+                all_reduct[i] = 0.5 * (
+                    resid_ub @ resid_ub
+                    + resid_eq @ resid_eq
+                    - resid_ub_alt @ resid_ub_alt
+                    - resid_eq_alt @ resid_eq_alt
+                )
+            if np.all(all_reduct <= 0.0):
+                # No reduction in the objective function is obtained.
+                break
+
+            # Accept the angle that provides the largest reduction in the
+            # objective function, and update the iterate.
+            i_max = np.argmax(all_reduct)
+            cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
+                1.0 + t_samples[i_max] ** 2.0
+            )
+            sin_value = (2.0 * t_samples[i_max]
+                         / (1.0 + t_samples[i_max] ** 2.0))
+            step[free_bd] = cos_value * step[free_bd] + sin_value * sd[free_bd]
+            grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ (
+                aeq @ step - beq
+            )
+            reduct += all_reduct[i_max]
+
+            # If the above angle is restricted by bound constraints, add them
+            # to the working set, and restart the alternative iteration.
+            # Otherwise, the calculations are terminated.
+            if t_bd < 1.0 and i_max == n_samples - 1:
+                if t_xl <= t_bd:
+                    i_new = _argmin(all_t_xl)
+                    step[i_new] = xl[i_new]
+                    free_bd[i_new] = False
+                if t_xu <= t_bd:
+                    i_new = _argmin(all_t_xu)
+                    step[i_new] = xu[i_new]
+                    free_bd[i_new] = False
+            else:
+                break
+
+        # Ensure that the alternative iteration improves the objective
+        # function.
+        resid_ub = np.maximum(aub @ step - bub, 0.0)
+        resid_ub_base = np.maximum(aub @ step_base - bub, 0.0)
+        resid_eq = aeq @ step - beq
+        resid_eq_base = aeq @ step_base - beq
+        if (
+            resid_ub @ resid_ub + resid_eq @ resid_eq
+            > resid_ub_base @ resid_ub_base + resid_eq_base @ resid_eq_base
+        ):
+            step = step_base
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub):
+    n = free_xl.size
+    identity = np.eye(n)
+    q, r, _ = qr(
+        np.block(
+            [
+                [aeq],
+                [aub[~free_ub, :]],
+                [-identity[~free_xl, :]],
+                [identity[~free_xu, :]],
+            ]
+        ).T,
+        pivoting=True,
+    )
+    n_act = np.count_nonzero(
+        np.abs(np.diag(r))
+        >= 10.0
+        * EPS
+        * n
+        * np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0)
+    )
+    return n_act, q
+
+
+def qr_normal_byrd_omojokun(aub, free_xl, free_xu, free_slack, free_ub):
+    m_linear_ub, n = aub.shape
+    identity_n = np.eye(n)
+    identity_m = np.eye(m_linear_ub)
+    q, r, _ = qr(
+        np.block(
+            [
+                [
+                    aub[~free_ub, :],
+                    -identity_m[~free_ub, :],
+                ],
+                [
+                    np.zeros((m_linear_ub - np.count_nonzero(free_slack), n)),
+                    -identity_m[~free_slack, :],
+                ],
+                [
+                    -identity_n[~free_xl, :],
+                    np.zeros((n - np.count_nonzero(free_xl), m_linear_ub)),
+                ],
+                [
+                    identity_n[~free_xu, :],
+                    np.zeros((n - np.count_nonzero(free_xu), m_linear_ub)),
+                ],
+            ]
+        ).T,
+        pivoting=True,
+    )
+    n_act = np.count_nonzero(
+        np.abs(np.diag(r))
+        >= 10.0
+        * EPS
+        * (n + m_linear_ub)
+        * np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0)
+    )
+    return n_act, q
+
+
+def _alpha_tr(step, sd, delta):
+    step_sd = step @ sd
+    sd_sq = sd @ sd
+    dist_tr_sq = delta**2.0 - step @ step
+    temp = np.sqrt(max(step_sd**2.0 + sd_sq * dist_tr_sq, 0.0))
+    if step_sd <= 0.0 and sd_sq > TINY * abs(temp - step_sd):
+        alpha_tr = max((temp - step_sd) / sd_sq, 0.0)
+    elif abs(temp + step_sd) > TINY * dist_tr_sq:
+        alpha_tr = max(dist_tr_sq / (temp + step_sd), 0.0)
+    else:
+        raise ZeroDivisionError
+    return alpha_tr
+
+
+def _argmax(x):
+    return np.flatnonzero(x >= np.max(x))
+
+
+def _argmin(x):
+    return np.flatnonzero(x <= np.min(x))
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe6b4841ddff3a04bda5cbff744e30681b6963b9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py
@@ -0,0 +1,18 @@
+from .exceptions import (
+    MaxEvalError,
+    TargetSuccess,
+    CallbackSuccess,
+    FeasibleSuccess,
+)
+from .math import get_arrays_tol, exact_1d_array
+from .versions import show_versions
+
+__all__ = [
+    "MaxEvalError",
+    "TargetSuccess",
+    "CallbackSuccess",
+    "FeasibleSuccess",
+    "get_arrays_tol",
+    "exact_1d_array",
+    "show_versions",
+]
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c4fbb68f4642d3b51c513a5eceaa4f0f3343cff
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ad587ddfd2345c3baeee6293aeaacf1f89efc4c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/math.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/math.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e738ab7afd23708bc006df84f34d8635e2fced0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/math.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/versions.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/versions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..540cee7021130a7bbd1b79d437e19d7dbb587e5b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__pycache__/versions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85094894f378a8e3934ad109ea6166e33e4366b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
@@ -0,0 +1,22 @@
+class MaxEvalError(Exception):
+    """
+    Exception raised when the maximum number of evaluations is reached.
+    """
+
+
+class TargetSuccess(Exception):
+    """
+    Exception raised when the target value is reached.
+    """
+
+
+class CallbackSuccess(StopIteration):
+    """
+    Exception raised when the callback function raises a ``StopIteration``.
+    """
+
+
+class FeasibleSuccess(Exception):
+    """
+    Exception raised when a feasible point of a feasible problem is found.
+    """
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b16ae98a0df38752815f5a69d56da20f856f9f9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py
@@ -0,0 +1,77 @@
+import numpy as np
+
+
+EPS = np.finfo(float).eps
+
+
+def get_arrays_tol(*arrays):
+    """
+    Get a relative tolerance for a set of arrays.
+
+    Parameters
+    ----------
+    *arrays: tuple
+        Set of `numpy.ndarray` to get the tolerance for.
+
+    Returns
+    -------
+    float
+        Relative tolerance for the set of arrays.
+
+    Raises
+    ------
+    ValueError
+        If no array is provided.
+    """
+    if len(arrays) == 0:
+        raise ValueError("At least one array must be provided.")
+    size = max(array.size for array in arrays)
+    weight = max(
+        np.max(np.abs(array[np.isfinite(array)]), initial=1.0)
+        for array in arrays
+    )
+    return 10.0 * EPS * max(size, 1.0) * weight
+
+
+def exact_1d_array(x, message):
+    """
+    Preprocess a 1-dimensional array.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to be preprocessed.
+    message : str
+        Error message if `x` cannot be interpreter as a 1-dimensional array.
+
+    Returns
+    -------
+    `numpy.ndarray`
+        Preprocessed array.
+    """
+    x = np.atleast_1d(np.squeeze(x)).astype(float)
+    if x.ndim != 1:
+        raise ValueError(message)
+    return x
+
+
+def exact_2d_array(x, message):
+    """
+    Preprocess a 2-dimensional array.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to be preprocessed.
+    message : str
+        Error message if `x` cannot be interpreter as a 2-dimensional array.
+
+    Returns
+    -------
+    `numpy.ndarray`
+        Preprocessed array.
+    """
+    x = np.atleast_2d(x).astype(float)
+    if x.ndim != 2:
+        raise ValueError(message)
+    return x
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..94a0f8f5cef626354f40901cbe06a84287291c1c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py
@@ -0,0 +1,67 @@
+import os
+import platform
+import sys
+from importlib.metadata import PackageNotFoundError, version
+
+
+def _get_sys_info():
+    """
+    Get useful system information.
+
+    Returns
+    -------
+    dict
+        Useful system information.
+    """
+    return {
+        "python": sys.version.replace(os.linesep, " "),
+        "executable": sys.executable,
+        "machine": platform.platform(),
+    }
+
+
+def _get_deps_info():
+    """
+    Get the versions of the dependencies.
+
+    Returns
+    -------
+    dict
+        Versions of the dependencies.
+    """
+    deps = ["cobyqa", "numpy", "scipy", "setuptools", "pip"]
+    deps_info = {}
+    for module in deps:
+        try:
+            deps_info[module] = version(module)
+        except PackageNotFoundError:
+            deps_info[module] = None
+    return deps_info
+
+
+def show_versions():
+    """
+    Display useful system and dependencies information.
+
+    When reporting issues, please include this information.
+    """
+    print("System settings")
+    print("---------------")
+    sys_info = _get_sys_info()
+    print(
+        "\n".join(
+            f"{k:>{max(map(len, sys_info.keys())) + 1}}: {v}"
+            for k, v in sys_info.items()
+        )
+    )
+
+    print()
+    print("Python dependencies")
+    print("-------------------")
+    deps_info = _get_deps_info()
+    print(
+        "\n".join(
+            f"{k:>{max(map(len, deps_info.keys())) + 1}}: {v}"
+            for k, v in deps_info.items()
+        )
+    )
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/decorator.py b/venv/lib/python3.10/site-packages/scipy/_lib/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c4ab90e3d52db448b6381bc7860f55ac8789c9c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/decorator.py
@@ -0,0 +1,399 @@
+# #########################     LICENSE     ############################ #
+
+# Copyright (c) 2005-2015, Michele Simionato
+# All rights reserved.
+
+# 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 bytecode 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.
+
+# 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
+# HOLDERS 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.
+
+"""
+Decorator module, see https://pypi.python.org/pypi/decorator
+for the documentation.
+"""
+import re
+import sys
+import inspect
+import operator
+import itertools
+import collections
+
+from inspect import getfullargspec
+
+__version__ = '4.0.5'
+
+
+def get_init(cls):
+    return cls.__init__
+
+
+# getargspec has been deprecated in Python 3.5
+ArgSpec = collections.namedtuple(
+    'ArgSpec', 'args varargs varkw defaults')
+
+
+def getargspec(f):
+    """A replacement for inspect.getargspec"""
+    spec = getfullargspec(f)
+    return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
+
+
+DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
+
+
+# basic functionality
+class FunctionMaker:
+    """
+    An object with the ability to create functions with a given signature.
+    It has attributes name, doc, module, signature, defaults, dict, and
+    methods update and make.
+    """
+
+    # Atomic get-and-increment provided by the GIL
+    _compile_count = itertools.count()
+
+    def __init__(self, func=None, name=None, signature=None,
+                 defaults=None, doc=None, module=None, funcdict=None):
+        self.shortsignature = signature
+        if func:
+            # func can be a class or a callable, but not an instance method
+            self.name = func.__name__
+            if self.name == '':  # small hack for lambda functions
+                self.name = '_lambda_'
+            self.doc = func.__doc__
+            self.module = func.__module__
+            if inspect.isfunction(func):
+                argspec = getfullargspec(func)
+                self.annotations = getattr(func, '__annotations__', {})
+                for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
+                          'kwonlydefaults'):
+                    setattr(self, a, getattr(argspec, a))
+                for i, arg in enumerate(self.args):
+                    setattr(self, 'arg%d' % i, arg)
+                allargs = list(self.args)
+                allshortargs = list(self.args)
+                if self.varargs:
+                    allargs.append('*' + self.varargs)
+                    allshortargs.append('*' + self.varargs)
+                elif self.kwonlyargs:
+                    allargs.append('*')  # single star syntax
+                for a in self.kwonlyargs:
+                    allargs.append(f'{a}=None')
+                    allshortargs.append(f'{a}={a}')
+                if self.varkw:
+                    allargs.append('**' + self.varkw)
+                    allshortargs.append('**' + self.varkw)
+                self.signature = ', '.join(allargs)
+                self.shortsignature = ', '.join(allshortargs)
+                self.dict = func.__dict__.copy()
+        # func=None happens when decorating a caller
+        if name:
+            self.name = name
+        if signature is not None:
+            self.signature = signature
+        if defaults:
+            self.defaults = defaults
+        if doc:
+            self.doc = doc
+        if module:
+            self.module = module
+        if funcdict:
+            self.dict = funcdict
+        # check existence required attributes
+        assert hasattr(self, 'name')
+        if not hasattr(self, 'signature'):
+            raise TypeError(f'You are decorating a non-function: {func}')
+
+    def update(self, func, **kw):
+        "Update the signature of func with the data in self"
+        func.__name__ = self.name
+        func.__doc__ = getattr(self, 'doc', None)
+        func.__dict__ = getattr(self, 'dict', {})
+        func.__defaults__ = getattr(self, 'defaults', ())
+        func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
+        func.__annotations__ = getattr(self, 'annotations', None)
+        try:
+            frame = sys._getframe(3)
+        except AttributeError:  # for IronPython and similar implementations
+            callermodule = '?'
+        else:
+            callermodule = frame.f_globals.get('__name__', '?')
+        func.__module__ = getattr(self, 'module', callermodule)
+        func.__dict__.update(kw)
+
+    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
+        "Make a new function from a given template and update the signature"
+        src = src_templ % vars(self)  # expand name and signature
+        evaldict = evaldict or {}
+        mo = DEF.match(src)
+        if mo is None:
+            raise SyntaxError(f'not a valid function template\n{src}')
+        name = mo.group(1)  # extract the function name
+        names = set([name] + [arg.strip(' *') for arg in
+                              self.shortsignature.split(',')])
+        for n in names:
+            if n in ('_func_', '_call_'):
+                raise NameError(f'{n} is overridden in\n{src}')
+        if not src.endswith('\n'):  # add a newline just for safety
+            src += '\n'  # this is needed in old versions of Python
+
+        # Ensure each generated function has a unique filename for profilers
+        # (such as cProfile) that depend on the tuple of (,
+        # , ) being unique.
+        filename = '' % (next(self._compile_count),)
+        try:
+            code = compile(src, filename, 'single')
+            exec(code, evaldict)
+        except:  # noqa: E722
+            print('Error in generated code:', file=sys.stderr)
+            print(src, file=sys.stderr)
+            raise
+        func = evaldict[name]
+        if addsource:
+            attrs['__source__'] = src
+        self.update(func, **attrs)
+        return func
+
+    @classmethod
+    def create(cls, obj, body, evaldict, defaults=None,
+               doc=None, module=None, addsource=True, **attrs):
+        """
+        Create a function from the strings name, signature, and body.
+        evaldict is the evaluation dictionary. If addsource is true, an
+        attribute __source__ is added to the result. The attributes attrs
+        are added, if any.
+        """
+        if isinstance(obj, str):  # "name(signature)"
+            name, rest = obj.strip().split('(', 1)
+            signature = rest[:-1]  # strip a right parens
+            func = None
+        else:  # a function
+            name = None
+            signature = None
+            func = obj
+        self = cls(func, name, signature, defaults, doc, module)
+        ibody = '\n'.join('    ' + line for line in body.splitlines())
+        return self.make('def %(name)s(%(signature)s):\n' + ibody,
+                         evaldict, addsource, **attrs)
+
+
+def decorate(func, caller):
+    """
+    decorate(func, caller) decorates a function using a caller.
+    """
+    evaldict = func.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_func_'] = func
+    fun = FunctionMaker.create(
+        func, "return _call_(_func_, %(shortsignature)s)",
+        evaldict, __wrapped__=func)
+    if hasattr(func, '__qualname__'):
+        fun.__qualname__ = func.__qualname__
+    return fun
+
+
+def decorator(caller, _func=None):
+    """decorator(caller) converts a caller function into a decorator"""
+    if _func is not None:  # return a decorated function
+        # this is obsolete behavior; you should use decorate instead
+        return decorate(_func, caller)
+    # else return a decorator function
+    if inspect.isclass(caller):
+        name = caller.__name__.lower()
+        callerfunc = get_init(caller)
+        doc = (f'decorator({caller.__name__}) converts functions/generators into ' 
+               f'factories of {caller.__name__} objects')
+    elif inspect.isfunction(caller):
+        if caller.__name__ == '':
+            name = '_lambda_'
+        else:
+            name = caller.__name__
+        callerfunc = caller
+        doc = caller.__doc__
+    else:  # assume caller is an object with a __call__ method
+        name = caller.__class__.__name__.lower()
+        callerfunc = caller.__call__.__func__
+        doc = caller.__call__.__doc__
+    evaldict = callerfunc.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_decorate_'] = decorate
+    return FunctionMaker.create(
+        f'{name}(func)', 'return _decorate_(func, _call_)',
+        evaldict, doc=doc, module=caller.__module__,
+        __wrapped__=caller)
+
+
+# ####################### contextmanager ####################### #
+
+try:  # Python >= 3.2
+    from contextlib import _GeneratorContextManager
+except ImportError:  # Python >= 2.5
+    from contextlib import GeneratorContextManager as _GeneratorContextManager
+
+
+class ContextManager(_GeneratorContextManager):
+    def __call__(self, func):
+        """Context manager decorator"""
+        return FunctionMaker.create(
+            func, "with _self_: return _func_(%(shortsignature)s)",
+            dict(_self_=self, _func_=func), __wrapped__=func)
+
+
+init = getfullargspec(_GeneratorContextManager.__init__)
+n_args = len(init.args)
+if n_args == 2 and not init.varargs:  # (self, genobj) Python 2.7
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g(*a, **k))
+    ContextManager.__init__ = __init__
+elif n_args == 2 and init.varargs:  # (self, gen, *a, **k) Python 3.4
+    pass
+elif n_args == 4:  # (self, gen, args, kwds) Python 3.5
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g, a, k)
+    ContextManager.__init__ = __init__
+
+contextmanager = decorator(ContextManager)
+
+
+# ############################ dispatch_on ############################ #
+
+def append(a, vancestors):
+    """
+    Append ``a`` to the list of the virtual ancestors, unless it is already
+    included.
+    """
+    add = True
+    for j, va in enumerate(vancestors):
+        if issubclass(va, a):
+            add = False
+            break
+        if issubclass(a, va):
+            vancestors[j] = a
+            add = False
+    if add:
+        vancestors.append(a)
+
+
+# inspired from simplegeneric by P.J. Eby and functools.singledispatch
+def dispatch_on(*dispatch_args):
+    """
+    Factory of decorators turning a function into a generic function
+    dispatching on the given arguments.
+    """
+    assert dispatch_args, 'No dispatch args passed'
+    dispatch_str = f"({', '.join(dispatch_args)},)"
+
+    def check(arguments, wrong=operator.ne, msg=''):
+        """Make sure one passes the expected number of arguments"""
+        if wrong(len(arguments), len(dispatch_args)):
+            raise TypeError(f'Expected {len(dispatch_args)} arguments, '
+                            'got {len(arguments)}{msg}')
+
+    def gen_func_dec(func):
+        """Decorator turning a function into a generic function"""
+
+        # first check the dispatch arguments
+        argset = set(getfullargspec(func).args)
+        if not set(dispatch_args) <= argset:
+            raise NameError(f'Unknown dispatch arguments {dispatch_str}')
+
+        typemap = {}
+
+        def vancestors(*types):
+            """
+            Get a list of sets of virtual ancestors for the given types
+            """
+            check(types)
+            ras = [[] for _ in range(len(dispatch_args))]
+            for types_ in typemap:
+                for t, type_, ra in zip(types, types_, ras):
+                    if issubclass(t, type_) and type_ not in t.__mro__:
+                        append(type_, ra)
+            return [set(ra) for ra in ras]
+
+        def ancestors(*types):
+            """
+            Get a list of virtual MROs, one for each type
+            """
+            check(types)
+            lists = []
+            for t, vas in zip(types, vancestors(*types)):
+                n_vas = len(vas)
+                if n_vas > 1:
+                    raise RuntimeError(
+                        f'Ambiguous dispatch for {t}: {vas}')
+                elif n_vas == 1:
+                    va, = vas
+                    mro = type('t', (t, va), {}).__mro__[1:]
+                else:
+                    mro = t.__mro__
+                lists.append(mro[:-1])  # discard t and object
+            return lists
+
+        def register(*types):
+            """
+            Decorator to register an implementation for the given types
+            """
+            check(types)
+
+            def dec(f):
+                check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
+                typemap[types] = f
+                return f
+            return dec
+
+        def dispatch_info(*types):
+            """
+            An utility to introspect the dispatch algorithm
+            """
+            check(types)
+            lst = [tuple(a.__name__ for a in anc)
+                   for anc in itertools.product(*ancestors(*types))]
+            return lst
+
+        def _dispatch(dispatch_args, *args, **kw):
+            types = tuple(type(arg) for arg in dispatch_args)
+            try:  # fast path
+                f = typemap[types]
+            except KeyError:
+                pass
+            else:
+                return f(*args, **kw)
+            combinations = itertools.product(*ancestors(*types))
+            next(combinations)  # the first one has been already tried
+            for types_ in combinations:
+                f = typemap.get(types_)
+                if f is not None:
+                    return f(*args, **kw)
+
+            # else call the default implementation
+            return func(*args, **kw)
+
+        return FunctionMaker.create(
+            func, f'return _f_({dispatch_str}, %%(shortsignature)s)',
+            dict(_f_=_dispatch), register=register, default=func,
+            typemap=typemap, vancestors=vancestors, ancestors=ancestors,
+            dispatch_info=dispatch_info, __wrapped__=func)
+
+    gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
+    return gen_func_dec
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py b/venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a6ef8f39ba764b46fdc01de9281cdbf72f4736
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py
@@ -0,0 +1,274 @@
+from inspect import Parameter, signature
+import functools
+import warnings
+from importlib import import_module
+from scipy._lib._docscrape import FunctionDoc
+
+
+__all__ = ["_deprecated"]
+
+
+# Object to use as default value for arguments to be deprecated. This should
+# be used over 'None' as the user could parse 'None' as a positional argument
+_NoValue = object()
+
+def _sub_module_deprecation(*, sub_package, module, private_modules, all,
+                            attribute, correct_module=None, dep_version="1.16.0"):
+    """Helper function for deprecating modules that are public but were
+    intended to be private.
+
+    Parameters
+    ----------
+    sub_package : str
+        Subpackage the module belongs to eg. stats
+    module : str
+        Public but intended private module to deprecate
+    private_modules : list
+        Private replacement(s) for `module`; should contain the
+        content of ``all``, possibly spread over several modules.
+    all : list
+        ``__all__`` belonging to `module`
+    attribute : str
+        The attribute in `module` being accessed
+    correct_module : str, optional
+        Module in `sub_package` that `attribute` should be imported from.
+        Default is that `attribute` should be imported from ``scipy.sub_package``.
+    dep_version : str, optional
+        Version in which deprecated attributes will be removed.
+    """
+    if correct_module is not None:
+        correct_import = f"scipy.{sub_package}.{correct_module}"
+    else:
+        correct_import = f"scipy.{sub_package}"
+
+    if attribute not in all:
+        raise AttributeError(
+            f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
+            f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+
+    attr = getattr(import_module(correct_import), attribute, None)
+
+    if attr is not None:
+        message = (
+            f"Please import `{attribute}` from the `{correct_import}` namespace; "
+            f"the `scipy.{sub_package}.{module}` namespace is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+    else:
+        message = (
+            f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
+            f"the `scipy.{sub_package}.{module}` namespace. "
+            f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
+            f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
+            f"will be removed in SciPy 2.0.0."
+        )
+
+    warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+    for module in private_modules:
+        try:
+            return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
+        except AttributeError as e:
+            # still raise an error if the attribute isn't in any of the expected
+            # private modules
+            if module == private_modules[-1]:
+                raise e
+            continue
+    
+
+def _deprecated(msg, stacklevel=2):
+    """Deprecate a function by emitting a warning on use."""
+    def wrap(fun):
+        if isinstance(fun, type):
+            warnings.warn(
+                f"Trying to deprecate class {fun!r}",
+                category=RuntimeWarning, stacklevel=2)
+            return fun
+
+        @functools.wraps(fun)
+        def call(*args, **kwargs):
+            warnings.warn(msg, category=DeprecationWarning,
+                          stacklevel=stacklevel)
+            return fun(*args, **kwargs)
+        call.__doc__ = fun.__doc__
+        return call
+
+    return wrap
+
+
+class _DeprecationHelperStr:
+    """
+    Helper class used by deprecate_cython_api
+    """
+    def __init__(self, content, message):
+        self._content = content
+        self._message = message
+
+    def __hash__(self):
+        return hash(self._content)
+
+    def __eq__(self, other):
+        res = (self._content == other)
+        if res:
+            warnings.warn(self._message, category=DeprecationWarning,
+                          stacklevel=2)
+        return res
+
+
+def deprecate_cython_api(module, routine_name, new_name=None, message=None):
+    """
+    Deprecate an exported cdef function in a public Cython API module.
+
+    Only functions can be deprecated; typedefs etc. cannot.
+
+    Parameters
+    ----------
+    module : module
+        Public Cython API module (e.g. scipy.linalg.cython_blas).
+    routine_name : str
+        Name of the routine to deprecate. May also be a fused-type
+        routine (in which case its all specializations are deprecated).
+    new_name : str
+        New name to include in the deprecation warning message
+    message : str
+        Additional text in the deprecation warning message
+
+    Examples
+    --------
+    Usually, this function would be used in the top-level of the
+    module ``.pyx`` file:
+
+    >>> from scipy._lib.deprecation import deprecate_cython_api
+    >>> import scipy.linalg.cython_blas as mod
+    >>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
+    ...                      message="Deprecated in Scipy 1.5.0")
+    >>> del deprecate_cython_api, mod
+
+    After this, Cython modules that use the deprecated function emit a
+    deprecation warning when they are imported.
+
+    """
+    old_name = f"{module.__name__}.{routine_name}"
+
+    if new_name is None:
+        depdoc = f"`{old_name}` is deprecated!"
+    else:
+        depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
+
+    if message is not None:
+        depdoc += "\n" + message
+
+    d = module.__pyx_capi__
+
+    # Check if the function is a fused-type function with a mangled name
+    j = 0
+    has_fused = False
+    while True:
+        fused_name = f"__pyx_fuse_{j}{routine_name}"
+        if fused_name in d:
+            has_fused = True
+            d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
+            j += 1
+        else:
+            break
+
+    # If not, apply deprecation to the named routine
+    if not has_fused:
+        d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
+
+
+# taken from scikit-learn, see
+# https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
+def _deprecate_positional_args(func=None, *, version=None,
+                               deprecated_args=None, custom_message=""):
+    """Decorator for methods that issues warnings for positional arguments.
+
+    Using the keyword-only argument syntax in pep 3102, arguments after the
+    * will issue a warning when passed as a positional argument.
+
+    Parameters
+    ----------
+    func : callable, default=None
+        Function to check arguments on.
+    version : callable, default=None
+        The version when positional arguments will result in error.
+    deprecated_args : set of str, optional
+        Arguments to deprecate - whether passed by position or keyword.
+    custom_message : str, optional
+        Custom message to add to deprecation warning and documentation.
+    """
+    if version is None:
+        msg = "Need to specify a version where signature will be changed"
+        raise ValueError(msg)
+
+    deprecated_args = set() if deprecated_args is None else set(deprecated_args)
+
+    def _inner_deprecate_positional_args(f):
+        sig = signature(f)
+        kwonly_args = []
+        all_args = []
+
+        for name, param in sig.parameters.items():
+            if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
+                all_args.append(name)
+            elif param.kind == Parameter.KEYWORD_ONLY:
+                kwonly_args.append(name)
+
+        def warn_deprecated_args(kwargs):
+            intersection = deprecated_args.intersection(kwargs)
+            if intersection:
+                message = (f"Arguments {intersection} are deprecated, whether passed "
+                           "by position or keyword. They will be removed in SciPy "
+                           f"{version}. ")
+                message += custom_message
+                warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+        @functools.wraps(f)
+        def inner_f(*args, **kwargs):
+
+            extra_args = len(args) - len(all_args)
+            if extra_args <= 0:
+                warn_deprecated_args(kwargs)
+                return f(*args, **kwargs)
+
+            # extra_args > 0
+            kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
+            args_msg = ", ".join(kwonly_extra_args)
+            warnings.warn(
+                (
+                    f"You are passing as positional arguments: {args_msg}. "
+                    "Please change your invocation to use keyword arguments. "
+                    f"From SciPy {version}, passing these as positional "
+                    "arguments will result in an error."
+                ),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            kwargs.update(zip(sig.parameters, args))
+            warn_deprecated_args(kwargs)
+            return f(**kwargs)
+
+        doc = FunctionDoc(inner_f)
+        kwonly_extra_args = set(kwonly_args) - deprecated_args
+        admonition = f"""
+.. deprecated:: {version}
+    Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in 
+    SciPy {version}, these will be keyword-only. """
+        if deprecated_args:
+            admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
+                           "passed by position or keyword; they will be removed in "
+                           f"SciPy {version}. ")
+        admonition += custom_message
+        doc['Extended Summary'] += [admonition]
+
+        doc = str(doc).split("\n", 1)[1]  # remove signature
+        inner_f.__doc__ = str(doc)
+
+        return inner_f
+
+    if func is not None:
+        return _inner_deprecate_positional_args(func)
+
+    return _inner_deprecate_positional_args
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/doccer.py b/venv/lib/python3.10/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..538b83c482caba1d4a8a2f64e1ad56da1862e286
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/doccer.py
@@ -0,0 +1,372 @@
+"""Utilities to allow inserting docstring fragments for common
+parameters into function and method docstrings."""
+
+from collections.abc import Callable, Iterable, Mapping
+from typing import Protocol, TypeVar
+import sys
+
+__all__ = [
+    "docformat",
+    "inherit_docstring_from",
+    "indentcount_lines",
+    "filldoc",
+    "unindent_dict",
+    "unindent_string",
+    "extend_notes_in_docstring",
+    "replace_notes_in_docstring",
+    "doc_replace",
+]
+
+_F = TypeVar("_F", bound=Callable[..., object])
+
+
+class Decorator(Protocol):
+    """A decorator of a function."""
+
+    def __call__(self, func: _F, /) -> _F: ...
+
+
+def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
+    """Fill a function docstring from variables in dictionary.
+
+    Adapt the indent of the inserted docs
+
+    Parameters
+    ----------
+    docstring : str
+        A docstring from a function, possibly with dict formatting strings.
+    docdict : dict[str, str], optional
+        A dictionary with keys that match the dict formatting strings
+        and values that are docstring fragments to be inserted. The
+        indentation of the inserted docstrings is set to match the
+        minimum indentation of the ``docstring`` by adding this
+        indentation to all lines of the inserted string, except the
+        first.
+
+    Returns
+    -------
+    docstring : str
+        string with requested ``docdict`` strings inserted.
+
+    Examples
+    --------
+    >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
+    ' Test string with inserted value'
+    >>> docstring = 'First line\\n    Second line\\n    %(value)s'
+    >>> inserted_string = "indented\\nstring"
+    >>> docdict = {'value': inserted_string}
+    >>> docformat(docstring, docdict)
+    'First line\\n    Second line\\n    indented\\n    string'
+    """
+    if not docstring:
+        return docstring
+    if docdict is None:
+        docdict = {}
+    if not docdict:
+        return docstring
+    lines = docstring.expandtabs().splitlines()
+    # Find the minimum indent of the main docstring, after first line
+    if len(lines) < 2:
+        icount = 0
+    else:
+        icount = indentcount_lines(lines[1:])
+    indent = " " * icount
+    # Insert this indent to dictionary docstrings
+    indented = {}
+    for name, dstr in docdict.items():
+        lines = dstr.expandtabs().splitlines()
+        try:
+            newlines = [lines[0]]
+            for line in lines[1:]:
+                newlines.append(indent + line)
+            indented[name] = "\n".join(newlines)
+        except IndexError:
+            indented[name] = dstr
+    return docstring % indented
+
+
+def inherit_docstring_from(cls: object) -> Decorator:
+    """This decorator modifies the decorated function's docstring by
+    replacing occurrences of '%(super)s' with the docstring of the
+    method of the same name from the class `cls`.
+
+    If the decorated method has no docstring, it is simply given the
+    docstring of `cls`s method.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces '%(super)s' in the
+        docstring of the decorated method.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+
+    Examples
+    --------
+    In the following, the docstring for Bar.func created using the
+    docstring of `Foo.func`.
+
+    >>> class Foo:
+    ...     def func(self):
+    ...         '''Do something useful.'''
+    ...         return
+    ...
+    >>> class Bar(Foo):
+    ...     @inherit_docstring_from(Foo)
+    ...     def func(self):
+    ...         '''%(super)s
+    ...         Do it fast.
+    ...         '''
+    ...         return
+    ...
+    >>> b = Bar()
+    >>> b.func.__doc__
+    'Do something useful.\n        Do it fast.\n        '
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        func_docstring = func.__doc__
+        if func_docstring is None:
+            func.__doc__ = cls_docstring
+        else:
+            new_docstring = func_docstring % dict(super=cls_docstring)
+            func.__doc__ = new_docstring
+        return func
+
+    return _doc
+
+
+def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It extends the 'Notes' section of that docstring to include
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        Additional notes to append to the 'Notes' section of the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It replaces the 'Notes' section of that docstring with
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        The notes to replace the existing 'Notes' section with.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        notes_header = "        Notes\n        -----\n"
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        start_of_notes = cls_docstring.find(notes_header)
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[: start_of_notes + len(notes_header)]
+            + notes
+            + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def indentcount_lines(lines: Iterable[str]) -> int:
+    """Minimum indent for all lines in line list
+
+    Parameters
+    ----------
+    lines : Iterable[str]
+        The lines to find the minimum indent of.
+
+    Returns
+    -------
+    indent : int
+        The minimum indent.
+
+
+    Examples
+    --------
+    >>> lines = [' one', '  two', '   three']
+    >>> indentcount_lines(lines)
+    1
+    >>> lines = []
+    >>> indentcount_lines(lines)
+    0
+    >>> lines = [' one']
+    >>> indentcount_lines(lines)
+    1
+    >>> indentcount_lines(['    '])
+    0
+    """
+    indentno = sys.maxsize
+    for line in lines:
+        stripped = line.lstrip()
+        if stripped:
+            indentno = min(indentno, len(line) - len(stripped))
+    if indentno == sys.maxsize:
+        return 0
+    return indentno
+
+
+def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
+    """Return docstring decorator using docdict variable dictionary.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary containing name, docstring fragment pairs.
+    unindent_params : bool, optional
+        If True, strip common indentation from all parameters in docdict.
+        Default is False.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that applies dictionary to its
+        argument's __doc__ attribute.
+    """
+    if unindent_params:
+        docdict = unindent_dict(docdict)
+
+    def decorate(func: _F) -> _F:
+        # __doc__ may be None for optimized Python (-OO)
+        doc = func.__doc__ or ""
+        func.__doc__ = docformat(doc, docdict)
+        return func
+
+    return decorate
+
+
+def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
+    """Unindent all strings in a docdict.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary with string values to unindent.
+
+    Returns
+    -------
+    docdict : dict[str, str]
+        The `docdict` dictionary but each of its string values are unindented.
+    """
+    can_dict: dict[str, str] = {}
+    for name, dstr in docdict.items():
+        can_dict[name] = unindent_string(dstr)
+    return can_dict
+
+
+def unindent_string(docstring: str) -> str:
+    """Set docstring to minimum indent for all lines, including first.
+
+    Parameters
+    ----------
+    docstring : str
+        The input docstring to unindent.
+
+    Returns
+    -------
+    docstring : str
+        The unindented docstring.
+
+    Examples
+    --------
+    >>> unindent_string(' two')
+    'two'
+    >>> unindent_string('  two\\n   three')
+    'two\\n three'
+    """
+    lines = docstring.expandtabs().splitlines()
+    icount = indentcount_lines(lines)
+    if icount == 0:
+        return docstring
+    return "\n".join([line[icount:] for line in lines])
+
+
+def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
+    """Decorator to take the docstring from obj, with oldval replaced by newval
+
+    Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
+
+    Parameters
+    ----------
+    obj : object
+        A class or object whose docstring will be used as the basis for the
+        replacement operation.
+    oldval : str
+        The string to search for in the docstring.
+    newval : str
+        The string to replace `oldval` with in the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        A decorator function that replaces occurrences of `oldval` with `newval`
+        in the docstring of the decorated function.
+    """
+    # __doc__ may be None for optimized Python (-OO)
+    doc = (obj.__doc__ or "").replace(oldval, newval)
+
+    def inner(func: _F) -> _F:
+        func.__doc__ = doc
+        return func
+
+    return inner
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8601000890aa60527e6ec7f43e36a66dc0cb5c2d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..623124a591cf06e6c59a786f2d5a867dbb980e11
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__gcutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__gcutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69ab7d5923abaeaa5349b26dfa7d9ae25da655ee
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__gcutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__pep440.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__pep440.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d924d19d3ac50e6e869cd869adf58134b6dc5e7f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__pep440.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__testutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__testutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86fff4b08c751029f6780926dca525efc22a2b6c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__testutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__threadsafety.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__threadsafety.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e92cae603753d2e7563a41a94911916beb53deb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__threadsafety.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__util.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aceef0383cdad407256d83dc9fe59115f1521dcd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__util.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_array_api.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_array_api.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1420b77282e463866360befe0622a18e5768f499
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_array_api.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30ec827f8cb99cf8271ed6bcf5d9079563d3cdb7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_ccallback.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_ccallback.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a84ea3e20b17c06d13c7513eae1714b45fc0506
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_ccallback.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_config.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_config.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ef8a025c428aaedbcd4528d695f363bcc34a0d2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_config.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_deprecation.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_deprecation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1e3760586b1076de497df43118c741775443d1e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_deprecation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_doccer.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_doccer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4045e9b9d831a76a8863ac1485103911fc577ad9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_doccer.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_import_cycles.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_import_cycles.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ad690ae55d21b2681a21aed1bc76b8cb36db9d4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_import_cycles.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_public_api.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_public_api.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ed770ce36cd21a5f0275d7ee8fea2b627f36347
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_public_api.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_scipy_version.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_scipy_version.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba32e948d19b4e0093df7961b8dae57c6fb5b6f5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_scipy_version.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_tmpdirs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_tmpdirs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27dc20affd592c6325ad080657de2995558b22fd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_tmpdirs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_warnings.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_warnings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bcbf5be0989f5ad3573e6a0afc6fba4705796878
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_warnings.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e397af4fb7e9bc69f31d1e39aa80716469d5470
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py
@@ -0,0 +1,110 @@
+""" Test for assert_deallocated context manager and gc utilities
+"""
+import gc
+from threading import Lock
+
+from scipy._lib._gcutils import (set_gc_state, gc_state, assert_deallocated,
+                                 ReferenceError, IS_PYPY)
+
+from numpy.testing import assert_equal
+
+import pytest
+
+
+@pytest.fixture
+def gc_lock():
+    return Lock()
+
+
+def test_set_gc_state(gc_lock):
+    with gc_lock:
+        gc_status = gc.isenabled()
+        try:
+            for state in (True, False):
+                gc.enable()
+                set_gc_state(state)
+                assert_equal(gc.isenabled(), state)
+                gc.disable()
+                set_gc_state(state)
+                assert_equal(gc.isenabled(), state)
+        finally:
+            if gc_status:
+                gc.enable()
+
+
+def test_gc_state(gc_lock):
+    # Test gc_state context manager
+    with gc_lock:
+        gc_status = gc.isenabled()
+        try:
+            for pre_state in (True, False):
+                set_gc_state(pre_state)
+                for with_state in (True, False):
+                    # Check the gc state is with_state in with block
+                    with gc_state(with_state):
+                        assert_equal(gc.isenabled(), with_state)
+                    # And returns to previous state outside block
+                    assert_equal(gc.isenabled(), pre_state)
+                    # Even if the gc state is set explicitly within the block
+                    with gc_state(with_state):
+                        assert_equal(gc.isenabled(), with_state)
+                        set_gc_state(not with_state)
+                    assert_equal(gc.isenabled(), pre_state)
+        finally:
+            if gc_status:
+                gc.enable()
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated(gc_lock):
+    # Ordinary use
+    class C:
+        def __init__(self, arg0, arg1, name='myname'):
+            self.name = name
+    with gc_lock:
+        for gc_current in (True, False):
+            with gc_state(gc_current):
+                # We are deleting from with-block context, so that's OK
+                with assert_deallocated(C, 0, 2, 'another name') as c:
+                    assert_equal(c.name, 'another name')
+                    del c
+                # Or not using the thing in with-block context, also OK
+                with assert_deallocated(C, 0, 2, name='third name'):
+                    pass
+                assert_equal(gc.isenabled(), gc_current)
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated_nodel():
+    class C:
+        pass
+    with pytest.raises(ReferenceError):
+        # Need to delete after using if in with-block context
+        # Note: assert_deallocated(C) needs to be assigned for the test
+        # to function correctly.  It is assigned to _, but _ itself is
+        # not referenced in the body of the with, it is only there for
+        # the refcount.
+        with assert_deallocated(C) as _:
+            pass
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated_circular():
+    class C:
+        def __init__(self):
+            self._circular = self
+    with pytest.raises(ReferenceError):
+        # Circular reference, no automatic garbage collection
+        with assert_deallocated(C) as c:
+            del c
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated_circular2():
+    class C:
+        def __init__(self):
+            self._circular = self
+    with pytest.raises(ReferenceError):
+        # Still circular reference, no automatic garbage collection
+        with assert_deallocated(C):
+            pass
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5b71c8f1e13b42de2e8e612a005dec409fc025
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py
@@ -0,0 +1,67 @@
+from pytest import raises as assert_raises
+from scipy._lib._pep440 import Version, parse
+
+
+def test_main_versions():
+    assert Version('1.8.0') == Version('1.8.0')
+    for ver in ['1.9.0', '2.0.0', '1.8.1']:
+        assert Version('1.8.0') < Version(ver)
+
+    for ver in ['1.7.0', '1.7.1', '0.9.9']:
+        assert Version('1.8.0') > Version(ver)
+
+
+def test_version_1_point_10():
+    # regression test for gh-2998.
+    assert Version('1.9.0') < Version('1.10.0')
+    assert Version('1.11.0') < Version('1.11.1')
+    assert Version('1.11.0') == Version('1.11.0')
+    assert Version('1.99.11') < Version('1.99.12')
+
+
+def test_alpha_beta_rc():
+    assert Version('1.8.0rc1') == Version('1.8.0rc1')
+    for ver in ['1.8.0', '1.8.0rc2']:
+        assert Version('1.8.0rc1') < Version(ver)
+
+    for ver in ['1.8.0a2', '1.8.0b3', '1.7.2rc4']:
+        assert Version('1.8.0rc1') > Version(ver)
+
+    assert Version('1.8.0b1') > Version('1.8.0a2')
+
+
+def test_dev_version():
+    assert Version('1.9.0.dev+Unknown') < Version('1.9.0')
+    for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev+ffffffff', '1.9.0.dev1']:
+        assert Version('1.9.0.dev+f16acvda') < Version(ver)
+
+    assert Version('1.9.0.dev+f16acvda') == Version('1.9.0.dev+f16acvda')
+
+
+def test_dev_a_b_rc_mixed():
+    assert Version('1.9.0a2.dev+f16acvda') == Version('1.9.0a2.dev+f16acvda')
+    assert Version('1.9.0a2.dev+6acvda54') < Version('1.9.0a2')
+
+
+def test_dev0_version():
+    assert Version('1.9.0.dev0+Unknown') < Version('1.9.0')
+    for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev0+ffffffff']:
+        assert Version('1.9.0.dev0+f16acvda') < Version(ver)
+
+    assert Version('1.9.0.dev0+f16acvda') == Version('1.9.0.dev0+f16acvda')
+
+
+def test_dev0_a_b_rc_mixed():
+    assert Version('1.9.0a2.dev0+f16acvda') == Version('1.9.0a2.dev0+f16acvda')
+    assert Version('1.9.0a2.dev0+6acvda54') < Version('1.9.0a2')
+
+
+def test_raises():
+    for ver in ['1,9.0', '1.7.x']:
+        assert_raises(ValueError, Version, ver)
+
+def test_legacy_version():
+    # Non-PEP-440 version identifiers always compare less. For NumPy this only
+    # occurs on dev builds prior to 1.10.0 which are unsupported anyway.
+    assert parse('invalid') < Version('0.0.0')
+    assert parse('1.9.0-f16acvda') < Version('1.0.0')
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..88db113d6d5a35c96ecc0a6a36ab42d74be49153
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py
@@ -0,0 +1,32 @@
+import sys
+from scipy._lib._testutils import _parse_size, _get_mem_available
+import pytest
+
+
+def test__parse_size():
+    expected = {
+        '12': 12e6,
+        '12 b': 12,
+        '12k': 12e3,
+        '  12  M  ': 12e6,
+        '  12  G  ': 12e9,
+        ' 12Tb ': 12e12,
+        '12  Mib ': 12 * 1024.0**2,
+        '12Tib': 12 * 1024.0**4,
+    }
+
+    for inp, outp in sorted(expected.items()):
+        if outp is None:
+            with pytest.raises(ValueError):
+                _parse_size(inp)
+        else:
+            assert _parse_size(inp) == outp
+
+
+def test__mem_available():
+    # May return None on non-Linux platforms
+    available = _get_mem_available()
+    if sys.platform.startswith('linux'):
+        assert available >= 0
+    else:
+        assert available is None or available >= 0
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ae85ef318da2b8bb104c4a87faa4e4021c01d5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py
@@ -0,0 +1,51 @@
+import threading
+import time
+import traceback
+
+from numpy.testing import assert_
+from pytest import raises as assert_raises
+
+from scipy._lib._threadsafety import ReentrancyLock, non_reentrant, ReentrancyError
+
+
+def test_parallel_threads():
+    # Check that ReentrancyLock serializes work in parallel threads.
+    #
+    # The test is not fully deterministic, and may succeed falsely if
+    # the timings go wrong.
+
+    lock = ReentrancyLock("failure")
+
+    failflag = [False]
+    exceptions_raised = []
+
+    def worker(k):
+        try:
+            with lock:
+                assert_(not failflag[0])
+                failflag[0] = True
+                time.sleep(0.1 * k)
+                assert_(failflag[0])
+                failflag[0] = False
+        except Exception:
+            exceptions_raised.append(traceback.format_exc(2))
+
+    threads = [threading.Thread(target=lambda k=k: worker(k))
+               for k in range(3)]
+    for t in threads:
+        t.start()
+    for t in threads:
+        t.join()
+
+    exceptions_raised = "\n".join(exceptions_raised)
+    assert_(not exceptions_raised, exceptions_raised)
+
+
+def test_reentering():
+    # Check that ReentrancyLock prevents re-entering from the same thread.
+
+    @non_reentrant()
+    def func(x):
+        return func(x)
+
+    assert_raises(ReentrancyError, func, 0)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4d22ce468ec951355961cb77dda15b56899818
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py
@@ -0,0 +1,657 @@
+from multiprocessing import Pool
+from multiprocessing.pool import Pool as PWL
+import re
+import math
+from fractions import Fraction
+
+import numpy as np
+from numpy.testing import assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+import hypothesis.extra.numpy as npst
+from hypothesis import given, strategies, reproduce_failure  # noqa: F401
+from scipy.conftest import array_api_compatible, skip_xp_invalid_arg
+
+from scipy._lib._array_api import (xp_assert_equal, xp_assert_close, is_numpy,
+                                   xp_copy, is_array_api_strict)
+from scipy._lib._util import (_aligned_zeros, check_random_state, MapWrapper,
+                              getfullargspec_no_self, FullArgSpec,
+                              rng_integers, _validate_int, _rename_parameter,
+                              _contains_nan, _rng_html_rewrite, _lazywhere)
+from scipy import cluster, interpolate, linalg, optimize, sparse, spatial, stats
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@pytest.mark.slow
+def test__aligned_zeros():
+    niter = 10
+
+    def check(shape, dtype, order, align):
+        err_msg = repr((shape, dtype, order, align))
+        x = _aligned_zeros(shape, dtype, order, align=align)
+        if align is None:
+            align = np.dtype(dtype).alignment
+        assert_equal(x.__array_interface__['data'][0] % align, 0)
+        if hasattr(shape, '__len__'):
+            assert_equal(x.shape, shape, err_msg)
+        else:
+            assert_equal(x.shape, (shape,), err_msg)
+        assert_equal(x.dtype, dtype)
+        if order == "C":
+            assert_(x.flags.c_contiguous, err_msg)
+        elif order == "F":
+            if x.size > 0:
+                # Size-0 arrays get invalid flags on NumPy 1.5
+                assert_(x.flags.f_contiguous, err_msg)
+        elif order is None:
+            assert_(x.flags.c_contiguous, err_msg)
+        else:
+            raise ValueError()
+
+    # try various alignments
+    for align in [1, 2, 3, 4, 8, 16, 32, 64, None]:
+        for n in [0, 1, 3, 11]:
+            for order in ["C", "F", None]:
+                for dtype in [np.uint8, np.float64]:
+                    for shape in [n, (1, 2, 3, n)]:
+                        for j in range(niter):
+                            check(shape, dtype, order, align)
+
+
+def test_check_random_state():
+    # If seed is None, return the RandomState singleton used by np.random.
+    # If seed is an int, return a new RandomState instance seeded with seed.
+    # If seed is already a RandomState instance, return it.
+    # Otherwise raise ValueError.
+    rsi = check_random_state(1)
+    assert_equal(type(rsi), np.random.RandomState)
+    rsi = check_random_state(rsi)
+    assert_equal(type(rsi), np.random.RandomState)
+    rsi = check_random_state(None)
+    assert_equal(type(rsi), np.random.RandomState)
+    assert_raises(ValueError, check_random_state, 'a')
+    rg = np.random.Generator(np.random.PCG64())
+    rsi = check_random_state(rg)
+    assert_equal(type(rsi), np.random.Generator)
+
+
+def test_getfullargspec_no_self():
+    p = MapWrapper(1)
+    argspec = getfullargspec_no_self(p.__init__)
+    assert_equal(argspec, FullArgSpec(['pool'], None, None, (1,), [],
+                                      None, {}))
+    argspec = getfullargspec_no_self(p.__call__)
+    assert_equal(argspec, FullArgSpec(['func', 'iterable'], None, None, None,
+                                      [], None, {}))
+
+    class _rv_generic:
+        def _rvs(self, a, b=2, c=3, *args, size=None, **kwargs):
+            return None
+
+    rv_obj = _rv_generic()
+    argspec = getfullargspec_no_self(rv_obj._rvs)
+    assert_equal(argspec, FullArgSpec(['a', 'b', 'c'], 'args', 'kwargs',
+                                      (2, 3), ['size'], {'size': None}, {}))
+
+
+def test_mapwrapper_serial():
+    in_arg = np.arange(10.)
+    out_arg = np.sin(in_arg)
+
+    p = MapWrapper(1)
+    assert_(p._mapfunc is map)
+    assert_(p.pool is None)
+    assert_(p._own_pool is False)
+    out = list(p(np.sin, in_arg))
+    assert_equal(out, out_arg)
+
+    with assert_raises(RuntimeError):
+        p = MapWrapper(0)
+
+
+def test_pool():
+    with Pool(2) as p:
+        p.map(math.sin, [1, 2, 3, 4])
+
+
+def test_mapwrapper_parallel():
+    in_arg = np.arange(10.)
+    out_arg = np.sin(in_arg)
+
+    with MapWrapper(2) as p:
+        out = p(np.sin, in_arg)
+        assert_equal(list(out), out_arg)
+
+        assert_(p._own_pool is True)
+        assert_(isinstance(p.pool, PWL))
+        assert_(p._mapfunc is not None)
+
+    # the context manager should've closed the internal pool
+    # check that it has by asking it to calculate again.
+    with assert_raises(Exception) as excinfo:
+        p(np.sin, in_arg)
+
+    assert_(excinfo.type is ValueError)
+
+    # can also set a PoolWrapper up with a map-like callable instance
+    with Pool(2) as p:
+        q = MapWrapper(p.map)
+
+        assert_(q._own_pool is False)
+        q.close()
+
+        # closing the PoolWrapper shouldn't close the internal pool
+        # because it didn't create it
+        out = p.map(np.sin, in_arg)
+        assert_equal(list(out), out_arg)
+
+
+def test_rng_integers():
+    rng = np.random.RandomState()
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # now try with np.random.Generator
+    try:
+        rng = np.random.default_rng()
+    except AttributeError:
+        return
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+
+class TestValidateInt:
+
+    @pytest.mark.parametrize('n', [4, np.uint8(4), np.int16(4), np.array(4)])
+    def test_validate_int(self, n):
+        n = _validate_int(n, 'n')
+        assert n == 4
+
+    @pytest.mark.parametrize('n', [4.0, np.array([4]), Fraction(4, 1)])
+    def test_validate_int_bad(self, n):
+        with pytest.raises(TypeError, match='n must be an integer'):
+            _validate_int(n, 'n')
+
+    def test_validate_int_below_min(self):
+        with pytest.raises(ValueError, match='n must be an integer not '
+                                             'less than 0'):
+            _validate_int(-1, 'n', 0)
+
+
+class TestRenameParameter:
+    # check that wrapper `_rename_parameter` for backward-compatible
+    # keyword renaming works correctly
+
+    # Example method/function that still accepts keyword `old`
+    @_rename_parameter("old", "new")
+    def old_keyword_still_accepted(self, new):
+        return new
+
+    # Example method/function for which keyword `old` is deprecated
+    @_rename_parameter("old", "new", dep_version="1.9.0")
+    def old_keyword_deprecated(self, new):
+        return new
+
+    def test_old_keyword_still_accepted(self):
+        # positional argument and both keyword work identically
+        res1 = self.old_keyword_still_accepted(10)
+        res2 = self.old_keyword_still_accepted(new=10)
+        res3 = self.old_keyword_still_accepted(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_still_accepted() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(unexpected=10)
+
+        # multiple values for the same parameter raises an error
+        message = re.escape("old_keyword_still_accepted() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, new=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, old=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(new=10, old=10)
+
+    @pytest.fixture
+    def kwarg_lock(self):
+        from threading import Lock
+        return Lock()
+
+    def test_old_keyword_deprecated(self, kwarg_lock):
+        # positional argument and both keyword work identically,
+        # but use of old keyword results in DeprecationWarning
+        dep_msg = "Use of keyword argument `old` is deprecated"
+        res1 = self.old_keyword_deprecated(10)
+        res2 = self.old_keyword_deprecated(new=10)
+        # pytest warning filter is not thread-safe, enforce serialization
+        with kwarg_lock:
+            with pytest.warns(DeprecationWarning, match=dep_msg):
+                    res3 = self.old_keyword_deprecated(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_deprecated() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(unexpected=10)
+
+        # multiple values for the same parameter raises an error and,
+        # if old keyword is used, results in DeprecationWarning
+        message = re.escape("old_keyword_deprecated() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(10, new=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    # breakpoint()
+                    self.old_keyword_deprecated(10, old=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    self.old_keyword_deprecated(new=10, old=10)
+
+
+class TestContainsNaNTest:
+
+    def test_policy(self):
+        data = np.array([1, 2, 3, np.nan])
+
+        contains_nan, nan_policy = _contains_nan(data, nan_policy="propagate")
+        assert contains_nan
+        assert nan_policy == "propagate"
+
+        contains_nan, nan_policy = _contains_nan(data, nan_policy="omit")
+        assert contains_nan
+        assert nan_policy == "omit"
+
+        msg = "The input contains nan values"
+        with pytest.raises(ValueError, match=msg):
+            _contains_nan(data, nan_policy="raise")
+
+        msg = "nan_policy must be one of"
+        with pytest.raises(ValueError, match=msg):
+            _contains_nan(data, nan_policy="nan")
+
+    def test_contains_nan(self):
+        data1 = np.array([1, 2, 3])
+        assert not _contains_nan(data1)[0]
+
+        data2 = np.array([1, 2, 3, np.nan])
+        assert _contains_nan(data2)[0]
+
+        data3 = np.array([np.nan, 2, 3, np.nan])
+        assert _contains_nan(data3)[0]
+
+        data4 = np.array([[1, 2], [3, 4]])
+        assert not _contains_nan(data4)[0]
+
+        data5 = np.array([[1, 2], [3, np.nan]])
+        assert _contains_nan(data5)[0]
+
+    @skip_xp_invalid_arg
+    def test_contains_nan_with_strings(self):
+        data1 = np.array([1, 2, "3", np.nan])  # converted to string "nan"
+        assert not _contains_nan(data1)[0]
+
+        data2 = np.array([1, 2, "3", np.nan], dtype='object')
+        assert _contains_nan(data2)[0]
+
+        data3 = np.array([["1", 2], [3, np.nan]])  # converted to string "nan"
+        assert not _contains_nan(data3)[0]
+
+        data4 = np.array([["1", 2], [3, np.nan]], dtype='object')
+        assert _contains_nan(data4)[0]
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit', 'raise'])
+    def test_array_api(self, xp, nan_policy):
+        rng = np.random.default_rng(932347235892482)
+        x0 = rng.random(size=(2, 3, 4))
+        x = xp.asarray(x0)
+        x_nan = xp_copy(x, xp=xp)
+        x_nan[1, 2, 1] = np.nan
+
+        contains_nan, nan_policy_out = _contains_nan(x, nan_policy=nan_policy)
+        assert not contains_nan
+        assert nan_policy_out == nan_policy
+
+        if nan_policy == 'raise':
+            message = 'The input contains...'
+            with pytest.raises(ValueError, match=message):
+                _contains_nan(x_nan, nan_policy=nan_policy)
+        elif nan_policy == 'omit' and not is_numpy(xp):
+            message = "`nan_policy='omit' is incompatible..."
+            with pytest.raises(ValueError, match=message):
+                _contains_nan(x_nan, nan_policy=nan_policy)
+        elif nan_policy == 'propagate':
+            contains_nan, nan_policy_out = _contains_nan(
+                x_nan, nan_policy=nan_policy)
+            assert contains_nan
+            assert nan_policy_out == nan_policy
+
+
+def test__rng_html_rewrite():
+    def mock_str():
+        lines = [
+            'np.random.default_rng(8989843)',
+            'np.random.default_rng(seed)',
+            'np.random.default_rng(0x9a71b21474694f919882289dc1559ca)',
+            ' bob ',
+        ]
+        return lines
+
+    res = _rng_html_rewrite(mock_str)()
+    ref = [
+        'np.random.default_rng()',
+        'np.random.default_rng(seed)',
+        'np.random.default_rng()',
+        ' bob ',
+    ]
+
+    assert res == ref
+
+
+class TestTransitionToRNG:
+    def kmeans(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def kmeans2(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def barycentric(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x1, x2, y1 = rng.random((3, 10))
+        f = interpolate.BarycentricInterpolator(x1, y1, **kwargs)
+        return f(x2)
+
+    def clarkson_woodruff_transform(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return linalg.clarkson_woodruff_transform(rng.random((10, 10)), 3, **kwargs)
+
+    def basinhopping(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return optimize.basinhopping(optimize.rosen, rng.random(3), **kwargs).x
+
+    def opt(self, fun, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        bounds = optimize.Bounds(-rng.random(3) * 10, rng.random(3) * 10)
+        return fun(optimize.rosen, bounds, **kwargs).x
+
+    def differential_evolution(self, **kwargs):
+        return self.opt(optimize.differential_evolution, **kwargs)
+
+    def dual_annealing(self, **kwargs):
+        return self.opt(optimize.dual_annealing, **kwargs)
+
+    def check_grad(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x = rng.random(3)
+        return optimize.check_grad(optimize.rosen, optimize.rosen_der, x,
+                                   direction='random', **kwargs)
+
+    def random_array(self, **kwargs):
+        return sparse.random_array((10, 10), density=1.0, **kwargs).toarray()
+
+    def random(self, **kwargs):
+        return sparse.random(10, 10, density=1.0, **kwargs).toarray()
+
+    def rand(self, **kwargs):
+        return sparse.rand(10, 10, density=1.0, **kwargs).toarray()
+
+    def svds(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        A = rng.random((10, 10))
+        return sparse.linalg.svds(A, **kwargs)
+
+    def random_rotation(self, **kwargs):
+        return spatial.transform.Rotation.random(3, **kwargs).as_matrix()
+
+    def goodness_of_fit(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = rng.random(100)
+        return stats.goodness_of_fit(stats.laplace, data, **kwargs).pvalue
+
+    def permutation_test(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        def statistic(x, y, axis): return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+        return stats.permutation_test(data, statistic, **kwargs).pvalue
+
+    def bootstrap(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = (rng.random(100),)
+        return stats.bootstrap(data, np.mean, **kwargs).confidence_interval
+
+    def dunnett(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x, y, control = rng.random((3, 100))
+        return stats.dunnett(x, y, control=control, **kwargs).pvalue
+
+    def sobol_indices(self, **kwargs):
+        def f_ishigami(x): return (np.sin(x[0]) + 7 * np.sin(x[1]) ** 2
+                                   + 0.1 * (x[2] ** 4) * np.sin(x[0]))
+        dists = [stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi)]
+        res = stats.sobol_indices(func=f_ishigami, n=1024, dists=dists, **kwargs)
+        return res.first_order
+
+    def qmc_engine(self, engine, **kwargs):
+        qrng = engine(d=1, **kwargs)
+        return qrng.random(4)
+
+    def halton(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Halton, **kwargs)
+
+    def sobol(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Sobol, **kwargs)
+
+    def latin_hypercube(self, **kwargs):
+        return self.qmc_engine(stats.qmc.LatinHypercube, **kwargs)
+
+    def poisson_disk(self, **kwargs):
+        return self.qmc_engine(stats.qmc.PoissonDisk, **kwargs)
+
+    def multivariate_normal_qmc(self, **kwargs):
+        X = stats.qmc.MultivariateNormalQMC([0], **kwargs)
+        return X.random(4)
+
+    def multinomial_qmc(self, **kwargs):
+        X = stats.qmc.MultinomialQMC([0.5, 0.5], 4, **kwargs)
+        return X.random(4)
+
+    def permutation_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        method = stats.PermutationMethod(**kwargs)
+        return stats.pearsonr(*data, method=method).pvalue
+
+    def bootstrap_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        res = stats.pearsonr(*data)
+        method = stats.BootstrapMethod(**kwargs)
+        return res.confidence_interval(method=method)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow
+    @pytest.mark.parametrize("method, arg_name", [
+        (kmeans, "seed"),
+        (kmeans2, "seed"),
+        (barycentric, "random_state"),
+        (clarkson_woodruff_transform, "seed"),
+        (basinhopping, "seed"),
+        (differential_evolution, "seed"),
+        (dual_annealing, "seed"),
+        (check_grad, "seed"),
+        (random_array, 'random_state'),
+        (random, 'random_state'),
+        (rand, 'random_state'),
+        (svds, "random_state"),
+        (random_rotation, "random_state"),
+        (goodness_of_fit, "random_state"),
+        (permutation_test, "random_state"),
+        (bootstrap, "random_state"),
+        (permutation_method, "random_state"),
+        (bootstrap_method, "random_state"),
+        (dunnett, "random_state"),
+        (sobol_indices, "random_state"),
+        (halton, "seed"),
+        (sobol, "seed"),
+        (latin_hypercube, "seed"),
+        (poisson_disk, "seed"),
+        (multivariate_normal_qmc, "seed"),
+        (multinomial_qmc, "seed"),
+    ])
+    def test_rng_deterministic(self, method, arg_name):
+        np.random.seed(None)
+        seed = 2949672964
+
+        rng = np.random.default_rng(seed)
+        message = "got multiple values for argument now known as `rng`"
+        with pytest.raises(TypeError, match=message):
+            method(self, **{'rng': rng, arg_name: seed})
+
+        rng = np.random.default_rng(seed)
+        res1 = method(self, rng=rng)
+        res2 = method(self, rng=seed)
+        assert_equal(res2, res1)
+
+        if method.__name__ in {"dunnett", "sobol_indices"}:
+            # the two kwargs have essentially the same behavior for these functions
+            res3 = method(self, **{arg_name: seed})
+            assert_equal(res3, res1)
+            return
+
+        rng = np.random.RandomState(seed)
+        res1 = method(self, **{arg_name: rng})
+        res2 = method(self, **{arg_name: seed})
+
+        if method.__name__ in {"halton", "sobol", "latin_hypercube", "poisson_disk",
+                               "multivariate_normal_qmc", "multinomial_qmc"}:
+            # For these, passing `random_state=RandomState(seed)` is not the same as
+            # passing integer `seed`.
+            res1b = method(self, **{arg_name: np.random.RandomState(seed)})
+            assert_equal(res1b, res1)
+            res2b = method(self, **{arg_name: seed})
+            assert_equal(res2b, res2)
+            return
+
+        np.random.seed(seed)
+        res3 = method(self, **{arg_name: None})
+        assert_equal(res2, res1)
+        assert_equal(res3, res1)
+
+
+class TestLazywhere:
+    n_arrays = strategies.integers(min_value=1, max_value=3)
+    rng_seed = strategies.integers(min_value=1000000000, max_value=9999999999)
+    dtype = strategies.sampled_from((np.float32, np.float64))
+    p = strategies.floats(min_value=0, max_value=1)
+    data = strategies.data()
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.filterwarnings('ignore::RuntimeWarning')  # overflows, etc.
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @given(n_arrays=n_arrays, rng_seed=rng_seed, dtype=dtype, p=p, data=data)
+    @pytest.mark.thread_unsafe
+    def test_basic(self, n_arrays, rng_seed, dtype, p, data, xp):
+        mbs = npst.mutually_broadcastable_shapes(num_shapes=n_arrays+1,
+                                                 min_side=0)
+        input_shapes, result_shape = data.draw(mbs)
+        cond_shape, *shapes = input_shapes
+        elements = {'allow_subnormal': False}  # cupy/cupy#8382
+        fillvalue = xp.asarray(data.draw(npst.arrays(dtype=dtype, shape=tuple(),
+                                                     elements=elements)))
+        float_fillvalue = float(fillvalue)
+        arrays = [xp.asarray(data.draw(npst.arrays(dtype=dtype, shape=shape)))
+                  for shape in shapes]
+
+        def f(*args):
+            return sum(arg for arg in args)
+
+        def f2(*args):
+            return sum(arg for arg in args) / 2
+
+        rng = np.random.default_rng(rng_seed)
+        cond = xp.asarray(rng.random(size=cond_shape) > p)
+
+        res1 = _lazywhere(cond, arrays, f, fillvalue)
+        res2 = _lazywhere(cond, arrays, f, f2=f2)
+        if not is_array_api_strict(xp):
+            res3 = _lazywhere(cond, arrays, f, float_fillvalue)
+
+        # Ensure arrays are at least 1d to follow sane type promotion rules.
+        # This can be removed when minimum supported NumPy is 2.0
+        if xp == np:
+            cond, fillvalue, *arrays = np.atleast_1d(cond, fillvalue, *arrays)
+
+        ref1 = xp.where(cond, f(*arrays), fillvalue)
+        ref2 = xp.where(cond, f(*arrays), f2(*arrays))
+        if not is_array_api_strict(xp):
+            # Array API standard doesn't currently define behavior when fillvalue is a
+            # Python scalar. When it does, test can be run with array_api_strict, too.
+            ref3 = xp.where(cond, f(*arrays), float_fillvalue)
+
+        if xp == np:  # because we ensured arrays are at least 1d
+            ref1 = ref1.reshape(result_shape)
+            ref2 = ref2.reshape(result_shape)
+            ref3 = ref3.reshape(result_shape)
+
+        xp_assert_close(res1, ref1, rtol=2e-16)
+        xp_assert_equal(res2, ref2)
+        if not is_array_api_strict(xp):
+            xp_assert_equal(res3, ref3)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..f425eb4327fe042a3cf8eb79cf3402f23b526ae7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py
@@ -0,0 +1,191 @@
+import numpy as np
+import pytest
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    _GLOBAL_CONFIG, array_namespace, _asarray, xp_copy, xp_assert_equal, is_numpy,
+    np_compat, xp_default_dtype
+)
+from scipy._lib._array_api_no_0d import xp_assert_equal as xp_assert_equal_no_0d
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@pytest.mark.skipif(not _GLOBAL_CONFIG["SCIPY_ARRAY_API"],
+        reason="Array API test; set environment variable SCIPY_ARRAY_API=1 to run it")
+class TestArrayAPI:
+
+    def test_array_namespace(self):
+        x, y = np.array([0, 1, 2]), np.array([0, 1, 2])
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+
+        _GLOBAL_CONFIG["SCIPY_ARRAY_API"] = False
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+        _GLOBAL_CONFIG["SCIPY_ARRAY_API"] = True
+
+    @array_api_compatible
+    def test_asarray(self, xp):
+        x, y = _asarray([0, 1, 2], xp=xp), _asarray(np.arange(3), xp=xp)
+        ref = xp.asarray([0, 1, 2])
+        xp_assert_equal(x, ref)
+        xp_assert_equal(y, ref)
+
+    @pytest.mark.filterwarnings("ignore: the matrix subclass")
+    def test_raises(self):
+        msg = "of type `numpy.ma.MaskedArray` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.ma.array(1), np.array(1))
+
+        msg = "of type `numpy.matrix` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.array(1), np.matrix(1))
+
+        msg = "only boolean and numerical dtypes are supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace([object()])
+        with pytest.raises(TypeError, match=msg):
+            array_namespace('abc')
+
+    def test_array_likes(self):
+        # should be no exceptions
+        array_namespace([0, 1, 2])
+        array_namespace(1, 2, 3)
+        array_namespace(1)
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_copy(self, xp):
+        for _xp in [xp, None]:
+            x = xp.asarray([1, 2, 3])
+            y = xp_copy(x, xp=_xp)
+            # with numpy we'd want to use np.shared_memory, but that's not specified
+            # in the array-api
+            x[0] = 10
+            x[1] = 11
+            x[2] = 12
+
+            assert x[0] != y[0]
+            assert x[1] != y[1]
+            assert x[2] != y[2]
+            assert id(x) != id(y)
+
+    @array_api_compatible
+    @pytest.mark.parametrize('dtype', ['int32', 'int64', 'float32', 'float64'])
+    @pytest.mark.parametrize('shape', [(), (3,)])
+    def test_strict_checks(self, xp, dtype, shape):
+        # Check that `_strict_check` behaves as expected
+        dtype = getattr(xp, dtype)
+        x = xp.broadcast_to(xp.asarray(1, dtype=dtype), shape)
+        x = x if shape else x[()]
+        y = np_compat.asarray(1)[()]
+
+        kwarg_names = ["check_namespace", "check_dtype", "check_shape", "check_0d"]
+        options = dict(zip(kwarg_names, [True, False, False, False]))
+        if xp == np:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Namespaces do not match."):
+                xp_assert_equal(x, y, **options)
+
+        options = dict(zip(kwarg_names, [False, True, False, False]))
+        if y.dtype.name in str(x.dtype):
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="dtypes do not match."):
+                xp_assert_equal(x, y, **options)
+
+        options = dict(zip(kwarg_names, [False, False, True, False]))
+        if x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Shapes do not match."):
+                xp_assert_equal(x, xp.asarray(y), **options)
+
+        options = dict(zip(kwarg_names, [False, False, False, True]))
+        if is_numpy(xp) and x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        elif is_numpy(xp):
+            with pytest.raises(AssertionError, match="Array-ness does not match."):
+                xp_assert_equal(x, y, **options)
+
+
+    @array_api_compatible
+    def test_check_scalar(self, xp):
+        if not is_numpy(xp):
+            pytest.skip("Scalars only exist in NumPy")
+
+        # identity always passes
+        xp_assert_equal(xp.float64(0), xp.float64(0))
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.))
+        xp_assert_equal(xp.float64(0), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.), check_0d=False)
+
+        # Check default convention: 0d-arrays are distinguished from scalars
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.float64(0), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(42), xp.int64(42))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.int64(42), xp.asarray(42))
+
+        # with `check_0d=False`, scalars-vs-0d passes (if values match)
+        xp_assert_equal(xp.asarray(0.), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.float64(0), xp.asarray(0.), check_0d=False)
+        # also with regular python objects
+        xp_assert_equal(xp.asarray(0.), 0., check_0d=False)
+        xp_assert_equal(0., xp.asarray(0.), check_0d=False)
+        xp_assert_equal(xp.asarray(42), 42, check_0d=False)
+        xp_assert_equal(42, xp.asarray(42), check_0d=False)
+
+        # as an alternative to `check_0d=False`, explicitly expect scalar
+        xp_assert_equal(xp.float64(0), xp.asarray(0.)[()])
+
+
+    @array_api_compatible
+    def test_check_scalar_no_0d(self, xp):
+        if not is_numpy(xp):
+            pytest.skip("Scalars only exist in NumPy")
+
+        # identity passes, if first argument is not 0d (or check_0d=True)
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0))
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0), check_0d=True)
+        xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.), check_0d=True)
+
+        # by default, 0d values are forbidden as the first argument
+        message = "Result is a NumPy 0d-array.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(42))
+
+        # Check default convention: 0d-arrays are NOT distinguished from scalars
+        xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.))
+        xp_assert_equal_no_0d(xp.int64(42), xp.asarray(42))
+
+        # opt in to 0d-check remains possible
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.int64(0), xp.asarray(42), check_0d=True)
+
+        # scalars-vs-0d passes (if values match) also with regular python objects
+        xp_assert_equal_no_0d(0., xp.asarray(0.))
+        xp_assert_equal_no_0d(42, xp.asarray(42))
+
+    @array_api_compatible
+    def test_default_dtype(self, xp):
+        assert xp_default_dtype(xp) == xp.asarray(1.).dtype
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f19ca377129b925cad732dd25bf3089c646f923f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py
@@ -0,0 +1,162 @@
+import pytest
+import pickle
+from numpy.testing import assert_equal
+from scipy._lib._bunch import _make_tuple_bunch
+
+
+# `Result` is defined at the top level of the module so it can be
+# used to test pickling.
+Result = _make_tuple_bunch('Result', ['x', 'y', 'z'], ['w', 'beta'])
+
+
+class TestMakeTupleBunch:
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Tests with Result
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def setup_method(self):
+        # Set up an instance of Result.
+        self.result = Result(x=1, y=2, z=3, w=99, beta=0.5)
+
+    def test_attribute_access(self):
+        assert_equal(self.result.x, 1)
+        assert_equal(self.result.y, 2)
+        assert_equal(self.result.z, 3)
+        assert_equal(self.result.w, 99)
+        assert_equal(self.result.beta, 0.5)
+
+    def test_indexing(self):
+        assert_equal(self.result[0], 1)
+        assert_equal(self.result[1], 2)
+        assert_equal(self.result[2], 3)
+        assert_equal(self.result[-1], 3)
+        with pytest.raises(IndexError, match='index out of range'):
+            self.result[3]
+
+    def test_unpacking(self):
+        x0, y0, z0 = self.result
+        assert_equal((x0, y0, z0), (1, 2, 3))
+        assert_equal(self.result, (1, 2, 3))
+
+    def test_slice(self):
+        assert_equal(self.result[1:], (2, 3))
+        assert_equal(self.result[::2], (1, 3))
+        assert_equal(self.result[::-1], (3, 2, 1))
+
+    def test_len(self):
+        assert_equal(len(self.result), 3)
+
+    def test_repr(self):
+        s = repr(self.result)
+        assert_equal(s, 'Result(x=1, y=2, z=3, w=99, beta=0.5)')
+
+    def test_hash(self):
+        assert_equal(hash(self.result), hash((1, 2, 3)))
+
+    def test_pickle(self):
+        s = pickle.dumps(self.result)
+        obj = pickle.loads(s)
+        assert isinstance(obj, Result)
+        assert_equal(obj.x, self.result.x)
+        assert_equal(obj.y, self.result.y)
+        assert_equal(obj.z, self.result.z)
+        assert_equal(obj.w, self.result.w)
+        assert_equal(obj.beta, self.result.beta)
+
+    def test_read_only_existing(self):
+        with pytest.raises(AttributeError, match="can't set attribute"):
+            self.result.x = -1
+
+    def test_read_only_new(self):
+        self.result.plate_of_shrimp = "lattice of coincidence"
+        assert self.result.plate_of_shrimp == "lattice of coincidence"
+
+    def test_constructor_missing_parameter(self):
+        with pytest.raises(TypeError, match='missing'):
+            # `w` is missing.
+            Result(x=1, y=2, z=3, beta=0.75)
+
+    def test_constructor_incorrect_parameter(self):
+        with pytest.raises(TypeError, match='unexpected'):
+            # `foo` is not an existing field.
+            Result(x=1, y=2, z=3, w=123, beta=0.75, foo=999)
+
+    def test_module(self):
+        m = 'scipy._lib.tests.test_bunch'
+        assert_equal(Result.__module__, m)
+        assert_equal(self.result.__module__, m)
+
+    def test_extra_fields_per_instance(self):
+        # This test exists to ensure that instances of the same class
+        # store their own values for the extra fields. That is, the values
+        # are stored per instance and not in the class.
+        result1 = Result(x=1, y=2, z=3, w=-1, beta=0.0)
+        result2 = Result(x=4, y=5, z=6, w=99, beta=1.0)
+        assert_equal(result1.w, -1)
+        assert_equal(result1.beta, 0.0)
+        # The rest of these checks aren't essential, but let's check
+        # them anyway.
+        assert_equal(result1[:], (1, 2, 3))
+        assert_equal(result2.w, 99)
+        assert_equal(result2.beta, 1.0)
+        assert_equal(result2[:], (4, 5, 6))
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Other tests
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def test_extra_field_names_is_optional(self):
+        Square = _make_tuple_bunch('Square', ['width', 'height'])
+        sq = Square(width=1, height=2)
+        assert_equal(sq.width, 1)
+        assert_equal(sq.height, 2)
+        s = repr(sq)
+        assert_equal(s, 'Square(width=1, height=2)')
+
+    def test_tuple_like(self):
+        Tup = _make_tuple_bunch('Tup', ['a', 'b'])
+        tu = Tup(a=1, b=2)
+        assert isinstance(tu, tuple)
+        assert isinstance(tu + (1,), tuple)
+
+    def test_explicit_module(self):
+        m = 'some.module.name'
+        Foo = _make_tuple_bunch('Foo', ['x'], ['a', 'b'], module=m)
+        foo = Foo(x=1, a=355, b=113)
+        assert_equal(Foo.__module__, m)
+        assert_equal(foo.__module__, m)
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Argument validation
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    @pytest.mark.parametrize('args', [('123', ['a'], ['b']),
+                                      ('Foo', ['-3'], ['x']),
+                                      ('Foo', ['a'], ['+-*/'])])
+    def test_identifiers_not_allowed(self, args):
+        with pytest.raises(ValueError, match='identifiers'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['a', 'b', 'a'], ['x']),
+                                      ('Foo', ['a', 'b'], ['b', 'x'])])
+    def test_repeated_field_names(self, args):
+        with pytest.raises(ValueError, match='Duplicate'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['_a'], ['x']),
+                                      ('Foo', ['a'], ['_x'])])
+    def test_leading_underscore_not_allowed(self, args):
+        with pytest.raises(ValueError, match='underscore'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['def'], ['x']),
+                                      ('Foo', ['a'], ['or']),
+                                      ('and', ['a'], ['x'])])
+    def test_keyword_not_allowed_in_fields(self, args):
+        with pytest.raises(ValueError, match='keyword'):
+            _make_tuple_bunch(*args)
+
+    def test_at_least_one_field_name_required(self):
+        with pytest.raises(ValueError, match='at least one name'):
+            _make_tuple_bunch('Qwerty', [], ['a', 'b'])
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py
new file mode 100644
index 0000000000000000000000000000000000000000..82021775c294c7b881b9458b57d16deaac483cc7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py
@@ -0,0 +1,204 @@
+from numpy.testing import assert_equal, assert_
+from pytest import raises as assert_raises
+
+import time
+import pytest
+import ctypes
+import threading
+from scipy._lib import _ccallback_c as _test_ccallback_cython
+from scipy._lib import _test_ccallback
+from scipy._lib._ccallback import LowLevelCallable
+
+try:
+    import cffi
+    HAVE_CFFI = True
+except ImportError:
+    HAVE_CFFI = False
+
+
+ERROR_VALUE = 2.0
+
+
+def callback_python(a, user_data=None):
+    if a == ERROR_VALUE:
+        raise ValueError("bad value")
+
+    if user_data is None:
+        return a + 1
+    else:
+        return a + user_data
+
+def _get_cffi_func(base, signature):
+    if not HAVE_CFFI:
+        pytest.skip("cffi not installed")
+
+    # Get function address
+    voidp = ctypes.cast(base, ctypes.c_void_p)
+    address = voidp.value
+
+    # Create corresponding cffi handle
+    ffi = cffi.FFI()
+    func = ffi.cast(signature, address)
+    return func
+
+
+def _get_ctypes_data():
+    value = ctypes.c_double(2.0)
+    return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp)
+
+
+def _get_cffi_data():
+    if not HAVE_CFFI:
+        pytest.skip("cffi not installed")
+    ffi = cffi.FFI()
+    return ffi.new('double *', 2.0)
+
+
+CALLERS = {
+    'simple': _test_ccallback.test_call_simple,
+    'nodata': _test_ccallback.test_call_nodata,
+    'nonlocal': _test_ccallback.test_call_nonlocal,
+    'cython': _test_ccallback_cython.test_call_cython,
+}
+
+# These functions have signatures known to the callers
+FUNCS = {
+    'python': lambda: callback_python,
+    'capsule': lambda: _test_ccallback.test_get_plus1_capsule(),
+    'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                   "plus1_cython"),
+    'ctypes': lambda: _test_ccallback_cython.plus1_ctypes,
+    'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes,
+                                   'double (*)(double, int *, void *)'),
+    'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(),
+    'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                     "plus1b_cython"),
+    'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes,
+    'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes,
+                                     'double (*)(double, double, int *, void *)'),
+}
+
+# These functions have signatures the callers don't know
+BAD_FUNCS = {
+    'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(),
+    'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                      "plus1bc_cython"),
+    'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes,
+    'cffi_bc': lambda: _get_cffi_func(
+        _test_ccallback_cython.plus1bc_ctypes,
+        'double (*)(double, double, double, int *, void *)'
+    ),
+}
+
+USER_DATAS = {
+    'ctypes': _get_ctypes_data,
+    'cffi': _get_cffi_data,
+    'capsule': _test_ccallback.test_get_data_capsule,
+}
+
+
+def test_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        func = FUNCS[func]()
+        user_data = USER_DATAS[user_data]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test basic call
+        assert_equal(caller(func, 1.0), 2.0)
+
+        # Test 'bad' value resulting to an error
+        assert_raises(ValueError, caller, func, ERROR_VALUE)
+
+        # Test passing in user_data
+        assert_equal(caller(func2, 1.0), 3.0)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_bad_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        user_data = USER_DATAS[user_data]()
+        func = BAD_FUNCS[func]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test that basic call fails
+        assert_raises(ValueError, caller, LowLevelCallable(func), 1.0)
+
+        # Test that passing in user_data also fails
+        assert_raises(ValueError, caller, func2, 1.0)
+
+        # Test error message
+        llfunc = LowLevelCallable(func)
+        try:
+            caller(llfunc, 1.0)
+        except ValueError as err:
+            msg = str(err)
+            assert_(llfunc.signature in msg, msg)
+            assert_('double (double, double, int *, void *)' in msg, msg)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(BAD_FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_signature_override():
+    caller = _test_ccallback.test_call_simple
+    func = _test_ccallback.test_get_plus1_capsule()
+
+    llcallable = LowLevelCallable(func, signature="bad signature")
+    assert_equal(llcallable.signature, "bad signature")
+    assert_raises(ValueError, caller, llcallable, 3)
+
+    llcallable = LowLevelCallable(func, signature="double (double, int *, void *)")
+    assert_equal(llcallable.signature, "double (double, int *, void *)")
+    assert_equal(caller(llcallable, 3), 4)
+
+
+def test_threadsafety():
+    def callback(a, caller):
+        if a <= 0:
+            return 1
+        else:
+            res = caller(lambda x: callback(x, caller), a - 1)
+            return 2*res
+
+    def check(caller):
+        caller = CALLERS[caller]
+
+        results = []
+
+        count = 10
+
+        def run():
+            time.sleep(0.01)
+            r = caller(lambda x: callback(x, caller), count)
+            results.append(r)
+
+        threads = [threading.Thread(target=run) for j in range(20)]
+        for thread in threads:
+            thread.start()
+        for thread in threads:
+            thread.join()
+
+        assert_equal(results, [2.0**count]*len(threads))
+
+    for caller in CALLERS.keys():
+        check(caller)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..794e365c0d8a5ce337765fc669d688e80240d540
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py
@@ -0,0 +1,45 @@
+"""
+Check the SciPy config is valid.
+"""
+import scipy
+import pytest
+from unittest.mock import patch
+
+pytestmark = pytest.mark.skipif(
+    not hasattr(scipy.__config__, "_built_with_meson"),
+    reason="Requires Meson builds",
+)
+
+
+class TestSciPyConfigs:
+    REQUIRED_CONFIG_KEYS = [
+        "Compilers",
+        "Machine Information",
+        "Python Information",
+    ]
+
+    @pytest.mark.thread_unsafe
+    @patch("scipy.__config__._check_pyyaml")
+    def test_pyyaml_not_found(self, mock_yaml_importer):
+        mock_yaml_importer.side_effect = ModuleNotFoundError()
+        with pytest.warns(UserWarning):
+            scipy.show_config()
+
+    def test_dict_mode(self):
+        config = scipy.show_config(mode="dicts")
+
+        assert isinstance(config, dict)
+        assert all([key in config for key in self.REQUIRED_CONFIG_KEYS]), (
+            "Required key missing,"
+            " see index of `False` with `REQUIRED_CONFIG_KEYS`"
+        )
+
+    def test_invalid_mode(self):
+        with pytest.raises(AttributeError):
+            scipy.show_config(mode="foo")
+
+    def test_warn_to_add_tests(self):
+        assert len(scipy.__config__.DisplayModes) == 2, (
+            "New mode detected,"
+            " please add UT if applicable and increment this count"
+        )
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..667e6ab94346fc8b22c0ea4d4624acf33124c8c0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py
@@ -0,0 +1,10 @@
+import pytest
+
+@pytest.mark.thread_unsafe
+def test_cython_api_deprecation():
+    match = ("`scipy._lib._test_deprecation_def.foo_deprecated` "
+             "is deprecated, use `foo` instead!\n"
+             "Deprecated in Scipy 42.0.0")
+    with pytest.warns(DeprecationWarning, match=match):
+        from .. import _test_deprecation_call
+    assert _test_deprecation_call.call() == (1, 1)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..176a69698b10bd1d0d23fc57f8e8a99ce7209f0f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py
@@ -0,0 +1,143 @@
+''' Some tests for the documenting decorator and support functions '''
+
+import sys
+import pytest
+from numpy.testing import assert_equal, suppress_warnings
+
+from scipy._lib import doccer
+
+# python -OO strips docstrings
+DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
+
+docstring = \
+"""Docstring
+    %(strtest1)s
+        %(strtest2)s
+     %(strtest3)s
+"""
+param_doc1 = \
+"""Another test
+   with some indent"""
+
+param_doc2 = \
+"""Another test, one line"""
+
+param_doc3 = \
+"""    Another test
+       with some indent"""
+
+doc_dict = {'strtest1':param_doc1,
+            'strtest2':param_doc2,
+            'strtest3':param_doc3}
+
+filled_docstring = \
+"""Docstring
+    Another test
+       with some indent
+        Another test, one line
+     Another test
+       with some indent
+"""
+
+
+def test_unindent():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        assert_equal(doccer.unindent_string(param_doc1), param_doc1)
+        assert_equal(doccer.unindent_string(param_doc2), param_doc2)
+        assert_equal(doccer.unindent_string(param_doc3), param_doc1)
+
+
+def test_unindent_dict():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        d2 = doccer.unindent_dict(doc_dict)
+    assert_equal(d2['strtest1'], doc_dict['strtest1'])
+    assert_equal(d2['strtest2'], doc_dict['strtest2'])
+    assert_equal(d2['strtest3'], doc_dict['strtest1'])
+
+
+def test_docformat():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        udd = doccer.unindent_dict(doc_dict)
+        formatted = doccer.docformat(docstring, udd)
+        assert_equal(formatted, filled_docstring)
+        single_doc = 'Single line doc %(strtest1)s'
+        formatted = doccer.docformat(single_doc, doc_dict)
+        # Note - initial indent of format string does not
+        # affect subsequent indent of inserted parameter
+        assert_equal(formatted, """Single line doc Another test
+   with some indent""")
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_decorator():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        # with unindentation of parameters
+        decorator = doccer.filldoc(doc_dict, True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+
+        def expected():
+            """ Docstring
+            Another test
+               with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+        # without unindentation of parameters
+
+        # The docstring should be unindented for Python 3.13+
+        # because of https://github.com/python/cpython/issues/81283
+        decorator = doccer.filldoc(doc_dict, False if \
+                                   sys.version_info < (3, 13) else True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+        def expected():
+            """ Docstring
+                Another test
+                   with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_inherit_docstring_from():
+
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+
+        class Foo:
+            def func(self):
+                '''Do something useful.'''
+                return
+
+            def func2(self):
+                '''Something else.'''
+
+        class Bar(Foo):
+            @doccer.inherit_docstring_from(Foo)
+            def func(self):
+                '''%(super)sABC'''
+                return
+
+            @doccer.inherit_docstring_from(Foo)
+            def func2(self):
+                # No docstring.
+                return
+
+    assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(Bar.func2.__doc__, Foo.func2.__doc__)
+    bar = Bar()
+    assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(bar.func2.__doc__, Foo.func2.__doc__)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a35800a8198af8215e0b5624738f9ac45b0bb96
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py
@@ -0,0 +1,18 @@
+import pytest
+import sys
+import subprocess
+
+from .test_public_api import PUBLIC_MODULES
+
+# Regression tests for gh-6793.
+# Check that all modules are importable in a new Python process.
+# This is not necessarily true if there are import cycles present.
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+@pytest.mark.thread_unsafe
+def test_public_modules_importable():
+    pids = [subprocess.Popen([sys.executable, '-c', f'import {module}'])
+            for module in PUBLIC_MODULES]
+    for i, pid in enumerate(pids):
+        assert pid.wait() == 0, f'Failed to import {PUBLIC_MODULES[i]}'
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..5332107cd21cdd2b6e40cc545c87138cee04ff97
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py
@@ -0,0 +1,469 @@
+"""
+This test script is adopted from:
+    https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py
+"""
+
+import pkgutil
+import types
+import importlib
+import warnings
+from importlib import import_module
+
+import pytest
+
+import numpy as np
+import scipy
+
+from scipy.conftest import xp_available_backends
+
+
+def test_dir_testing():
+    """Assert that output of dir has only one "testing/tester"
+    attribute without duplicate"""
+    assert len(dir(scipy)) == len(set(dir(scipy)))
+
+
+# Historically SciPy has not used leading underscores for private submodules
+# much.  This has resulted in lots of things that look like public modules
+# (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
+# but were never intended to be public.  The PUBLIC_MODULES list contains
+# modules that are either public because they were meant to be, or because they
+# contain public functions/objects that aren't present in any other namespace
+# for whatever reason and therefore should be treated as public.
+PUBLIC_MODULES = ["scipy." + s for s in [
+    "cluster",
+    "cluster.vq",
+    "cluster.hierarchy",
+    "constants",
+    "datasets",
+    "differentiate",
+    "fft",
+    "fftpack",
+    "integrate",
+    "interpolate",
+    "io",
+    "io.arff",
+    "io.matlab",
+    "io.wavfile",
+    "linalg",
+    "linalg.blas",
+    "linalg.cython_blas",
+    "linalg.lapack",
+    "linalg.cython_lapack",
+    "linalg.interpolative",
+    "ndimage",
+    "odr",
+    "optimize",
+    "optimize.elementwise",
+    "signal",
+    "signal.windows",
+    "sparse",
+    "sparse.linalg",
+    "sparse.csgraph",
+    "spatial",
+    "spatial.distance",
+    "spatial.transform",
+    "special",
+    "stats",
+    "stats.contingency",
+    "stats.distributions",
+    "stats.mstats",
+    "stats.qmc",
+    "stats.sampling"
+]]
+
+# The PRIVATE_BUT_PRESENT_MODULES list contains modules that lacked underscores
+# in their name and hence looked public, but weren't meant to be. All these
+# namespace were deprecated in the 1.8.0 release - see "clear split between
+# public and private API" in the 1.8.0 release notes.
+# These private modules support will be removed in SciPy v2.0.0, as the
+# deprecation messages emitted by each of these modules say.
+PRIVATE_BUT_PRESENT_MODULES = [
+    'scipy.constants.codata',
+    'scipy.constants.constants',
+    'scipy.fftpack.basic',
+    'scipy.fftpack.convolve',
+    'scipy.fftpack.helper',
+    'scipy.fftpack.pseudo_diffs',
+    'scipy.fftpack.realtransforms',
+    'scipy.integrate.dop',
+    'scipy.integrate.lsoda',
+    'scipy.integrate.odepack',
+    'scipy.integrate.quadpack',
+    'scipy.integrate.vode',
+    'scipy.interpolate.dfitpack',
+    'scipy.interpolate.fitpack',
+    'scipy.interpolate.fitpack2',
+    'scipy.interpolate.interpnd',
+    'scipy.interpolate.interpolate',
+    'scipy.interpolate.ndgriddata',
+    'scipy.interpolate.polyint',
+    'scipy.interpolate.rbf',
+    'scipy.io.arff.arffread',
+    'scipy.io.harwell_boeing',
+    'scipy.io.idl',
+    'scipy.io.matlab.byteordercodes',
+    'scipy.io.matlab.mio',
+    'scipy.io.matlab.mio4',
+    'scipy.io.matlab.mio5',
+    'scipy.io.matlab.mio5_params',
+    'scipy.io.matlab.mio5_utils',
+    'scipy.io.matlab.mio_utils',
+    'scipy.io.matlab.miobase',
+    'scipy.io.matlab.streams',
+    'scipy.io.mmio',
+    'scipy.io.netcdf',
+    'scipy.linalg.basic',
+    'scipy.linalg.decomp',
+    'scipy.linalg.decomp_cholesky',
+    'scipy.linalg.decomp_lu',
+    'scipy.linalg.decomp_qr',
+    'scipy.linalg.decomp_schur',
+    'scipy.linalg.decomp_svd',
+    'scipy.linalg.matfuncs',
+    'scipy.linalg.misc',
+    'scipy.linalg.special_matrices',
+    'scipy.misc',
+    'scipy.misc.common',
+    'scipy.misc.doccer',
+    'scipy.ndimage.filters',
+    'scipy.ndimage.fourier',
+    'scipy.ndimage.interpolation',
+    'scipy.ndimage.measurements',
+    'scipy.ndimage.morphology',
+    'scipy.odr.models',
+    'scipy.odr.odrpack',
+    'scipy.optimize.cobyla',
+    'scipy.optimize.cython_optimize',
+    'scipy.optimize.lbfgsb',
+    'scipy.optimize.linesearch',
+    'scipy.optimize.minpack',
+    'scipy.optimize.minpack2',
+    'scipy.optimize.moduleTNC',
+    'scipy.optimize.nonlin',
+    'scipy.optimize.optimize',
+    'scipy.optimize.slsqp',
+    'scipy.optimize.tnc',
+    'scipy.optimize.zeros',
+    'scipy.signal.bsplines',
+    'scipy.signal.filter_design',
+    'scipy.signal.fir_filter_design',
+    'scipy.signal.lti_conversion',
+    'scipy.signal.ltisys',
+    'scipy.signal.signaltools',
+    'scipy.signal.spectral',
+    'scipy.signal.spline',
+    'scipy.signal.waveforms',
+    'scipy.signal.wavelets',
+    'scipy.signal.windows.windows',
+    'scipy.sparse.base',
+    'scipy.sparse.bsr',
+    'scipy.sparse.compressed',
+    'scipy.sparse.construct',
+    'scipy.sparse.coo',
+    'scipy.sparse.csc',
+    'scipy.sparse.csr',
+    'scipy.sparse.data',
+    'scipy.sparse.dia',
+    'scipy.sparse.dok',
+    'scipy.sparse.extract',
+    'scipy.sparse.lil',
+    'scipy.sparse.linalg.dsolve',
+    'scipy.sparse.linalg.eigen',
+    'scipy.sparse.linalg.interface',
+    'scipy.sparse.linalg.isolve',
+    'scipy.sparse.linalg.matfuncs',
+    'scipy.sparse.sparsetools',
+    'scipy.sparse.spfuncs',
+    'scipy.sparse.sputils',
+    'scipy.spatial.ckdtree',
+    'scipy.spatial.kdtree',
+    'scipy.spatial.qhull',
+    'scipy.spatial.transform.rotation',
+    'scipy.special.add_newdocs',
+    'scipy.special.basic',
+    'scipy.special.cython_special',
+    'scipy.special.orthogonal',
+    'scipy.special.sf_error',
+    'scipy.special.specfun',
+    'scipy.special.spfun_stats',
+    'scipy.stats.biasedurn',
+    'scipy.stats.kde',
+    'scipy.stats.morestats',
+    'scipy.stats.mstats_basic',
+    'scipy.stats.mstats_extras',
+    'scipy.stats.mvn',
+    'scipy.stats.stats',
+]
+
+
+def is_unexpected(name):
+    """Check if this needs to be considered."""
+    if '._' in name or '.tests' in name or '.setup' in name:
+        return False
+
+    if name in PUBLIC_MODULES:
+        return False
+
+    if name in PRIVATE_BUT_PRESENT_MODULES:
+        return False
+
+    return True
+
+
+SKIP_LIST = [
+    'scipy.conftest',
+    'scipy.version',
+    'scipy.special.libsf_error_state'
+]
+
+
+# XXX: this test does more than it says on the tin - in using `pkgutil.walk_packages`,
+# it will raise if it encounters any exceptions which are not handled by `ignore_errors`
+# while attempting to import each discovered package.
+# For now, `ignore_errors` only ignores what is necessary, but this could be expanded -
+# for example, to all errors from private modules or git subpackages - if desired.
+@pytest.mark.thread_unsafe
+def test_all_modules_are_expected():
+    """
+    Test that we don't add anything that looks like a new public module by
+    accident.  Check is based on filenames.
+    """
+
+    def ignore_errors(name):
+        # if versions of other array libraries are installed which are incompatible
+        # with the installed NumPy version, there can be errors on importing
+        # `array_api_compat`. This should only raise if SciPy is configured with
+        # that library as an available backend.
+        backends = {'cupy', 'torch', 'dask.array'}
+        for backend in backends:
+            path = f'array_api_compat.{backend}'
+            if path in name and backend not in xp_available_backends:
+                return
+        raise
+
+    modnames = []
+
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning,"scipy.misc")
+        for _, modname, _ in pkgutil.walk_packages(path=scipy.__path__,
+                                                   prefix=scipy.__name__ + '.',
+                                                   onerror=ignore_errors):
+            if is_unexpected(modname) and modname not in SKIP_LIST:
+                # We have a name that is new.  If that's on purpose, add it to
+                # PUBLIC_MODULES.  We don't expect to have to add anything to
+                # PRIVATE_BUT_PRESENT_MODULES.  Use an underscore in the name!
+                modnames.append(modname)
+
+    if modnames:
+        raise AssertionError(f'Found unexpected modules: {modnames}')
+
+
+# Stuff that clearly shouldn't be in the API and is detected by the next test
+# below
+SKIP_LIST_2 = [
+    'scipy.char',
+    'scipy.rec',
+    'scipy.emath',
+    'scipy.math',
+    'scipy.random',
+    'scipy.ctypeslib',
+    'scipy.ma'
+]
+
+
+def test_all_modules_are_expected_2():
+    """
+    Method checking all objects. The pkgutil-based method in
+    `test_all_modules_are_expected` does not catch imports into a namespace,
+    only filenames.
+    """
+
+    def find_unexpected_members(mod_name):
+        members = []
+        module = importlib.import_module(mod_name)
+        if hasattr(module, '__all__'):
+            objnames = module.__all__
+        else:
+            objnames = dir(module)
+
+        for objname in objnames:
+            if not objname.startswith('_'):
+                fullobjname = mod_name + '.' + objname
+                if isinstance(getattr(module, objname), types.ModuleType):
+                    if is_unexpected(fullobjname) and fullobjname not in SKIP_LIST_2:
+                        members.append(fullobjname)
+
+        return members
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, "scipy.misc")
+        unexpected_members = find_unexpected_members("scipy")
+
+    for modname in PUBLIC_MODULES:
+        unexpected_members.extend(find_unexpected_members(modname))
+
+    if unexpected_members:
+        raise AssertionError("Found unexpected object(s) that look like "
+                             f"modules: {unexpected_members}")
+
+
+def test_api_importable():
+    """
+    Check that all submodules listed higher up in this file can be imported
+    Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
+    simply need to be removed from the list (deprecation may or may not be
+    needed - apply common sense).
+    """
+    def check_importable(module_name):
+        try:
+            importlib.import_module(module_name)
+        except (ImportError, AttributeError):
+            return False
+
+        return True
+
+    module_names = []
+    for module_name in PUBLIC_MODULES:
+        if not check_importable(module_name):
+            module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules in the public API that cannot be "
+                             f"imported: {module_names}")
+
+    with warnings.catch_warnings(record=True):
+        warnings.filterwarnings('always', category=DeprecationWarning)
+        warnings.filterwarnings('always', category=ImportWarning)
+        for module_name in PRIVATE_BUT_PRESENT_MODULES:
+            if not check_importable(module_name):
+                module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules that are not really public but looked "
+                             "public and can not be imported: "
+                             f"{module_names}")
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize(("module_name", "correct_module"),
+                         [('scipy.constants.codata', None),
+                          ('scipy.constants.constants', None),
+                          ('scipy.fftpack.basic', None),
+                          ('scipy.fftpack.helper', None),
+                          ('scipy.fftpack.pseudo_diffs', None),
+                          ('scipy.fftpack.realtransforms', None),
+                          ('scipy.integrate.dop', None),
+                          ('scipy.integrate.lsoda', None),
+                          ('scipy.integrate.odepack', None),
+                          ('scipy.integrate.quadpack', None),
+                          ('scipy.integrate.vode', None),
+                          ('scipy.interpolate.fitpack', None),
+                          ('scipy.interpolate.fitpack2', None),
+                          ('scipy.interpolate.interpolate', None),
+                          ('scipy.interpolate.ndgriddata', None),
+                          ('scipy.interpolate.polyint', None),
+                          ('scipy.interpolate.rbf', None),
+                          ('scipy.io.harwell_boeing', None),
+                          ('scipy.io.idl', None),
+                          ('scipy.io.mmio', None),
+                          ('scipy.io.netcdf', None),
+                          ('scipy.io.arff.arffread', 'arff'),
+                          ('scipy.io.matlab.byteordercodes', 'matlab'),
+                          ('scipy.io.matlab.mio_utils', 'matlab'),
+                          ('scipy.io.matlab.mio', 'matlab'),
+                          ('scipy.io.matlab.mio4', 'matlab'),
+                          ('scipy.io.matlab.mio5_params', 'matlab'),
+                          ('scipy.io.matlab.mio5_utils', 'matlab'),
+                          ('scipy.io.matlab.mio5', 'matlab'),
+                          ('scipy.io.matlab.miobase', 'matlab'),
+                          ('scipy.io.matlab.streams', 'matlab'),
+                          ('scipy.linalg.basic', None),
+                          ('scipy.linalg.decomp', None),
+                          ('scipy.linalg.decomp_cholesky', None),
+                          ('scipy.linalg.decomp_lu', None),
+                          ('scipy.linalg.decomp_qr', None),
+                          ('scipy.linalg.decomp_schur', None),
+                          ('scipy.linalg.decomp_svd', None),
+                          ('scipy.linalg.matfuncs', None),
+                          ('scipy.linalg.misc', None),
+                          ('scipy.linalg.special_matrices', None),
+                          ('scipy.ndimage.filters', None),
+                          ('scipy.ndimage.fourier', None),
+                          ('scipy.ndimage.interpolation', None),
+                          ('scipy.ndimage.measurements', None),
+                          ('scipy.ndimage.morphology', None),
+                          ('scipy.odr.models', None),
+                          ('scipy.odr.odrpack', None),
+                          ('scipy.optimize.cobyla', None),
+                          ('scipy.optimize.lbfgsb', None),
+                          ('scipy.optimize.linesearch', None),
+                          ('scipy.optimize.minpack', None),
+                          ('scipy.optimize.minpack2', None),
+                          ('scipy.optimize.moduleTNC', None),
+                          ('scipy.optimize.nonlin', None),
+                          ('scipy.optimize.optimize', None),
+                          ('scipy.optimize.slsqp', None),
+                          ('scipy.optimize.tnc', None),
+                          ('scipy.optimize.zeros', None),
+                          ('scipy.signal.bsplines', None),
+                          ('scipy.signal.filter_design', None),
+                          ('scipy.signal.fir_filter_design', None),
+                          ('scipy.signal.lti_conversion', None),
+                          ('scipy.signal.ltisys', None),
+                          ('scipy.signal.signaltools', None),
+                          ('scipy.signal.spectral', None),
+                          ('scipy.signal.waveforms', None),
+                          ('scipy.signal.wavelets', None),
+                          ('scipy.signal.windows.windows', 'windows'),
+                          ('scipy.sparse.lil', None),
+                          ('scipy.sparse.linalg.dsolve', 'linalg'),
+                          ('scipy.sparse.linalg.eigen', 'linalg'),
+                          ('scipy.sparse.linalg.interface', 'linalg'),
+                          ('scipy.sparse.linalg.isolve', 'linalg'),
+                          ('scipy.sparse.linalg.matfuncs', 'linalg'),
+                          ('scipy.sparse.sparsetools', None),
+                          ('scipy.sparse.spfuncs', None),
+                          ('scipy.sparse.sputils', None),
+                          ('scipy.spatial.ckdtree', None),
+                          ('scipy.spatial.kdtree', None),
+                          ('scipy.spatial.qhull', None),
+                          ('scipy.spatial.transform.rotation', 'transform'),
+                          ('scipy.special.add_newdocs', None),
+                          ('scipy.special.basic', None),
+                          ('scipy.special.orthogonal', None),
+                          ('scipy.special.sf_error', None),
+                          ('scipy.special.specfun', None),
+                          ('scipy.special.spfun_stats', None),
+                          ('scipy.stats.biasedurn', None),
+                          ('scipy.stats.kde', None),
+                          ('scipy.stats.morestats', None),
+                          ('scipy.stats.mstats_basic', 'mstats'),
+                          ('scipy.stats.mstats_extras', 'mstats'),
+                          ('scipy.stats.mvn', None),
+                          ('scipy.stats.stats', None)])
+def test_private_but_present_deprecation(module_name, correct_module):
+    # gh-18279, gh-17572, gh-17771 noted that deprecation warnings
+    # for imports from private modules
+    # were misleading. Check that this is resolved.
+    module = import_module(module_name)
+    if correct_module is None:
+        import_name = f'scipy.{module_name.split(".")[1]}'
+    else:
+        import_name = f'scipy.{module_name.split(".")[1]}.{correct_module}'
+
+    correct_import = import_module(import_name)
+
+    # Attributes that were formerly in `module_name` can still be imported from
+    # `module_name`, albeit with a deprecation warning.
+    for attr_name in module.__all__:
+        # ensure attribute is present where the warning is pointing
+        assert getattr(correct_import, attr_name, None) is not None
+        message = f"Please import `{attr_name}` from the `{import_name}`..."
+        with pytest.deprecated_call(match=message):
+            getattr(module, attr_name)
+
+    # Attributes that were not in `module_name` get an error notifying the user
+    # that the attribute is not in `module_name` and that `module_name` is deprecated.
+    message = f"`{module_name}` is deprecated..."
+    with pytest.raises(AttributeError, match=message):
+        getattr(module, "ekki")
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..68e1a43c3fb329b6a4274ba76b53a215738da6ad
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py
@@ -0,0 +1,28 @@
+import re
+
+import scipy
+import scipy.version
+
+
+def test_valid_scipy_version():
+    # Verify that the SciPy version is a valid one (no .post suffix or other
+    # nonsense). See NumPy issue gh-6431 for an issue caused by an invalid
+    # version.
+    version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(|a[0-9]|b[0-9]|rc[0-9])"
+    dev_suffix = r"((.dev0)|(\.dev0+\+git[0-9]{8}.[0-9a-f]{7}))"
+    if scipy.version.release:
+        res = re.match(version_pattern, scipy.__version__)
+    else:
+        res = re.match(version_pattern + dev_suffix, scipy.__version__)
+
+    assert res is not None
+    assert scipy.__version__
+
+
+def test_version_submodule_members():
+    """`scipy.version` may not be quite public, but we install it.
+
+    So check that we don't silently change its contents.
+    """
+    for attr in ('version', 'full_version', 'short_version', 'git_revision', 'release'):
+        assert hasattr(scipy.version, attr)
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..292e7ab1739e663979f9f0b9647fb2c7c95d625c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py
@@ -0,0 +1,48 @@
+""" Test tmpdirs module """
+from os import getcwd
+from os.path import realpath, abspath, dirname, isfile, join as pjoin, exists
+
+from scipy._lib._tmpdirs import tempdir, in_tempdir, in_dir
+
+from numpy.testing import assert_, assert_equal
+
+import pytest
+
+
+MY_PATH = abspath(__file__)
+MY_DIR = dirname(MY_PATH)
+
+
+@pytest.mark.thread_unsafe
+def test_tempdir():
+    with tempdir() as tmpdir:
+        fname = pjoin(tmpdir, 'example_file.txt')
+        with open(fname, "w") as fobj:
+            fobj.write('a string\\n')
+    assert_(not exists(tmpdir))
+
+
+@pytest.mark.thread_unsafe
+def test_in_tempdir():
+    my_cwd = getcwd()
+    with in_tempdir() as tmpdir:
+        with open('test.txt', "w") as f:
+            f.write('some text')
+        assert_(isfile('test.txt'))
+        assert_(isfile(pjoin(tmpdir, 'test.txt')))
+    assert_(not exists(tmpdir))
+    assert_equal(getcwd(), my_cwd)
+
+
+@pytest.mark.thread_unsafe
+def test_given_directory():
+    # Test InGivenDirectory
+    cwd = getcwd()
+    with in_dir() as tmpdir:
+        assert_equal(tmpdir, abspath(cwd))
+        assert_equal(tmpdir, abspath(getcwd()))
+    with in_dir(MY_DIR) as tmpdir:
+        assert_equal(tmpdir, MY_DIR)
+        assert_equal(realpath(MY_DIR), realpath(abspath(getcwd())))
+    # We were deleting the given directory! Check not so now.
+    assert_(isfile(MY_PATH))
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..f200b1a6e9756b17c96e5b8368271bbf61878d72
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py
@@ -0,0 +1,137 @@
+"""
+Tests which scan for certain occurrences in the code, they may not find
+all of these occurrences but should catch almost all. This file was adapted
+from NumPy.
+"""
+
+
+import os
+from pathlib import Path
+import ast
+import tokenize
+
+import scipy
+
+import pytest
+
+
+class ParseCall(ast.NodeVisitor):
+    def __init__(self):
+        self.ls = []
+
+    def visit_Attribute(self, node):
+        ast.NodeVisitor.generic_visit(self, node)
+        self.ls.append(node.attr)
+
+    def visit_Name(self, node):
+        self.ls.append(node.id)
+
+
+class FindFuncs(ast.NodeVisitor):
+    def __init__(self, filename):
+        super().__init__()
+        self.__filename = filename
+        self.bad_filters = []
+        self.bad_stacklevels = []
+
+    def visit_Call(self, node):
+        p = ParseCall()
+        p.visit(node.func)
+        ast.NodeVisitor.generic_visit(self, node)
+
+        if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
+            # get first argument of the `args` node of the filter call
+            match node.args[0]:
+                case ast.Constant() as c:
+                    argtext = c.value
+                case ast.JoinedStr() as js:
+                    # if we get an f-string, discard the templated pieces, which
+                    # are likely the type or specific message; we're interested
+                    # in the action, which is less likely to use a template
+                    argtext = "".join(
+                        x.value for x in js.values if isinstance(x, ast.Constant)
+                    )
+                case _:
+                    raise ValueError("unknown ast node type")
+            # check if filter is set to ignore
+            if argtext == "ignore":
+                self.bad_filters.append(
+                    f"{self.__filename}:{node.lineno}")
+
+        if p.ls[-1] == 'warn' and (
+                len(p.ls) == 1 or p.ls[-2] == 'warnings'):
+
+            if self.__filename == "_lib/tests/test_warnings.py":
+                # This file
+                return
+
+            # See if stacklevel exists:
+            if len(node.args) == 3:
+                return
+            args = {kw.arg for kw in node.keywords}
+            if "stacklevel" not in args:
+                self.bad_stacklevels.append(
+                    f"{self.__filename}:{node.lineno}")
+
+
+@pytest.fixture(scope="session")
+def warning_calls():
+    # combined "ignore" and stacklevel error
+    base = Path(scipy.__file__).parent
+
+    bad_filters = []
+    bad_stacklevels = []
+
+    for path in base.rglob("*.py"):
+        # use tokenize to auto-detect encoding on systems where no
+        # default encoding is defined (e.g., LANG='C')
+        with tokenize.open(str(path)) as file:
+            tree = ast.parse(file.read(), filename=str(path))
+            finder = FindFuncs(path.relative_to(base))
+            finder.visit(tree)
+            bad_filters.extend(finder.bad_filters)
+            bad_stacklevels.extend(finder.bad_stacklevels)
+
+    return bad_filters, bad_stacklevels
+
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+def test_warning_calls_filters(warning_calls):
+    bad_filters, bad_stacklevels = warning_calls
+
+    # We try not to add filters in the code base, because those filters aren't
+    # thread-safe. We aim to only filter in tests with
+    # np.testing.suppress_warnings. However, in some cases it may prove
+    # necessary to filter out warnings, because we can't (easily) fix the root
+    # cause for them and we don't want users to see some warnings when they use
+    # SciPy correctly. So we list exceptions here.  Add new entries only if
+    # there's a good reason.
+    allowed_filters = (
+        os.path.join('datasets', '_fetchers.py'),
+        os.path.join('datasets', '__init__.py'),
+        os.path.join('optimize', '_optimize.py'),
+        os.path.join('optimize', '_constraints.py'),
+        os.path.join('optimize', '_nnls.py'),
+        os.path.join('signal', '_ltisys.py'),
+        os.path.join('sparse', '__init__.py'),  # np.matrix pending-deprecation
+        os.path.join('special', '_basic.py'),  # gh-21801
+        os.path.join('stats', '_discrete_distns.py'),  # gh-14901
+        os.path.join('stats', '_continuous_distns.py'),
+        os.path.join('stats', '_binned_statistic.py'),  # gh-19345
+        os.path.join('stats', '_stats_py.py'),  # gh-20743
+        os.path.join('stats', 'tests', 'test_axis_nan_policy.py'),  # gh-20694
+        os.path.join('_lib', '_util.py'),  # gh-19341
+        os.path.join('sparse', 'linalg', '_dsolve', 'linsolve.py'),  # gh-17924
+        "conftest.py",
+    )
+    bad_filters = [item for item in bad_filters if item.split(':')[0] not in
+                   allowed_filters]
+
+    if bad_filters:
+        raise AssertionError(
+            "warning ignore filter should not be used, instead, use\n"
+            "numpy.testing.suppress_warnings (in tests only);\n"
+            "found in:\n    {}".format(
+                "\n    ".join(bad_filters)))
+
diff --git a/venv/lib/python3.10/site-packages/scipy/_lib/uarray.py b/venv/lib/python3.10/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..b29fc713efb3e836cc179ac87ce41f87b51870ef
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/_lib/uarray.py
@@ -0,0 +1,31 @@
+"""`uarray` provides functions for generating multimethods that dispatch to
+multiple different backends
+
+This should be imported, rather than `_uarray` so that an installed version could
+be used instead, if available. This means that users can call
+`uarray.set_backend` directly instead of going through SciPy.
+
+"""
+
+
+# Prefer an installed version of uarray, if available
+try:
+    import uarray as _uarray
+except ImportError:
+    _has_uarray = False
+else:
+    from scipy._lib._pep440 import Version as _Version
+
+    _has_uarray = _Version(_uarray.__version__) >= _Version("0.8")
+    del _uarray
+    del _Version
+
+
+if _has_uarray:
+    from uarray import *  # noqa: F403
+    from uarray import _Function
+else:
+    from ._uarray import *  # noqa: F403
+    from ._uarray import _Function  # noqa: F401
+
+del _has_uarray
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/__init__.py b/venv/lib/python3.10/site-packages/scipy/cluster/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b7784969a573d05cc6b98ee9066c42720156d1d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/__init__.py
@@ -0,0 +1,31 @@
+"""
+=========================================
+Clustering package (:mod:`scipy.cluster`)
+=========================================
+
+.. currentmodule:: scipy.cluster
+
+Clustering algorithms are useful in information theory, target detection,
+communications, compression, and other areas. The `vq` module only
+supports vector quantization and the k-means algorithms.
+
+The `hierarchy` module provides functions for hierarchical and
+agglomerative clustering.  Its features include generating hierarchical
+clusters from distance matrices,
+calculating statistics on clusters, cutting linkages
+to generate flat clusters, and visualizing clusters with dendrograms.
+
+.. toctree::
+   :maxdepth: 1
+
+   cluster.vq
+   cluster.hierarchy
+
+"""
+__all__ = ['vq', 'hierarchy']
+
+from . import vq, hierarchy
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07bddf99bdc2625f9521a996b2dfa0953fdbb8c5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/__pycache__/vq.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/__pycache__/vq.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1d22a83ed11a9f90ecb40633a702afcf40b1efc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/__pycache__/vq.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/hierarchy.py b/venv/lib/python3.10/site-packages/scipy/cluster/hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..522e63d8e6f2904c73c704897f715721509c819c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/hierarchy.py
@@ -0,0 +1,4178 @@
+"""
+Hierarchical clustering (:mod:`scipy.cluster.hierarchy`)
+========================================================
+
+.. currentmodule:: scipy.cluster.hierarchy
+
+These functions cut hierarchical clusterings into flat clusterings
+or find the roots of the forest formed by a cut by providing the flat
+cluster ids of each observation.
+
+.. autosummary::
+   :toctree: generated/
+
+   fcluster
+   fclusterdata
+   leaders
+
+These are routines for agglomerative clustering.
+
+.. autosummary::
+   :toctree: generated/
+
+   linkage
+   single
+   complete
+   average
+   weighted
+   centroid
+   median
+   ward
+
+These routines compute statistics on hierarchies.
+
+.. autosummary::
+   :toctree: generated/
+
+   cophenet
+   from_mlab_linkage
+   inconsistent
+   maxinconsts
+   maxdists
+   maxRstat
+   to_mlab_linkage
+
+Routines for visualizing flat clusters.
+
+.. autosummary::
+   :toctree: generated/
+
+   dendrogram
+
+These are data structures and routines for representing hierarchies as
+tree objects.
+
+.. autosummary::
+   :toctree: generated/
+
+   ClusterNode
+   leaves_list
+   to_tree
+   cut_tree
+   optimal_leaf_ordering
+
+These are predicates for checking the validity of linkage and
+inconsistency matrices as well as for checking isomorphism of two
+flat cluster assignments.
+
+.. autosummary::
+   :toctree: generated/
+
+   is_valid_im
+   is_valid_linkage
+   is_isomorphic
+   is_monotonic
+   correspond
+   num_obs_linkage
+
+Utility routines for plotting:
+
+.. autosummary::
+   :toctree: generated/
+
+   set_link_color_palette
+
+Utility classes:
+
+.. autosummary::
+   :toctree: generated/
+
+   DisjointSet -- data structure for incremental connectivity queries
+
+"""
+# Copyright (C) Damian Eads, 2007-2008. New BSD License.
+
+# hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com)
+#
+# Author: Damian Eads
+# Date:   September 22, 2007
+#
+# Copyright (c) 2007, 2008, Damian Eads
+#
+# All rights reserved.
+#
+# 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.
+#   - Neither the name of the author nor the names of its
+#     contributors 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
+# OWNER 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 warnings
+import bisect
+from collections import deque
+
+import numpy as np
+from . import _hierarchy, _optimal_leaf_ordering
+import scipy.spatial.distance as distance
+from scipy._lib._array_api import array_namespace, _asarray, xp_copy, is_jax
+from scipy._lib._disjoint_set import DisjointSet
+
+
+_LINKAGE_METHODS = {'single': 0, 'complete': 1, 'average': 2, 'centroid': 3,
+                    'median': 4, 'ward': 5, 'weighted': 6}
+_EUCLIDEAN_METHODS = ('centroid', 'median', 'ward')
+
+__all__ = ['ClusterNode', 'DisjointSet', 'average', 'centroid', 'complete',
+           'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster',
+           'fclusterdata', 'from_mlab_linkage', 'inconsistent',
+           'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage',
+           'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists',
+           'maxinconsts', 'median', 'num_obs_linkage', 'optimal_leaf_ordering',
+           'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree',
+           'ward', 'weighted']
+
+
+class ClusterWarning(UserWarning):
+    pass
+
+
+def _warning(s):
+    warnings.warn(f'scipy.cluster: {s}', ClusterWarning, stacklevel=3)
+
+
+def int_floor(arr, xp):
+    # array_api_strict is strict about not allowing `int()` on a float array.
+    # That's typically not needed, here it is - so explicitly convert
+    return int(xp.astype(xp.asarray(arr), xp.int64))
+
+
+def single(y):
+    """
+    Perform single/min/nearest linkage on the condensed distance matrix ``y``.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        The linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = single(y)
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  4,  5,  6,  1,  2,  3], dtype=int32)
+    >>> fcluster(Z, 1, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='single', metric='euclidean')
+
+
+def complete(y):
+    """
+    Perform complete/max/farthest point linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import complete, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = complete(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.41421356,  3.        ],
+           [ 5.        , 13.        ,  1.41421356,  3.        ],
+           [ 8.        , 14.        ,  1.41421356,  3.        ],
+           [11.        , 15.        ,  1.41421356,  3.        ],
+           [16.        , 17.        ,  4.12310563,  6.        ],
+           [18.        , 19.        ,  4.12310563,  6.        ],
+           [20.        , 21.        ,  5.65685425, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4.5, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='complete', metric='euclidean')
+
+
+def average(y):
+    """
+    Perform average/UPGMA linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import average, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = average(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 5.        , 13.        ,  1.20710678,  3.        ],
+           [ 8.        , 14.        ,  1.20710678,  3.        ],
+           [11.        , 15.        ,  1.20710678,  3.        ],
+           [16.        , 17.        ,  3.39675184,  6.        ],
+           [18.        , 19.        ,  3.39675184,  6.        ],
+           [20.        , 21.        ,  4.09206523, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='average', metric='euclidean')
+
+
+def weighted(y):
+    """
+    Perform weighted/WPGMA linkage on the condensed distance matrix.
+
+    See `linkage` for more information on the return
+    structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import weighted, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = weighted(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 11.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 8.        , 13.        ,  1.20710678,  3.        ],
+           [ 5.        , 14.        ,  1.20710678,  3.        ],
+           [10.        , 15.        ,  1.20710678,  3.        ],
+           [18.        , 19.        ,  3.05595762,  6.        ],
+           [16.        , 17.        ,  3.32379407,  6.        ],
+           [20.        , 21.        ,  4.06357713, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9,  1,  2,  3, 10, 11, 12,  4,  6,  5], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([3, 3, 3, 1, 1, 1, 4, 4, 4, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='weighted', metric='euclidean')
+
+
+def centroid(y):
+    """
+    Perform centroid/UPGMC linkage.
+
+    See `linkage` for more information on the input matrix,
+    return structure, and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = centroid(y)``
+
+       Performs centroid/UPGMC linkage on the condensed distance
+       matrix ``y``.
+
+    2. ``Z = centroid(X)``
+
+       Performs centroid/UPGMC linkage on the observation matrix ``X``
+       using Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns. Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import centroid, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = centroid(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.33333333,  6.        ],
+           [16.        , 17.        ,  3.33333333,  6.        ],
+           [20.        , 21.        ,  3.33333333, 12.        ]]) # may vary
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32) # may vary
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32) # may vary
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32) # may vary
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='centroid', metric='euclidean')
+
+
+def median(y):
+    """
+    Perform median/WPGMC linkage.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+     The following are common calling conventions:
+
+     1. ``Z = median(y)``
+
+        Performs median/WPGMC linkage on the condensed distance matrix
+        ``y``.  See ``linkage`` for more information on the return
+        structure and algorithm.
+
+     2. ``Z = median(X)``
+
+        Performs median/WPGMC linkage on the observation matrix ``X``
+        using Euclidean distance as the distance metric. See `linkage`
+        for more information on the return structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = median(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='median', metric='euclidean')
+
+
+def ward(y):
+    """
+    Perform Ward's linkage on a condensed distance matrix.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = ward(y)``
+       Performs Ward's linkage on the condensed distance matrix ``y``.
+
+    2. ``Z = ward(X)``
+       Performs Ward's linkage on the observation matrix ``X`` using
+       Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = ward(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+    >>> fcluster(Z, 3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='ward', metric='euclidean')
+
+
+def linkage(y, method='single', metric='euclidean', optimal_ordering=False):
+    """
+    Perform hierarchical/agglomerative clustering.
+
+    The input y may be either a 1-D condensed distance matrix
+    or a 2-D array of observation vectors.
+
+    If y is a 1-D condensed distance matrix,
+    then y must be a :math:`\\binom{n}{2}` sized
+    vector, where n is the number of original observations paired
+    in the distance matrix. The behavior of this function is very
+    similar to the MATLAB linkage function.
+
+    A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the
+    :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and
+    ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A
+    cluster with an index less than :math:`n` corresponds to one of
+    the :math:`n` original observations. The distance between
+    clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The
+    fourth value ``Z[i, 3]`` represents the number of original
+    observations in the newly formed cluster.
+
+    The following linkage methods are used to compute the distance
+    :math:`d(s, t)` between two clusters :math:`s` and
+    :math:`t`. The algorithm begins with a forest of clusters that
+    have yet to be used in the hierarchy being formed. When two
+    clusters :math:`s` and :math:`t` from this forest are combined
+    into a single cluster :math:`u`, :math:`s` and :math:`t` are
+    removed from the forest, and :math:`u` is added to the
+    forest. When only one cluster remains in the forest, the algorithm
+    stops, and this cluster becomes the root.
+
+    A distance matrix is maintained at each iteration. The ``d[i,j]``
+    entry corresponds to the distance between cluster :math:`i` and
+    :math:`j` in the original forest.
+
+    At each iteration, the algorithm must update the distance matrix
+    to reflect the distance of the newly formed cluster u with the
+    remaining clusters in the forest.
+
+    Suppose there are :math:`|u|` original observations
+    :math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and
+    :math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in
+    cluster :math:`v`. Recall, :math:`s` and :math:`t` are
+    combined to form cluster :math:`u`. Let :math:`v` be any
+    remaining cluster in the forest that is not :math:`u`.
+
+    The following are methods for calculating the distance between the
+    newly formed cluster :math:`u` and each :math:`v`.
+
+      * method='single' assigns
+
+        .. math::
+           d(u,v) = \\min(dist(u[i],v[j]))
+
+        for all points :math:`i` in cluster :math:`u` and
+        :math:`j` in cluster :math:`v`. This is also known as the
+        Nearest Point Algorithm.
+
+      * method='complete' assigns
+
+        .. math::
+           d(u, v) = \\max(dist(u[i],v[j]))
+
+        for all points :math:`i` in cluster u and :math:`j` in
+        cluster :math:`v`. This is also known by the Farthest Point
+        Algorithm or Voor Hees Algorithm.
+
+      * method='average' assigns
+
+        .. math::
+           d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])}
+                                   {(|u|*|v|)}
+
+        for all points :math:`i` and :math:`j` where :math:`|u|`
+        and :math:`|v|` are the cardinalities of clusters :math:`u`
+        and :math:`v`, respectively. This is also called the UPGMA
+        algorithm.
+
+      * method='weighted' assigns
+
+        .. math::
+           d(u,v) = (dist(s,v) + dist(t,v))/2
+
+        where cluster u was formed with cluster s and t and v
+        is a remaining cluster in the forest (also called WPGMA).
+
+      * method='centroid' assigns
+
+        .. math::
+           dist(s,t) = ||c_s-c_t||_2
+
+        where :math:`c_s` and :math:`c_t` are the centroids of
+        clusters :math:`s` and :math:`t`, respectively. When two
+        clusters :math:`s` and :math:`t` are combined into a new
+        cluster :math:`u`, the new centroid is computed over all the
+        original objects in clusters :math:`s` and :math:`t`. The
+        distance then becomes the Euclidean distance between the
+        centroid of :math:`u` and the centroid of a remaining cluster
+        :math:`v` in the forest. This is also known as the UPGMC
+        algorithm.
+
+      * method='median' assigns :math:`d(s,t)` like the ``centroid``
+        method. When two clusters :math:`s` and :math:`t` are combined
+        into a new cluster :math:`u`, the average of centroids s and t
+        give the new centroid :math:`u`. This is also known as the
+        WPGMC algorithm.
+
+      * method='ward' uses the Ward variance minimization algorithm.
+        The new entry :math:`d(u,v)` is computed as follows,
+
+        .. math::
+
+           d(u,v) = \\sqrt{\\frac{|v|+|s|}
+                               {T}d(v,s)^2
+                        + \\frac{|v|+|t|}
+                               {T}d(v,t)^2
+                        - \\frac{|v|}
+                               {T}d(s,t)^2}
+
+        where :math:`u` is the newly joined cluster consisting of
+        clusters :math:`s` and :math:`t`, :math:`v` is an unused
+        cluster in the forest, :math:`T=|v|+|s|+|t|`, and
+        :math:`|*|` is the cardinality of its argument. This is also
+        known as the incremental algorithm.
+
+    Warning: When the minimum distance pair in the forest is chosen, there
+    may be two or more pairs with the same minimum distance. This
+    implementation may choose a different minimum than the MATLAB
+    version.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed distance matrix
+        is a flat array containing the upper triangular of the distance matrix.
+        This is the form that ``pdist`` returns. Alternatively, a collection of
+        :math:`m` observation vectors in :math:`n` dimensions may be passed as
+        an :math:`m` by :math:`n` array. All elements of the condensed distance
+        matrix must be finite, i.e., no NaNs or infs.
+    method : str, optional
+        The linkage algorithm to use. See the ``Linkage Methods`` section below
+        for full descriptions.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+    optimal_ordering : bool, optional
+        If True, the linkage matrix will be reordered so that the distance
+        between successive leaves is minimal. This results in a more intuitive
+        tree structure when the data are visualized. defaults to False, because
+        this algorithm can be slow, particularly on large datasets [2]_. See
+        also the `optimal_leaf_ordering` function.
+
+        .. versionadded:: 1.0.0
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    Notes
+    -----
+    1. For method 'single', an optimized algorithm based on minimum spanning
+       tree is implemented. It has time complexity :math:`O(n^2)`.
+       For methods 'complete', 'average', 'weighted' and 'ward', an algorithm
+       called nearest-neighbors chain is implemented. It also has time
+       complexity :math:`O(n^2)`.
+       For other methods, a naive algorithm is implemented with :math:`O(n^3)`
+       time complexity.
+       All algorithms use :math:`O(n^2)` memory.
+       Refer to [1]_ for details about the algorithms.
+    2. Methods 'centroid', 'median', and 'ward' are correctly defined only if
+       Euclidean pairwise metric is used. If `y` is passed as precomputed
+       pairwise distances, then it is the user's responsibility to assure that
+       these distances are in fact Euclidean, otherwise the produced result
+       will be incorrect.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    References
+    ----------
+    .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering
+           algorithms", :arXiv:`1109.2378v1`.
+    .. [2] Ziv Bar-Joseph, David K. Gifford, Tommi S. Jaakkola, "Fast optimal
+           leaf ordering for hierarchical clustering", 2001. Bioinformatics
+           :doi:`10.1093/bioinformatics/17.suppl_1.S22`
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import dendrogram, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+
+    >>> Z = linkage(X, 'ward')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+
+    >>> Z = linkage(X, 'single')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+
+    if method not in _LINKAGE_METHODS:
+        raise ValueError(f"Invalid method: {method}")
+
+    if method in _EUCLIDEAN_METHODS and metric != 'euclidean' and y.ndim == 2:
+        msg = f"`method={method}` requires the distance metric to be Euclidean"
+        raise ValueError(msg)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (y.shape[0] == y.shape[1] and np.allclose(np.diag(y), 0) and
+                xp.all(y >= 0) and np.allclose(y, y.T)):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+        y = xp.asarray(y)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+
+    if not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    n = int(distance.num_obs_y(y))
+    method_code = _LINKAGE_METHODS[method]
+
+    y = np.asarray(y)
+    if method == 'single':
+        result = _hierarchy.mst_single_linkage(y, n)
+    elif method in ['complete', 'average', 'weighted', 'ward']:
+        result = _hierarchy.nn_chain(y, n, method_code)
+    else:
+        result = _hierarchy.fast_linkage(y, n, method_code)
+    result = xp.asarray(result)
+
+    if optimal_ordering:
+        y = xp.asarray(y)
+        return optimal_leaf_ordering(result, y)
+    else:
+        return result
+
+
+class ClusterNode:
+    """
+    A tree node class for representing a cluster.
+
+    Leaf nodes correspond to original observations, while non-leaf nodes
+    correspond to non-singleton clusters.
+
+    The `to_tree` function converts a matrix returned by the linkage
+    function into an easy-to-use tree representation.
+
+    All parameter names are also attributes.
+
+    Parameters
+    ----------
+    id : int
+        The node id.
+    left : ClusterNode instance, optional
+        The left child tree node.
+    right : ClusterNode instance, optional
+        The right child tree node.
+    dist : float, optional
+        Distance for this cluster in the linkage matrix.
+    count : int, optional
+        The number of samples in this cluster.
+
+    See Also
+    --------
+    to_tree : for converting a linkage matrix ``Z`` into a tree object.
+
+    """
+
+    def __init__(self, id, left=None, right=None, dist=0.0, count=1):
+        if id < 0:
+            raise ValueError('The id must be non-negative.')
+        if dist < 0:
+            raise ValueError('The distance must be non-negative.')
+        if (left is None and right is not None) or \
+           (left is not None and right is None):
+            raise ValueError('Only full or proper binary trees are permitted.'
+                             '  This node has one child.')
+        if count < 1:
+            raise ValueError('A cluster must contain at least one original '
+                             'observation.')
+        self.id = id
+        self.left = left
+        self.right = right
+        self.dist = dist
+        if self.left is None:
+            self.count = count
+        else:
+            self.count = left.count + right.count
+
+    def __lt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist < node.dist
+
+    def __gt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist > node.dist
+
+    def __eq__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist == node.dist
+
+    def get_id(self):
+        """
+        The identifier of the target node.
+
+        For ``0 <= i < n``, `i` corresponds to original observation i.
+        For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed
+        at iteration ``i-n``.
+
+        Returns
+        -------
+        id : int
+            The identifier of the target node.
+
+        """
+        return self.id
+
+    def get_count(self):
+        """
+        The number of leaf nodes (original observations) belonging to
+        the cluster node nd. If the target node is a leaf, 1 is
+        returned.
+
+        Returns
+        -------
+        get_count : int
+            The number of leaf nodes below the target node.
+
+        """
+        return self.count
+
+    def get_left(self):
+        """
+        Return a reference to the left child tree object.
+
+        Returns
+        -------
+        left : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.left
+
+    def get_right(self):
+        """
+        Return a reference to the right child tree object.
+
+        Returns
+        -------
+        right : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.right
+
+    def is_leaf(self):
+        """
+        Return True if the target node is a leaf.
+
+        Returns
+        -------
+        leafness : bool
+            True if the target node is a leaf node.
+
+        """
+        return self.left is None
+
+    def pre_order(self, func=(lambda x: x.id)):
+        """
+        Perform pre-order traversal without recursive function calls.
+
+        When a leaf node is first encountered, ``func`` is called with
+        the leaf node as its argument, and its result is appended to
+        the list.
+
+        For example, the statement::
+
+           ids = root.pre_order(lambda x: x.id)
+
+        returns a list of the node ids corresponding to the leaf nodes
+        of the tree as they appear from left to right.
+
+        Parameters
+        ----------
+        func : function
+            Applied to each leaf ClusterNode object in the pre-order traversal.
+            Given the ``i``-th leaf node in the pre-order traversal ``n[i]``,
+            the result of ``func(n[i])`` is stored in ``L[i]``. If not
+            provided, the index of the original observation to which the node
+            corresponds is used.
+
+        Returns
+        -------
+        L : list
+            The pre-order traversal.
+
+        """
+        # Do a preorder traversal, caching the result. To avoid having to do
+        # recursion, we'll store the previous index we've visited in a vector.
+        n = self.count
+
+        curNode = [None] * (2 * n)
+        lvisited = set()
+        rvisited = set()
+        curNode[0] = self
+        k = 0
+        preorder = []
+        while k >= 0:
+            nd = curNode[k]
+            ndid = nd.id
+            if nd.is_leaf():
+                preorder.append(func(nd))
+                k = k - 1
+            else:
+                if ndid not in lvisited:
+                    curNode[k + 1] = nd.left
+                    lvisited.add(ndid)
+                    k = k + 1
+                elif ndid not in rvisited:
+                    curNode[k + 1] = nd.right
+                    rvisited.add(ndid)
+                    k = k + 1
+                # If we've visited the left and right of this non-leaf
+                # node already, go up in the tree.
+                else:
+                    k = k - 1
+
+        return preorder
+
+
+_cnode_bare = ClusterNode(0)
+_cnode_type = type(ClusterNode)
+
+
+def _order_cluster_tree(Z):
+    """
+    Return clustering nodes in bottom-up order by distance.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+
+    Returns
+    -------
+    nodes : list
+        A list of ClusterNode objects.
+    """
+    q = deque()
+    tree = to_tree(Z)
+    q.append(tree)
+    nodes = []
+
+    while q:
+        node = q.popleft()
+        if not node.is_leaf():
+            bisect.insort_left(nodes, node)
+            q.append(node.get_right())
+            q.append(node.get_left())
+    return nodes
+
+
+def cut_tree(Z, n_clusters=None, height=None):
+    """
+    Given a linkage matrix Z, return the cut tree.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+    n_clusters : array_like, optional
+        Number of clusters in the tree at the cut point.
+    height : array_like, optional
+        The height at which to cut the tree. Only possible for ultrametric
+        trees.
+
+    Returns
+    -------
+    cutree : array
+        An array indicating group membership at each agglomeration step. I.e.,
+        for a full cut tree, in the first column each data point is in its own
+        cluster. At the next step, two nodes are merged. Finally, all
+        singleton and non-singleton clusters are in one group. If `n_clusters`
+        or `height` are given, the columns correspond to the columns of
+        `n_clusters` or `height`.
+
+    Examples
+    --------
+    >>> from scipy import cluster
+    >>> import numpy as np
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> X = rng.random((50, 4))
+    >>> Z = cluster.hierarchy.ward(X)
+    >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10])
+    >>> cutree[:10]
+    array([[0, 0],
+           [1, 1],
+           [2, 2],
+           [3, 3],
+           [3, 4],
+           [2, 2],
+           [0, 0],
+           [1, 5],
+           [3, 6],
+           [4, 7]])  # random
+
+    """
+    xp = array_namespace(Z)
+    nobs = num_obs_linkage(Z)
+    nodes = _order_cluster_tree(Z)
+
+    if height is not None and n_clusters is not None:
+        raise ValueError("At least one of either height or n_clusters "
+                         "must be None")
+    elif height is None and n_clusters is None:  # return the full cut tree
+        cols_idx = xp.arange(nobs)
+    elif height is not None:
+        height = xp.asarray(height)
+        heights = xp.asarray([x.dist for x in nodes])
+        cols_idx = xp.searchsorted(heights, height)
+    else:
+        n_clusters = xp.asarray(n_clusters)
+        cols_idx = nobs - xp.searchsorted(xp.arange(nobs), n_clusters)
+
+    try:
+        n_cols = len(cols_idx)
+    except TypeError:  # scalar
+        n_cols = 1
+        cols_idx = xp.asarray([cols_idx])
+
+    groups = xp.zeros((n_cols, nobs), dtype=xp.int64)
+    last_group = xp.arange(nobs)
+    if 0 in cols_idx:
+        groups[0] = last_group
+
+    for i, node in enumerate(nodes):
+        idx = node.pre_order()
+        this_group = xp_copy(last_group, xp=xp)
+        # TODO ARRAY_API complex indexing not supported
+        this_group[idx] = xp.min(last_group[idx])
+        this_group[this_group > xp.max(last_group[idx])] -= 1
+        if i + 1 in cols_idx:
+            groups[np.nonzero(i + 1 == cols_idx)[0]] = this_group
+        last_group = this_group
+
+    return groups.T
+
+
+def to_tree(Z, rd=False):
+    """
+    Convert a linkage matrix into an easy-to-use tree object.
+
+    The reference to the root `ClusterNode` object is returned (by default).
+
+    Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``,
+    and ``count`` attribute. The left and right attributes point to
+    ClusterNode objects that were combined to generate the cluster.
+    If both are None then the `ClusterNode` object is a leaf node, its count
+    must be 1, and its distance is meaningless but set to 0.
+
+    *Note: This function is provided for the convenience of the library
+    user. ClusterNodes are not used as input to any of the functions in this
+    library.*
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix in proper form (see the `linkage`
+        function documentation).
+    rd : bool, optional
+        When False (default), a reference to the root `ClusterNode` object is
+        returned.  Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a
+        reference to the root node while ``d`` is a list of `ClusterNode`
+        objects - one per original entry in the linkage matrix plus entries
+        for all clustering steps. If a cluster id is
+        less than the number of samples ``n`` in the data that the linkage
+        matrix describes, then it corresponds to a singleton cluster (leaf
+        node).
+        See `linkage` for more information on the assignment of cluster ids
+        to clusters.
+
+    Returns
+    -------
+    tree : ClusterNode or tuple (ClusterNode, list of ClusterNode)
+        If ``rd`` is False, a `ClusterNode`.
+        If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number
+        of samples.  See the description of `rd` above for more details.
+
+    See Also
+    --------
+    linkage, is_valid_linkage, ClusterNode
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random((5, 2))
+    >>> Z = hierarchy.linkage(x)
+    >>> hierarchy.to_tree(Z)
+    >> rootnode, nodelist = hierarchy.to_tree(Z, rd=True)
+    >>> rootnode
+    >> len(nodelist)
+    9
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='c', xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    # Number of original objects is equal to the number of rows plus 1.
+    n = Z.shape[0] + 1
+
+    # Create a list full of None's to store the node objects
+    d = [None] * (n * 2 - 1)
+
+    # Create the nodes corresponding to the n original objects.
+    for i in range(0, n):
+        d[i] = ClusterNode(i)
+
+    nd = None
+
+    for i in range(Z.shape[0]):
+        row = Z[i, :]
+
+        fi = int_floor(row[0], xp)
+        fj = int_floor(row[1], xp)
+        if fi > i + n:
+            raise ValueError(('Corrupt matrix Z. Index to derivative cluster '
+                              'is used before it is formed. See row %d, '
+                              'column 0') % fi)
+        if fj > i + n:
+            raise ValueError(('Corrupt matrix Z. Index to derivative cluster '
+                              'is used before it is formed. See row %d, '
+                              'column 1') % fj)
+
+        nd = ClusterNode(i + n, d[fi], d[fj], row[2])
+        #                ^ id   ^ left ^ right ^ dist
+        if row[3] != nd.count:
+            raise ValueError(('Corrupt matrix Z. The count Z[%d,3] is '
+                              'incorrect.') % i)
+        d[n + i] = nd
+
+    if rd:
+        return (nd, d)
+    else:
+        return nd
+
+
+def optimal_leaf_ordering(Z, y, metric='euclidean'):
+    """
+    Given a linkage matrix Z and distance, reorder the cut tree.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+    y : ndarray
+        The condensed distance matrix from which Z was generated.
+        Alternatively, a collection of m observation vectors in n
+        dimensions may be passed as an m by n array.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+
+    Returns
+    -------
+    Z_ordered : ndarray
+        A copy of the linkage matrix Z, reordered to minimize the distance
+        between adjacent leaves.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> X = rng.standard_normal((10, 10))
+    >>> Z = hierarchy.ward(X)
+    >>> hierarchy.leaves_list(Z)
+    array([0, 3, 1, 9, 2, 5, 7, 4, 6, 8], dtype=int32)
+    >>> hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, X))
+    array([3, 0, 2, 5, 7, 4, 8, 6, 9, 1], dtype=int32)
+
+    """
+    xp = array_namespace(Z, y)
+    Z = _asarray(Z, order='C', xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (y.shape[0] == y.shape[1] and np.allclose(np.diag(y), 0) and
+                np.all(y >= 0) and np.allclose(y, y.T)):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+        y = xp.asarray(y)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+
+    if not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    Z = np.asarray(Z)
+    y = np.asarray(y)
+    return xp.asarray(_optimal_leaf_ordering.optimal_leaf_ordering(Z, y))
+
+
+def cophenet(Z, Y=None):
+    """
+    Calculate the cophenetic distances between each observation in
+    the hierarchical clustering defined by the linkage ``Z``.
+
+    Suppose ``p`` and ``q`` are original observations in
+    disjoint clusters ``s`` and ``t``, respectively and
+    ``s`` and ``t`` are joined by a direct parent cluster
+    ``u``. The cophenetic distance between observations
+    ``i`` and ``j`` is simply the distance between
+    clusters ``s`` and ``t``.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as an array
+        (see `linkage` function).
+    Y : ndarray (optional)
+        Calculates the cophenetic correlation coefficient ``c`` of a
+        hierarchical clustering defined by the linkage matrix `Z`
+        of a set of :math:`n` observations in :math:`m`
+        dimensions. `Y` is the condensed distance matrix from which
+        `Z` was generated.
+
+    Returns
+    -------
+    c : ndarray
+        The cophentic correlation distance (if ``Y`` is passed).
+    d : ndarray
+        The cophenetic distance matrix in condensed form. The
+        :math:`ij` th entry is the cophenetic distance between
+        original observations :math:`i` and :math:`j`.
+
+    See Also
+    --------
+    linkage :
+        for a description of what a linkage matrix is.
+    scipy.spatial.distance.squareform :
+        transforming condensed matrices into square ones.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, cophenet
+    >>> from scipy.spatial.distance import pdist, squareform
+
+    Given a dataset ``X`` and a linkage matrix ``Z``, the cophenetic distance
+    between two points of ``X`` is the distance between the largest two
+    distinct clusters that each of the points:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    ``X`` corresponds to this dataset ::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> Z = single(pdist(X))
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+    >>> cophenet(Z)
+    array([1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 2., 2., 2., 2., 2.,
+           2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 2., 2.,
+           2., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
+           1., 1., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 1., 1., 1.])
+
+    The output of the `scipy.cluster.hierarchy.cophenet` method is
+    represented in condensed form. We can use
+    `scipy.spatial.distance.squareform` to see the output as a
+    regular matrix (where each element ``ij`` denotes the cophenetic distance
+    between each ``i``, ``j`` pair of points in ``X``):
+
+    >>> squareform(cophenet(Z))
+    array([[0., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 0., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 1., 0., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 0., 1., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 0., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 1., 0., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 0., 1., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 0., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 1., 0., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 1., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 0., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 0.]])
+
+    In this example, the cophenetic distance between points on ``X`` that are
+    very close (i.e., in the same corner) is 1. For other pairs of points is 2,
+    because the points will be located in clusters at different
+    corners - thus, the distance between these clusters will be larger.
+
+    """
+    xp = array_namespace(Z, Y)
+    # Ensure float64 C-contiguous array. Cython code doesn't deal with striding.
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+    n = Z.shape[0] + 1
+    zz = np.zeros((n * (n-1)) // 2, dtype=np.float64)
+
+    Z = np.asarray(Z)
+    _hierarchy.cophenetic_distances(Z, zz, int(n))
+    zz = xp.asarray(zz)
+    if Y is None:
+        return zz
+
+    Y = _asarray(Y, order='C', xp=xp)
+    distance.is_valid_y(Y, throw=True, name='Y')
+
+    z = xp.mean(zz)
+    y = xp.mean(Y)
+    Yy = Y - y
+    Zz = zz - z
+    numerator = (Yy * Zz)
+    denomA = Yy**2
+    denomB = Zz**2
+    c = xp.sum(numerator) / xp.sqrt(xp.sum(denomA) * xp.sum(denomB))
+    return (c, zz)
+
+
+def inconsistent(Z, d=2):
+    r"""
+    Calculate inconsistency statistics on a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical
+        clustering).  See `linkage` documentation for more information on its
+        form.
+    d : int, optional
+        The number of links up to `d` levels below each non-singleton cluster.
+
+    Returns
+    -------
+    R : ndarray
+        A :math:`(n-1)` by 4 matrix where the ``i``'th row contains the link
+        statistics for the non-singleton cluster ``i``. The link statistics are
+        computed over the link heights for links :math:`d` levels below the
+        cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard
+        deviation of the link heights, respectively; ``R[i,2]`` is the number
+        of links included in the calculation; and ``R[i,3]`` is the
+        inconsistency coefficient,
+
+        .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]}
+
+    Notes
+    -----
+    This function behaves similarly to the MATLAB(TM) ``inconsistent``
+    function.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import inconsistent, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+    >>> Z = linkage(X, 'ward')
+    >>> print(Z)
+    [[ 5.          6.          0.          2.        ]
+     [ 2.          7.          0.          2.        ]
+     [ 0.          4.          1.          2.        ]
+     [ 1.          8.          1.15470054  3.        ]
+     [ 9.         10.          2.12132034  4.        ]
+     [ 3.         12.          4.11096096  5.        ]
+     [11.         13.         14.07183949  8.        ]]
+    >>> inconsistent(Z)
+    array([[ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 1.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.57735027,  0.81649658,  2.        ,  0.70710678],
+           [ 1.04044011,  1.06123822,  3.        ,  1.01850858],
+           [ 3.11614065,  1.40688837,  2.        ,  0.70710678],
+           [ 6.44583366,  6.76770586,  3.        ,  1.12682288]])
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    if (not d == np.floor(d)) or d < 0:
+        raise ValueError('The second argument d must be a nonnegative '
+                         'integer value.')
+
+    n = Z.shape[0] + 1
+    R = np.zeros((n - 1, 4), dtype=np.float64)
+
+    Z = np.asarray(Z)
+    _hierarchy.inconsistent(Z, R, int(n), int(d))
+    R = xp.asarray(R)
+    return R
+
+
+def from_mlab_linkage(Z):
+    """
+    Convert a linkage matrix generated by MATLAB(TM) to a new
+    linkage matrix compatible with this module.
+
+    The conversion does two things:
+
+     * the indices are converted from ``1..N`` to ``0..(N-1)`` form,
+       and
+
+     * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the
+       number of original observations (leaves) in the non-singleton
+       cluster ``i``.
+
+    This function is useful when loading in linkages from legacy data
+    files generated by MATLAB.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by MATLAB(TM).
+
+    Returns
+    -------
+    ZS : ndarray
+        A linkage matrix compatible with ``scipy.cluster.hierarchy``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    to_mlab_linkage : transform from SciPy to MATLAB format.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage
+
+    Given a linkage matrix in MATLAB format ``mZ``, we can use
+    `scipy.cluster.hierarchy.from_mlab_linkage` to import
+    it into SciPy format:
+
+    >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1],
+    ...                [10, 11, 1], [3, 13, 1.29099445],
+    ...                [6, 14, 1.29099445],
+    ...                [9, 15, 1.29099445],
+    ...                [12, 16, 1.29099445],
+    ...                [17, 18, 5.77350269],
+    ...                [19, 20, 5.77350269],
+    ...                [21, 22,  8.16496581]])
+
+    >>> Z = from_mlab_linkage(mZ)
+    >>> Z
+    array([[  0.        ,   1.        ,   1.        ,   2.        ],
+           [  3.        ,   4.        ,   1.        ,   2.        ],
+           [  6.        ,   7.        ,   1.        ,   2.        ],
+           [  9.        ,  10.        ,   1.        ,   2.        ],
+           [  2.        ,  12.        ,   1.29099445,   3.        ],
+           [  5.        ,  13.        ,   1.29099445,   3.        ],
+           [  8.        ,  14.        ,   1.29099445,   3.        ],
+           [ 11.        ,  15.        ,   1.29099445,   3.        ],
+           [ 16.        ,  17.        ,   5.77350269,   6.        ],
+           [ 18.        ,  19.        ,   5.77350269,   6.        ],
+           [ 20.        ,  21.        ,   8.16496581,  12.        ]])
+
+    As expected, the linkage matrix ``Z`` returned includes an
+    additional column counting the number of original samples in
+    each cluster. Also, all cluster indices are reduced by 1
+    (MATLAB format uses 1-indexing, whereas SciPy uses 0-indexing).
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, order='C', xp=xp)
+    Zs = Z.shape
+
+    # If it's empty, return it.
+    if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0):
+        return xp_copy(Z, xp=xp)
+
+    if len(Zs) != 2:
+        raise ValueError("The linkage array must be rectangular.")
+
+    # If it contains no rows, return it.
+    if Zs[0] == 0:
+        return xp_copy(Z, xp=xp)
+
+    if xp.min(Z[:, 0:2]) != 1.0 and xp.max(Z[:, 0:2]) != 2 * Zs[0]:
+        raise ValueError('The format of the indices is not 1..N')
+
+    Zpart = xp.concat((Z[:, 0:2] - 1.0, Z[:, 2:]), axis=1)
+    CS = np.zeros((Zs[0],), dtype=np.float64)
+    if is_jax(xp):
+        # calculate_cluster_sizes doesn't accept read-only arrays
+        Zpart = np.array(Zpart, copy=True)
+    else:
+        Zpart = np.asarray(Zpart)
+    _hierarchy.calculate_cluster_sizes(Zpart, CS, int(Zs[0]) + 1)
+    res = np.hstack([Zpart, CS.reshape(Zs[0], 1)])
+    return xp.asarray(res)
+
+
+def to_mlab_linkage(Z):
+    """
+    Convert a linkage matrix to a MATLAB(TM) compatible one.
+
+    Converts a linkage matrix ``Z`` generated by the linkage function
+    of this module to a MATLAB(TM) compatible one. The return linkage
+    matrix has the last column removed and the cluster indices are
+    converted to ``1..N`` indexing.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by ``scipy.cluster.hierarchy``.
+
+    Returns
+    -------
+    to_mlab_linkage : ndarray
+        A linkage matrix compatible with MATLAB(TM)'s hierarchical
+        clustering functions.
+
+        The return linkage matrix has the last column removed
+        and the cluster indices are converted to ``1..N`` indexing.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    from_mlab_linkage : transform from Matlab to SciPy format.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, to_mlab_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    After a linkage matrix ``Z`` has been created, we can use
+    `scipy.cluster.hierarchy.to_mlab_linkage` to convert it
+    into MATLAB format:
+
+    >>> mZ = to_mlab_linkage(Z)
+    >>> mZ
+    array([[  1.        ,   2.        ,   1.        ],
+           [  4.        ,   5.        ,   1.        ],
+           [  7.        ,   8.        ,   1.        ],
+           [ 10.        ,  11.        ,   1.        ],
+           [  3.        ,  13.        ,   1.29099445],
+           [  6.        ,  14.        ,   1.29099445],
+           [  9.        ,  15.        ,   1.29099445],
+           [ 12.        ,  16.        ,   1.29099445],
+           [ 17.        ,  18.        ,   5.77350269],
+           [ 19.        ,  20.        ,   5.77350269],
+           [ 21.        ,  22.        ,   8.16496581]])
+
+    The new linkage matrix ``mZ`` uses 1-indexing for all the
+    clusters (instead of 0-indexing). Also, the last column of
+    the original linkage matrix has been dropped.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    Zs = Z.shape
+    if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0):
+        return xp_copy(Z, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    return xp.concat((Z[:, :2] + 1.0, Z[:, 2:3]), axis=1)
+
+
+def is_monotonic(Z):
+    """
+    Return True if the linkage passed is monotonic.
+
+    The linkage is monotonic if for every cluster :math:`s` and :math:`t`
+    joined, the distance between them is no less than the distance
+    between any previously joined clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix to check for monotonicity.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage is monotonic.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, ward, is_monotonic
+    >>> from scipy.spatial.distance import pdist
+
+    By definition, some hierarchical clustering algorithms - such as
+    `scipy.cluster.hierarchy.ward` - produce monotonic assignments of
+    samples to clusters; however, this is not always true for other
+    hierarchical methods - e.g. `scipy.cluster.hierarchy.median`.
+
+    Given a linkage matrix ``Z`` (as the result of a hierarchical clustering
+    method) we can test programmatically whether it has the monotonicity
+    property or not, using `scipy.cluster.hierarchy.is_monotonic`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_monotonic(Z)
+    True
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> is_monotonic(Z)
+    False
+
+    Note that this method is equivalent to just verifying that the distances
+    in the third column of the linkage matrix appear in a monotonically
+    increasing order.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='c', xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    # We expect the i'th value to be greater than its successor.
+    return xp.all(Z[1:, 2] >= Z[:-1, 2])
+
+
+def is_valid_im(R, warning=False, throw=False, name=None):
+    """Return True if the inconsistency matrix passed is valid.
+
+    It must be a :math:`n` by 4 array of doubles. The standard
+    deviations ``R[:,1]`` must be nonnegative. The link counts
+    ``R[:,2]`` must be positive and no greater than :math:`n-1`.
+
+    Parameters
+    ----------
+    R : ndarray
+        The inconsistency matrix to check for validity.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, inconsistent, is_valid_im
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [6.57065706, 1.38071187, 3.        , 1.15470054]])
+
+    Now we can use `scipy.cluster.hierarchy.is_valid_im` to verify that
+    ``R`` is correct:
+
+    >>> is_valid_im(R)
+    True
+
+    However, if ``R`` is wrongly constructed (e.g., one of the standard
+    deviations is set to a negative value), then the check will fail:
+
+    >>> R[-1,1] = R[-1,1] * -1
+    >>> is_valid_im(R)
+    False
+
+    """
+    xp = array_namespace(R)
+    R = _asarray(R, order='c', xp=xp)
+    valid = True
+    name_str = f"{name!r} " if name else ''
+    try:
+        if R.dtype != xp.float64:
+            raise TypeError(f'Inconsistency matrix {name_str}must contain doubles '
+                            '(double).')
+        if len(R.shape) != 2:
+            raise ValueError(f'Inconsistency matrix {name_str}must have shape=2 (i.e. '
+                             'be two-dimensional).')
+        if R.shape[1] != 4:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have 4 columns.')
+        if R.shape[0] < 1:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have at least one row.')
+        if xp.any(R[:, 0] < 0):
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'contains negative link height means.')
+        if xp.any(R[:, 1] < 0):
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'contains negative link height standard deviations.')
+        if xp.any(R[:, 2] < 0):
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'contains negative link counts.')
+    except Exception as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        valid = False
+
+    return valid
+
+
+def is_valid_linkage(Z, warning=False, throw=False, name=None):
+    """
+    Check the validity of a linkage matrix.
+
+    A linkage matrix is valid if it is a 2-D array (type double)
+    with :math:`n` rows and 4 columns. The first two columns must contain
+    indices between 0 and :math:`2n-1`. For a given row ``i``, the following
+    two expressions have to hold:
+
+    .. math::
+
+        0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1
+        0 \\leq Z[i,1] \\leq i+n-1
+
+    I.e., a cluster cannot join another cluster unless the cluster being joined
+    has been generated.
+
+    The fourth column of `Z` represents the number of original observations
+    in a cluster, so a valid ``Z[i, 3]`` value may not exceed the number of
+    original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        Linkage matrix.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid.
+
+    See Also
+    --------
+    linkage: for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, is_valid_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    All linkage matrices generated by the clustering methods in this module
+    will be valid (i.e., they will have the appropriate dimensions and the two
+    required expressions will hold for all the rows).
+
+    We can check this using `scipy.cluster.hierarchy.is_valid_linkage`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_valid_linkage(Z)
+    True
+
+    However, if we create a linkage matrix in a wrong way - or if we modify
+    a valid one in a way that any of the required expressions don't hold
+    anymore, then the check will fail:
+
+    >>> Z[3][1] = 20    # the cluster number 20 is not defined at this point
+    >>> is_valid_linkage(Z)
+    False
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='c', xp=xp)
+    valid = True
+    name_str = f"{name!r} " if name else ''
+    try:
+        if Z.dtype != xp.float64:
+            raise TypeError(f'Linkage matrix {name_str}must contain doubles.')
+        if len(Z.shape) != 2:
+            raise ValueError(f'Linkage matrix {name_str}must have shape=2 (i.e. be'
+                             ' two-dimensional).')
+        if Z.shape[1] != 4:
+            raise ValueError(f'Linkage matrix {name_str}must have 4 columns.')
+        if Z.shape[0] == 0:
+            raise ValueError('Linkage must be computed on at least two '
+                             'observations.')
+        n = Z.shape[0]
+        if n > 1:
+            if (xp.any(Z[:, 0] < 0) or xp.any(Z[:, 1] < 0)):
+                raise ValueError(f'Linkage {name_str}contains negative indices.')
+            if xp.any(Z[:, 2] < 0):
+                raise ValueError(f'Linkage {name_str}contains negative distances.')
+            if xp.any(Z[:, 3] < 0):
+                raise ValueError(f'Linkage {name_str}contains negative counts.')
+            if xp.any(Z[:, 3] > (Z.shape[0] + 1)):
+                raise ValueError('Linkage matrix contains excessive observations'
+                                 'in a cluster')
+        if _check_hierarchy_uses_cluster_before_formed(Z):
+            raise ValueError(f'Linkage {name_str}uses non-singleton cluster before'
+                             ' it is formed.')
+        if _check_hierarchy_uses_cluster_more_than_once(Z):
+            raise ValueError(f'Linkage {name_str}uses the same cluster more than once.')
+    except Exception as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        valid = False
+
+    return valid
+
+
+def _check_hierarchy_uses_cluster_before_formed(Z):
+    n = Z.shape[0] + 1
+    for i in range(0, n - 1):
+        if Z[i, 0] >= n + i or Z[i, 1] >= n + i:
+            return True
+    return False
+
+
+def _check_hierarchy_uses_cluster_more_than_once(Z):
+    n = Z.shape[0] + 1
+    chosen = set()
+    for i in range(0, n - 1):
+        used_more_than_once = (
+            (float(Z[i, 0]) in chosen)
+            or (float(Z[i, 1]) in chosen)
+            or Z[i, 0] == Z[i, 1]
+        )
+        if used_more_than_once:
+            return True
+        chosen.add(float(Z[i, 0]))
+        chosen.add(float(Z[i, 1]))
+    return False
+
+
+def _check_hierarchy_not_all_clusters_used(Z):
+    n = Z.shape[0] + 1
+    chosen = set()
+    for i in range(0, n - 1):
+        chosen.add(int(Z[i, 0]))
+        chosen.add(int(Z[i, 1]))
+    must_chosen = set(range(0, 2 * n - 2))
+    return len(must_chosen.difference(chosen)) > 0
+
+
+def num_obs_linkage(Z):
+    """
+    Return the number of original observations of the linkage matrix passed.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix on which to perform the operation.
+
+    Returns
+    -------
+    n : int
+        The number of original observations in the linkage.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, num_obs_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    ``Z`` is a linkage matrix obtained after using the Ward clustering method
+    with ``X``, a dataset with 12 data points.
+
+    >>> num_obs_linkage(Z)
+    12
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='c', xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+    return (Z.shape[0] + 1)
+
+
+def correspond(Z, Y):
+    """
+    Check for correspondence between linkage and condensed distance matrices.
+
+    They must have the same number of original observations for
+    the check to succeed.
+
+    This function is useful as a sanity check in algorithms that make
+    extensive use of linkage and distance matrices that must
+    correspond to the same set of original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        The linkage matrix to check for correspondence.
+    Y : array_like
+        The condensed distance matrix to check for correspondence.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage matrix and distance
+        matrix could possibly correspond to one another.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, correspond
+    >>> from scipy.spatial.distance import pdist
+
+    This method can be used to check if a given linkage matrix ``Z`` has been
+    obtained from the application of a cluster method over a dataset ``X``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+    >>> X_condensed = pdist(X)
+    >>> Z = ward(X_condensed)
+
+    Here, we can compare ``Z`` and ``X`` (in condensed form):
+
+    >>> correspond(Z, X_condensed)
+    True
+
+    """
+    is_valid_linkage(Z, throw=True)
+    distance.is_valid_y(Y, throw=True)
+    xp = array_namespace(Z, Y)
+    Z = _asarray(Z, order='c', xp=xp)
+    Y = _asarray(Y, order='c', xp=xp)
+    return distance.num_obs_y(Y) == num_obs_linkage(Z)
+
+
+def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None):
+    """
+    Form flat clusters from the hierarchical clustering defined by
+    the given linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded with the matrix returned
+        by the `linkage` function.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        The criterion to use in forming flat clusters. This can
+        be any of the following values:
+
+          ``inconsistent`` :
+              If a cluster node and all its
+              descendants have an inconsistent value less than or equal
+              to `t`, then all its leaf descendants belong to the
+              same flat cluster. When no non-singleton cluster meets
+              this criterion, every node is assigned to its own
+              cluster. (Default)
+
+          ``distance`` :
+              Forms flat clusters so that the original
+              observations in each flat cluster have no greater a
+              cophenetic distance than `t`.
+
+          ``maxclust`` :
+              Finds a minimum threshold ``r`` so that
+              the cophenetic distance between any two original
+              observations in the same flat cluster is no more than
+              ``r`` and no more than `t` flat clusters are formed.
+
+          ``monocrit`` :
+              Forms a flat cluster from a cluster node c
+              with index i when ``monocrit[j] <= t``.
+
+              For example, to threshold on the maximum mean distance
+              as computed in the inconsistency matrix R with a
+              threshold of 0.8 do::
+
+                  MR = maxRstat(Z, R, 3)
+                  fcluster(Z, t=0.8, criterion='monocrit', monocrit=MR)
+
+          ``maxclust_monocrit`` :
+              Forms a flat cluster from a
+              non-singleton cluster node ``c`` when ``monocrit[i] <=
+              r`` for all cluster indices ``i`` below and including
+              ``c``. ``r`` is minimized such that no more than ``t``
+              flat clusters are formed. monocrit must be
+              monotonic. For example, to minimize the threshold t on
+              maximum inconsistency values so that no more than 3 flat
+              clusters are formed, do::
+
+                  MI = maxinconsts(Z, R)
+                  fcluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI)
+    depth : int, optional
+        The maximum depth to perform the inconsistency calculation.
+        It has no meaning for the other criteria. Default is 2.
+    R : ndarray, optional
+        The inconsistency matrix to use for the ``'inconsistent'``
+        criterion. This matrix is computed if not provided.
+    monocrit : ndarray, optional
+        An array of length n-1. `monocrit[i]` is the
+        statistics upon which non-singleton i is thresholded. The
+        monocrit vector must be monotonic, i.e., given a node c with
+        index i, for all node indices j corresponding to nodes
+        below c, ``monocrit[i] >= monocrit[j]``.
+
+    Returns
+    -------
+    fcluster : ndarray
+        An array of length ``n``. ``T[i]`` is the flat cluster number to
+        which original observation ``i`` belongs.
+
+    See Also
+    --------
+    linkage : for information about hierarchical clustering methods work.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    All cluster linkage methods - e.g., `scipy.cluster.hierarchy.ward`
+    generate a linkage matrix ``Z`` as their output:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    This matrix represents a dendrogram, where the first and second elements
+    are the two clusters merged at each step, the third element is the
+    distance between these clusters, and the fourth element is the size of
+    the new cluster - the number of original data points included.
+
+    `scipy.cluster.hierarchy.fcluster` can be used to flatten the
+    dendrogram, obtaining as a result an assignation of the original data
+    points to single clusters.
+
+    This assignation mostly depends on a distance threshold ``t`` - the maximum
+    inter-cluster distance allowed:
+
+    >>> fcluster(Z, t=0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+
+    >>> fcluster(Z, t=1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+
+    >>> fcluster(Z, t=3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    >>> fcluster(Z, t=9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    In the first case, the threshold ``t`` is too small to allow any two
+    samples in the data to form a cluster, so 12 different clusters are
+    returned.
+
+    In the second case, the threshold is large enough to allow the first
+    4 points to be merged with their nearest neighbors. So, here, only 8
+    clusters are returned.
+
+    The third case, with a much higher threshold, allows for up to 8 data
+    points to be connected - so 4 clusters are returned here.
+
+    Lastly, the threshold of the fourth case is large enough to allow for
+    all data points to be merged together - so a single cluster is returned.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    n = Z.shape[0] + 1
+    T = np.zeros((n,), dtype='i')
+
+    if monocrit is not None:
+        monocrit = np.asarray(monocrit, order='C', dtype=np.float64)
+
+    Z = np.asarray(Z)
+    monocrit = np.asarray(monocrit)
+    if criterion == 'inconsistent':
+        if R is None:
+            R = inconsistent(Z, depth)
+        else:
+            R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+            is_valid_im(R, throw=True, name='R')
+            # Since the C code does not support striding using strides.
+            # The dimensions are used instead.
+            R = np.asarray(R)
+        _hierarchy.cluster_in(Z, R, T, float(t), int(n))
+    elif criterion == 'distance':
+        _hierarchy.cluster_dist(Z, T, float(t), int(n))
+    elif criterion == 'maxclust':
+        _hierarchy.cluster_maxclust_dist(Z, T, int(n), t)
+    elif criterion == 'monocrit':
+        _hierarchy.cluster_monocrit(Z, monocrit, T, float(t), int(n))
+    elif criterion == 'maxclust_monocrit':
+        _hierarchy.cluster_maxclust_monocrit(Z, monocrit, T, int(n), int(t))
+    else:
+        raise ValueError(f'Invalid cluster formation criterion: {str(criterion)}')
+    return xp.asarray(T)
+
+
+def fclusterdata(X, t, criterion='inconsistent',
+                 metric='euclidean', depth=2, method='single', R=None):
+    """
+    Cluster observation data using a given metric.
+
+    Clusters the original observations in the n-by-m data
+    matrix X (n observations in m dimensions), using the euclidean
+    distance metric to calculate distances between original observations,
+    performs hierarchical clustering using the single linkage algorithm,
+    and forms flat clusters using the inconsistency method with `t` as the
+    cut-off threshold.
+
+    A 1-D array ``T`` of length ``n`` is returned. ``T[i]`` is
+    the index of the flat cluster to which the original observation ``i``
+    belongs.
+
+    Parameters
+    ----------
+    X : (N, M) ndarray
+        N by M data matrix with N observations in M dimensions.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        Specifies the criterion for forming flat clusters. Valid
+        values are 'inconsistent' (default), 'distance', or 'maxclust'
+        cluster formation algorithms. See `fcluster` for descriptions.
+    metric : str or function, optional
+        The distance metric for calculating pairwise distances. See
+        ``distance.pdist`` for descriptions and linkage to verify
+        compatibility with the linkage method.
+    depth : int, optional
+        The maximum depth for the inconsistency calculation. See
+        `inconsistent` for more information.
+    method : str, optional
+        The linkage method to use (single, complete, average,
+        weighted, median centroid, ward). See `linkage` for more
+        information. Default is "single".
+    R : ndarray, optional
+        The inconsistency matrix. It will be computed if necessary
+        if it is not passed.
+
+    Returns
+    -------
+    fclusterdata : ndarray
+        A vector of length n. T[i] is the flat cluster number to
+        which original observation i belongs.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Notes
+    -----
+    This function is similar to the MATLAB function ``clusterdata``.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fclusterdata
+
+    This is a convenience method that abstracts all the steps to perform in a
+    typical SciPy's hierarchical clustering workflow.
+
+    * Transform the input data into a condensed matrix with
+      `scipy.spatial.distance.pdist`.
+
+    * Apply a clustering method.
+
+    * Obtain flat clusters at a user defined distance threshold ``t`` using
+      `scipy.cluster.hierarchy.fcluster`.
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> fclusterdata(X, t=1)
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    The output here (for the dataset ``X``, distance threshold ``t``, and the
+    default settings) is four clusters with three data points each.
+
+    """
+    xp = array_namespace(X)
+    X = _asarray(X, order='C', dtype=xp.float64, xp=xp)
+
+    if X.ndim != 2:
+        raise TypeError('The observation matrix X must be an n by m '
+                        'array.')
+
+    Y = distance.pdist(X, metric=metric)
+    Y = xp.asarray(Y)
+    Z = linkage(Y, method=method)
+    if R is None:
+        R = inconsistent(Z, d=depth)
+    else:
+        R = _asarray(R, order='c', xp=xp)
+    T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t)
+    return T
+
+
+def leaves_list(Z):
+    """
+    Return a list of leaf node ids.
+
+    The return corresponds to the observation vector index as it appears
+    in the tree from left to right. Z is a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix.  `Z` is
+        a linkage matrix.  See `linkage` for more information.
+
+    Returns
+    -------
+    leaves_list : ndarray
+        The list of leaf node ids.
+
+    See Also
+    --------
+    dendrogram : for information about dendrogram structure.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, dendrogram, leaves_list
+    >>> from scipy.spatial.distance import pdist
+    >>> from matplotlib import pyplot as plt
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    The linkage matrix ``Z`` represents a dendrogram, that is, a tree that
+    encodes the structure of the clustering performed.
+    `scipy.cluster.hierarchy.leaves_list` shows the mapping between
+    indices in the ``X`` dataset and leaves in the dendrogram:
+
+    >>> leaves_list(Z)
+    array([ 2,  0,  1,  5,  3,  4,  8,  6,  7, 11,  9, 10], dtype=int32)
+
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+    n = Z.shape[0] + 1
+    ML = np.zeros((n,), dtype='i')
+    Z = np.asarray(Z)
+    _hierarchy.prelist(Z, ML, n)
+    return xp.asarray(ML)
+
+
+# Maps number of leaves to text size.
+#
+# p <= 20, size="12"
+# 20 < p <= 30, size="10"
+# 30 < p <= 50, size="8"
+# 50 < p <= np.inf, size="6"
+
+_dtextsizes = {20: 12, 30: 10, 50: 8, 85: 6, np.inf: 5}
+_drotation = {20: 0, 40: 45, np.inf: 90}
+_dtextsortedkeys = list(_dtextsizes.keys())
+_dtextsortedkeys.sort()
+_drotationsortedkeys = list(_drotation.keys())
+_drotationsortedkeys.sort()
+
+
+def _remove_dups(L):
+    """
+    Remove duplicates AND preserve the original order of the elements.
+
+    The set class is not guaranteed to do this.
+    """
+    seen_before = set()
+    L2 = []
+    for i in L:
+        if i not in seen_before:
+            seen_before.add(i)
+            L2.append(i)
+    return L2
+
+
+def _get_tick_text_size(p):
+    for k in _dtextsortedkeys:
+        if p <= k:
+            return _dtextsizes[k]
+
+
+def _get_tick_rotation(p):
+    for k in _drotationsortedkeys:
+        if p <= k:
+            return _drotation[k]
+
+
+def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation,
+                     no_labels, color_list, leaf_font_size=None,
+                     leaf_rotation=None, contraction_marks=None,
+                     ax=None, above_threshold_color='C0'):
+    # Import matplotlib here so that it's not imported unless dendrograms
+    # are plotted. Raise an informative error if importing fails.
+    try:
+        # if an axis is provided, don't use pylab at all
+        if ax is None:
+            import matplotlib.pylab
+        import matplotlib.patches
+        import matplotlib.collections
+    except ImportError as e:
+        raise ImportError("You must install the matplotlib library to plot "
+                          "the dendrogram. Use no_plot=True to calculate the "
+                          "dendrogram without plotting.") from e
+
+    if ax is None:
+        ax = matplotlib.pylab.gca()
+        # if we're using pylab, we want to trigger a draw at the end
+        trigger_redraw = True
+    else:
+        trigger_redraw = False
+
+    # Independent variable plot width
+    ivw = len(ivl) * 10
+    # Dependent variable plot height
+    dvw = mh + mh * 0.05
+
+    iv_ticks = np.arange(5, len(ivl) * 10 + 5, 10)
+    if orientation in ('top', 'bottom'):
+        if orientation == 'top':
+            ax.set_ylim([0, dvw])
+            ax.set_xlim([0, ivw])
+        else:
+            ax.set_ylim([dvw, 0])
+            ax.set_xlim([0, ivw])
+
+        xlines = icoords
+        ylines = dcoords
+        if no_labels:
+            ax.set_xticks([])
+            ax.set_xticklabels([])
+        else:
+            ax.set_xticks(iv_ticks)
+
+            if orientation == 'top':
+                ax.xaxis.set_ticks_position('bottom')
+            else:
+                ax.xaxis.set_ticks_position('top')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_xticklines():
+                line.set_visible(False)
+
+            leaf_rot = (float(_get_tick_rotation(len(ivl)))
+                        if (leaf_rotation is None) else leaf_rotation)
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+            ax.set_xticklabels(ivl, rotation=leaf_rot, size=leaf_font)
+
+    elif orientation in ('left', 'right'):
+        if orientation == 'left':
+            ax.set_xlim([dvw, 0])
+            ax.set_ylim([0, ivw])
+        else:
+            ax.set_xlim([0, dvw])
+            ax.set_ylim([0, ivw])
+
+        xlines = dcoords
+        ylines = icoords
+        if no_labels:
+            ax.set_yticks([])
+            ax.set_yticklabels([])
+        else:
+            ax.set_yticks(iv_ticks)
+
+            if orientation == 'left':
+                ax.yaxis.set_ticks_position('right')
+            else:
+                ax.yaxis.set_ticks_position('left')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_yticklines():
+                line.set_visible(False)
+
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+
+            if leaf_rotation is not None:
+                ax.set_yticklabels(ivl, rotation=leaf_rotation, size=leaf_font)
+            else:
+                ax.set_yticklabels(ivl, size=leaf_font)
+
+    # Let's use collections instead. This way there is a separate legend item
+    # for each tree grouping, rather than stupidly one for each line segment.
+    colors_used = _remove_dups(color_list)
+    color_to_lines = {}
+    for color in colors_used:
+        color_to_lines[color] = []
+    for (xline, yline, color) in zip(xlines, ylines, color_list):
+        color_to_lines[color].append(list(zip(xline, yline)))
+
+    colors_to_collections = {}
+    # Construct the collections.
+    for color in colors_used:
+        coll = matplotlib.collections.LineCollection(color_to_lines[color],
+                                                     colors=(color,))
+        colors_to_collections[color] = coll
+
+    # Add all the groupings below the color threshold.
+    for color in colors_used:
+        if color != above_threshold_color:
+            ax.add_collection(colors_to_collections[color])
+    # If there's a grouping of links above the color threshold, it goes last.
+    if above_threshold_color in colors_to_collections:
+        ax.add_collection(colors_to_collections[above_threshold_color])
+
+    if contraction_marks is not None:
+        Ellipse = matplotlib.patches.Ellipse
+        for (x, y) in contraction_marks:
+            if orientation in ('left', 'right'):
+                e = Ellipse((y, x), width=dvw / 100, height=1.0)
+            else:
+                e = Ellipse((x, y), width=1.0, height=dvw / 100)
+            ax.add_artist(e)
+            e.set_clip_box(ax.bbox)
+            e.set_alpha(0.5)
+            e.set_facecolor('k')
+
+    if trigger_redraw:
+        matplotlib.pylab.draw_if_interactive()
+
+
+# C0  is used for above threshold color
+_link_line_colors_default = ('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9')
+_link_line_colors = list(_link_line_colors_default)
+
+
+def set_link_color_palette(palette):
+    """
+    Set list of matplotlib color codes for use by dendrogram.
+
+    Note that this palette is global (i.e., setting it once changes the colors
+    for all subsequent calls to `dendrogram`) and that it affects only the
+    the colors below ``color_threshold``.
+
+    Note that `dendrogram` also accepts a custom coloring function through its
+    ``link_color_func`` keyword, which is more flexible and non-global.
+
+    Parameters
+    ----------
+    palette : list of str or None
+        A list of matplotlib color codes.  The order of the color codes is the
+        order in which the colors are cycled through when color thresholding in
+        the dendrogram.
+
+        If ``None``, resets the palette to its default (which are matplotlib
+        default colors C1 to C9).
+
+    Returns
+    -------
+    None
+
+    See Also
+    --------
+    dendrogram
+
+    Notes
+    -----
+    Ability to reset the palette with ``None`` added in SciPy 0.17.0.
+
+    Thread safety: using this function in a multi-threaded fashion may
+    result in `dendrogram` producing plots with unexpected colors.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True)
+    >>> dn['color_list']
+    ['C1', 'C0', 'C0', 'C0', 'C0']
+    >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k'])
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, above_threshold_color='b')
+    >>> dn['color_list']
+    ['c', 'b', 'b', 'b', 'b']
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267,
+    ...                           above_threshold_color='k')
+    >>> dn['color_list']
+    ['c', 'm', 'm', 'k', 'k']
+
+    Now, reset the color palette to its default:
+
+    >>> hierarchy.set_link_color_palette(None)
+
+    """
+    if palette is None:
+        # reset to its default
+        palette = _link_line_colors_default
+    elif not isinstance(palette, (list, tuple)):
+        raise TypeError("palette must be a list or tuple")
+    _ptypes = [isinstance(p, str) for p in palette]
+
+    if False in _ptypes:
+        raise TypeError("all palette list elements must be color strings")
+
+    global _link_line_colors
+    _link_line_colors = palette
+
+
+def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None,
+               get_leaves=True, orientation='top', labels=None,
+               count_sort=False, distance_sort=False, show_leaf_counts=True,
+               no_plot=False, no_labels=False, leaf_font_size=None,
+               leaf_rotation=None, leaf_label_func=None,
+               show_contracted=False, link_color_func=None, ax=None,
+               above_threshold_color='C0'):
+    """
+    Plot the hierarchical clustering as a dendrogram.
+
+    The dendrogram illustrates how each cluster is
+    composed by drawing a U-shaped link between a non-singleton
+    cluster and its children. The top of the U-link indicates a
+    cluster merge. The two legs of the U-link indicate which clusters
+    were merged. The length of the two legs of the U-link represents
+    the distance between the child clusters. It is also the
+    cophenetic distance between original observations in the two
+    children clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix encoding the hierarchical clustering to
+        render as a dendrogram. See the ``linkage`` function for more
+        information on the format of ``Z``.
+    p : int, optional
+        The ``p`` parameter for ``truncate_mode``.
+    truncate_mode : str, optional
+        The dendrogram can be hard to read when the original
+        observation matrix from which the linkage is derived is
+        large. Truncation is used to condense the dendrogram. There
+        are several modes:
+
+        ``None``
+          No truncation is performed (default).
+          Note: ``'none'`` is an alias for ``None`` that's kept for
+          backward compatibility.
+
+        ``'lastp'``
+          The last ``p`` non-singleton clusters formed in the linkage are the
+          only non-leaf nodes in the linkage; they correspond to rows
+          ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are
+          contracted into leaf nodes.
+
+        ``'level'``
+          No more than ``p`` levels of the dendrogram tree are displayed.
+          A "level" includes all nodes with ``p`` merges from the final merge.
+
+          Note: ``'mtica'`` is an alias for ``'level'`` that's kept for
+          backward compatibility.
+
+    color_threshold : double, optional
+        For brevity, let :math:`t` be the ``color_threshold``.
+        Colors all the descendent links below a cluster node
+        :math:`k` the same color if :math:`k` is the first node below
+        the cut threshold :math:`t`. All links connecting nodes with
+        distances greater than or equal to the threshold are colored
+        with de default matplotlib color ``'C0'``. If :math:`t` is less
+        than or equal to zero, all nodes are colored ``'C0'``.
+        If ``color_threshold`` is None or 'default',
+        corresponding with MATLAB(TM) behavior, the threshold is set to
+        ``0.7*max(Z[:,2])``.
+
+    get_leaves : bool, optional
+        Includes a list ``R['leaves']=H`` in the result
+        dictionary. For each :math:`i`, ``H[i] == j``, cluster node
+        ``j`` appears in position ``i`` in the left-to-right traversal
+        of the leaves, where :math:`j < 2n-1` and :math:`i < n`.
+    orientation : str, optional
+        The direction to plot the dendrogram, which can be any
+        of the following strings:
+
+        ``'top'``
+          Plots the root at the top, and plot descendent links going downwards.
+          (default).
+
+        ``'bottom'``
+          Plots the root at the bottom, and plot descendent links going
+          upwards.
+
+        ``'left'``
+          Plots the root at the left, and plot descendent links going right.
+
+        ``'right'``
+          Plots the root at the right, and plot descendent links going left.
+
+    labels : ndarray, optional
+        By default, ``labels`` is None so the index of the original observation
+        is used to label the leaf nodes.  Otherwise, this is an :math:`n`-sized
+        sequence, with ``n == Z.shape[0] + 1``. The ``labels[i]`` value is the
+        text to put under the :math:`i` th leaf node only if it corresponds to
+        an original observation and not a non-singleton cluster.
+    count_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum number of original objects in its cluster
+          is plotted first.
+
+        ``'descending'``
+          The child with the maximum number of original objects in its cluster
+          is plotted first.
+
+        Note, ``distance_sort`` and ``count_sort`` cannot both be True.
+    distance_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum distance between its direct descendents is
+          plotted first.
+
+        ``'descending'``
+          The child with the maximum distance between its direct descendents is
+          plotted first.
+
+        Note ``distance_sort`` and ``count_sort`` cannot both be True.
+    show_leaf_counts : bool, optional
+         When True, leaf nodes representing :math:`k>1` original
+         observation are labeled with the number of observations they
+         contain in parentheses.
+    no_plot : bool, optional
+        When True, the final rendering is not performed. This is
+        useful if only the data structures computed for the rendering
+        are needed or if matplotlib is not available.
+    no_labels : bool, optional
+        When True, no labels appear next to the leaf nodes in the
+        rendering of the dendrogram.
+    leaf_rotation : double, optional
+        Specifies the angle (in degrees) to rotate the leaf
+        labels. When unspecified, the rotation is based on the number of
+        nodes in the dendrogram (default is 0).
+    leaf_font_size : int, optional
+        Specifies the font size (in points) of the leaf labels. When
+        unspecified, the size based on the number of nodes in the
+        dendrogram.
+    leaf_label_func : lambda or function, optional
+        When ``leaf_label_func`` is a callable function, for each
+        leaf with cluster index :math:`k < 2n-1`. The function
+        is expected to return a string with the label for the
+        leaf.
+
+        Indices :math:`k < n` correspond to original observations
+        while indices :math:`k \\geq n` correspond to non-singleton
+        clusters.
+
+        For example, to label singletons with their node id and
+        non-singletons with their id, count, and inconsistency
+        coefficient, simply do::
+
+            # First define the leaf label function.
+            def llf(id):
+                if id < n:
+                    return str(id)
+                else:
+                    return '[%d %d %1.2f]' % (id, count, R[n-id,3])
+
+            # The text for the leaf nodes is going to be big so force
+            # a rotation of 90 degrees.
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90)
+
+            # leaf_label_func can also be used together with ``truncate_mode``,
+            # in which case you will get your leaves labeled after truncation:
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90,
+                       truncate_mode='level', p=2)
+
+    show_contracted : bool, optional
+        When True the heights of non-singleton nodes contracted
+        into a leaf node are plotted as crosses along the link
+        connecting that leaf node.  This really is only useful when
+        truncation is used (see ``truncate_mode`` parameter).
+    link_color_func : callable, optional
+        If given, `link_color_function` is called with each non-singleton id
+        corresponding to each U-shaped link it will paint. The function is
+        expected to return the color to paint the link, encoded as a matplotlib
+        color string code. For example::
+
+            dendrogram(Z, link_color_func=lambda k: colors[k])
+
+        colors the direct links below each untruncated non-singleton node
+        ``k`` using ``colors[k]``.
+    ax : matplotlib Axes instance, optional
+        If None and `no_plot` is not True, the dendrogram will be plotted
+        on the current axes.  Otherwise if `no_plot` is not True the
+        dendrogram will be plotted on the given ``Axes`` instance. This can be
+        useful if the dendrogram is part of a more complex figure.
+    above_threshold_color : str, optional
+        This matplotlib color string sets the color of the links above the
+        color_threshold. The default is ``'C0'``.
+
+    Returns
+    -------
+    R : dict
+        A dictionary of data structures computed to render the
+        dendrogram. Its has the following keys:
+
+        ``'color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th link.
+
+        ``'icoord'`` and ``'dcoord'``
+          Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]``
+          where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]``
+          where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is
+          ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``.
+
+        ``'ivl'``
+          A list of labels corresponding to the leaf nodes.
+
+        ``'leaves'``
+          For each i, ``H[i] == j``, cluster node ``j`` appears in position
+          ``i`` in the left-to-right traversal of the leaves, where
+          :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the
+          ``i``-th leaf node corresponds to an original observation.
+          Otherwise, it corresponds to a non-singleton cluster.
+
+        ``'leaves_color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th leaf.
+
+    See Also
+    --------
+    linkage, set_link_color_palette
+
+    Notes
+    -----
+    It is expected that the distances in ``Z[:,2]`` be monotonic, otherwise
+    crossings appear in the dendrogram.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> import matplotlib.pyplot as plt
+
+    A very basic example:
+
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> plt.figure()
+    >>> dn = hierarchy.dendrogram(Z)
+
+    Now, plot in given axes, improve the color scheme and use both vertical and
+    horizontal orientations:
+
+    >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k'])
+    >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3))
+    >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y',
+    ...                            orientation='top')
+    >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1],
+    ...                            above_threshold_color='#bcbddc',
+    ...                            orientation='right')
+    >>> hierarchy.set_link_color_palette(None)  # reset to default after use
+    >>> plt.show()
+
+    """
+    # This feature was thought about but never implemented (still useful?):
+    #
+    #         ... = dendrogram(..., leaves_order=None)
+    #
+    #         Plots the leaves in the order specified by a vector of
+    #         original observation indices. If the vector contains duplicates
+    #         or results in a crossing, an exception will be thrown. Passing
+    #         None orders leaf nodes based on the order they appear in the
+    #         pre-order traversal.
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='c', xp=xp)
+
+    if orientation not in ["top", "left", "bottom", "right"]:
+        raise ValueError("orientation must be one of 'top', 'left', "
+                         "'bottom', or 'right'")
+
+    if labels is not None:
+        try:
+            len_labels = len(labels)
+        except (TypeError, AttributeError):
+            len_labels = labels.shape[0]
+        if Z.shape[0] + 1 != len_labels:
+            raise ValueError("Dimensions of Z and labels must be consistent.")
+
+    is_valid_linkage(Z, throw=True, name='Z')
+    Zs = Z.shape
+    n = Zs[0] + 1
+    if isinstance(p, (int, float)):
+        p = int(p)
+    else:
+        raise TypeError('The second argument must be a number')
+
+    if truncate_mode not in ('lastp', 'mtica', 'level', 'none', None):
+        # 'mtica' is kept working for backwards compat.
+        raise ValueError('Invalid truncation mode.')
+
+    if truncate_mode == 'lastp':
+        if p > n or p == 0:
+            p = n
+
+    if truncate_mode == 'mtica':
+        # 'mtica' is an alias
+        truncate_mode = 'level'
+
+    if truncate_mode == 'level':
+        if p <= 0:
+            p = np.inf
+
+    if get_leaves:
+        lvs = []
+    else:
+        lvs = None
+
+    icoord_list = []
+    dcoord_list = []
+    color_list = []
+    current_color = [0]
+    currently_below_threshold = [False]
+    ivl = []  # list of leaves
+
+    if color_threshold is None or (isinstance(color_threshold, str) and
+                                   color_threshold == 'default'):
+        color_threshold = xp.max(Z[:, 2]) * 0.7
+
+    R = {'icoord': icoord_list, 'dcoord': dcoord_list, 'ivl': ivl,
+         'leaves': lvs, 'color_list': color_list}
+
+    # Empty list will be filled in _dendrogram_calculate_info
+    contraction_marks = [] if show_contracted else None
+
+    _dendrogram_calculate_info(
+        Z=Z, p=p,
+        truncate_mode=truncate_mode,
+        color_threshold=color_threshold,
+        get_leaves=get_leaves,
+        orientation=orientation,
+        labels=labels,
+        count_sort=count_sort,
+        distance_sort=distance_sort,
+        show_leaf_counts=show_leaf_counts,
+        i=2*n - 2,
+        iv=0.0,
+        ivl=ivl,
+        n=n,
+        icoord_list=icoord_list,
+        dcoord_list=dcoord_list,
+        lvs=lvs,
+        current_color=current_color,
+        color_list=color_list,
+        currently_below_threshold=currently_below_threshold,
+        leaf_label_func=leaf_label_func,
+        contraction_marks=contraction_marks,
+        link_color_func=link_color_func,
+        above_threshold_color=above_threshold_color)
+
+    if not no_plot:
+        mh = xp.max(Z[:, 2])
+        _plot_dendrogram(icoord_list, dcoord_list, ivl, p, n, mh, orientation,
+                         no_labels, color_list,
+                         leaf_font_size=leaf_font_size,
+                         leaf_rotation=leaf_rotation,
+                         contraction_marks=contraction_marks,
+                         ax=ax,
+                         above_threshold_color=above_threshold_color)
+
+    R["leaves_color_list"] = _get_leaves_color_list(R)
+
+    return R
+
+
+def _get_leaves_color_list(R):
+    leaves_color_list = [None] * len(R['leaves'])
+    for link_x, link_y, link_color in zip(R['icoord'],
+                                          R['dcoord'],
+                                          R['color_list']):
+        for (xi, yi) in zip(link_x, link_y):
+            if yi == 0.0 and (xi % 5 == 0 and xi % 2 == 1):
+                # if yi is 0.0 and xi is divisible by 5 and odd,
+                # the point is a leaf
+                # xi of leaves are      5, 15, 25, 35, ... (see `iv_ticks`)
+                # index of leaves are   0,  1,  2,  3, ... as below
+                leaf_index = (int(xi) - 5) // 10
+                # each leaf has a same color of its link.
+                leaves_color_list[leaf_index] = link_color
+    return leaves_color_list
+
+
+def _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                i, labels):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+
+    # If leaf node labels are to be displayed...
+    if ivl is not None:
+        # If a leaf_label_func has been provided, the label comes from the
+        # string returned from the leaf_label_func, which is a function
+        # passed to dendrogram.
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            # Otherwise, if the dendrogram caller has passed a labels list
+            # for the leaf nodes, use it.
+            if labels is not None:
+                ivl.append(labels[int(i - n)])
+            else:
+                # Otherwise, use the id as the label for the leaf.x
+                ivl.append(str(int(i)))
+
+
+def _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                   i, labels, show_leaf_counts):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+    if ivl is not None:
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            if show_leaf_counts:
+                ivl.append("(" + str(np.asarray(Z[i - n, 3], dtype=np.int64)) + ")")
+            else:
+                ivl.append("")
+
+
+def _append_contraction_marks(Z, iv, i, n, contraction_marks, xp):
+    _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp),
+                                  n, contraction_marks, xp)
+    _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp),
+                                  n, contraction_marks, xp)
+
+
+def _append_contraction_marks_sub(Z, iv, i, n, contraction_marks, xp):
+    if i >= n:
+        contraction_marks.append((iv, Z[i - n, 2]))
+        _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp),
+                                      n, contraction_marks, xp)
+        _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp),
+                                      n, contraction_marks, xp)
+
+
+def _dendrogram_calculate_info(Z, p, truncate_mode,
+                               color_threshold=np.inf, get_leaves=True,
+                               orientation='top', labels=None,
+                               count_sort=False, distance_sort=False,
+                               show_leaf_counts=False, i=-1, iv=0.0,
+                               ivl=None, n=0, icoord_list=None, dcoord_list=None,
+                               lvs=None, mhr=False,
+                               current_color=None, color_list=None,
+                               currently_below_threshold=None,
+                               leaf_label_func=None, level=0,
+                               contraction_marks=None,
+                               link_color_func=None,
+                               above_threshold_color='C0'):
+    """
+    Calculate the endpoints of the links as well as the labels for the
+    the dendrogram rooted at the node with index i. iv is the independent
+    variable value to plot the left-most leaf node below the root node i
+    (if orientation='top', this would be the left-most x value where the
+    plotting of this root node i and its descendents should begin).
+
+    ivl is a list to store the labels of the leaf nodes. The leaf_label_func
+    is called whenever ivl != None, labels == None, and
+    leaf_label_func != None. When ivl != None and labels != None, the
+    labels list is used only for labeling the leaf nodes. When
+    ivl == None, no labels are generated for leaf nodes.
+
+    When get_leaves==True, a list of leaves is built as they are visited
+    in the dendrogram.
+
+    Returns a tuple with l being the independent variable coordinate that
+    corresponds to the midpoint of cluster to the left of cluster i if
+    i is non-singleton, otherwise the independent coordinate of the leaf
+    node if i is a leaf node.
+
+    Returns
+    -------
+    A tuple (left, w, h, md), where:
+        * left is the independent variable coordinate of the center of the
+          the U of the subtree
+
+        * w is the amount of space used for the subtree (in independent
+          variable units)
+
+        * h is the height of the subtree in dependent variable units
+
+        * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including
+          the target node.
+
+    """
+    xp = array_namespace(Z)
+    if n == 0:
+        raise ValueError("Invalid singleton cluster count n.")
+
+    if i == -1:
+        raise ValueError("Invalid root cluster index i.")
+
+    if truncate_mode == 'lastp':
+        # If the node is a leaf node but corresponds to a non-singleton
+        # cluster, its label is either the empty string or the number of
+        # original observations belonging to cluster i.
+        if 2*n - p > i >= n:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+    elif truncate_mode == 'level':
+        if i > n and level > p:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # Otherwise, only truncate if we have a leaf node.
+    #
+    # Only place leaves if they correspond to original observations.
+    if i < n:
+        _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                    leaf_label_func, i, labels)
+        return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # !!! Otherwise, we don't have a leaf node, so work on plotting a
+    # non-leaf node.
+    # Actual indices of a and b
+    aa = int_floor(Z[i - n, 0], xp)
+    ab = int_floor(Z[i - n, 1], xp)
+    if aa >= n:
+        # The number of singletons below cluster a
+        na = Z[aa - n, 3]
+        # The distance between a's two direct children.
+        da = Z[aa - n, 2]
+    else:
+        na = 1
+        da = 0.0
+    if ab >= n:
+        nb = Z[ab - n, 3]
+        db = Z[ab - n, 2]
+    else:
+        nb = 1
+        db = 0.0
+
+    if count_sort == 'ascending' or count_sort is True:
+        # If a has a count greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if na > nb:
+            # The cluster index to draw to the left (ua) will be ab
+            # and the one to draw to the right (ub) will be aa
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif count_sort == 'descending':
+        # If a has a count less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if na > nb:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    elif distance_sort == 'ascending' or distance_sort is True:
+        # If a has a distance greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if da > db:
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif distance_sort == 'descending':
+        # If a has a distance less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if da > db:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    else:
+        ua = aa
+        ub = ab
+
+    # Updated iv variable and the amount of space used.
+    (uiva, uwa, uah, uamd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ua, iv=iv, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    h = Z[i - n, 2]
+    if h >= color_threshold or color_threshold <= 0:
+        c = above_threshold_color
+
+        if currently_below_threshold[0]:
+            current_color[0] = (current_color[0] + 1) % len(_link_line_colors)
+        currently_below_threshold[0] = False
+    else:
+        currently_below_threshold[0] = True
+        c = _link_line_colors[current_color[0]]
+
+    (uivb, uwb, ubh, ubmd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ub, iv=iv + uwa, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    max_dist = max(uamd, ubmd, h)
+
+    icoord_list.append([uiva, uiva, uivb, uivb])
+    dcoord_list.append([uah, h, h, ubh])
+    if link_color_func is not None:
+        v = link_color_func(int(i))
+        if not isinstance(v, str):
+            raise TypeError("link_color_func must return a matplotlib "
+                            "color string!")
+        color_list.append(v)
+    else:
+        color_list.append(c)
+
+    return (((uiva + uivb) / 2), uwa + uwb, h, max_dist)
+
+
+def is_isomorphic(T1, T2):
+    """
+    Determine if two different cluster assignments are equivalent.
+
+    Parameters
+    ----------
+    T1 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+    T2 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+
+    Returns
+    -------
+    b : bool
+        Whether the flat cluster assignments `T1` and `T2` are
+        equivalent.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fcluster, is_isomorphic
+    >>> from scipy.cluster.hierarchy import single, complete
+    >>> from scipy.spatial.distance import pdist
+
+    Two flat cluster assignments can be isomorphic if they represent the same
+    cluster assignment, with different labels.
+
+    For example, we can use the `scipy.cluster.hierarchy.single`: method
+    and flatten the output to four clusters:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = single(pdist(X))
+    >>> T = fcluster(Z, 1, criterion='distance')
+    >>> T
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    We can then do the same using the
+    `scipy.cluster.hierarchy.complete`: method:
+
+    >>> Z = complete(pdist(X))
+    >>> T_ = fcluster(Z, 1.5, criterion='distance')
+    >>> T_
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    As we can see, in both cases we obtain four clusters and all the data
+    points are distributed in the same way - the only thing that changes
+    are the flat cluster labels (3 => 1, 4 =>2, 2 =>3 and 4 =>1), so both
+    cluster assignments are isomorphic:
+
+    >>> is_isomorphic(T, T_)
+    True
+
+    """
+    T1 = np.asarray(T1, order='c')
+    T2 = np.asarray(T2, order='c')
+
+    T1S = T1.shape
+    T2S = T2.shape
+
+    if len(T1S) != 1:
+        raise ValueError('T1 must be one-dimensional.')
+    if len(T2S) != 1:
+        raise ValueError('T2 must be one-dimensional.')
+    if T1S[0] != T2S[0]:
+        raise ValueError('T1 and T2 must have the same number of elements.')
+    n = T1S[0]
+    d1 = {}
+    d2 = {}
+    for i in range(0, n):
+        if T1[i] in d1:
+            if T2[i] not in d2:
+                return False
+            if d1[T1[i]] != T2[i] or d2[T2[i]] != T1[i]:
+                return False
+        elif T2[i] in d2:
+            return False
+        else:
+            d1[T1[i]] = T2[i]
+            d2[T2[i]] = T1[i]
+    return True
+
+
+def maxdists(Z):
+    """
+    Return the maximum distance between any non-singleton cluster.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        ``linkage`` for more information.
+
+    Returns
+    -------
+    maxdists : ndarray
+        A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents
+        the maximum distance between any cluster (including
+        singletons) below and including the node with index i. More
+        specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the
+        set of all node indices below and including node i.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    is_monotonic : for testing for monotonicity of a linkage matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, maxdists
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z``, `scipy.cluster.hierarchy.maxdists`
+    computes for each new cluster generated (i.e., for each row of the linkage
+    matrix) what is the maximum distance between any two child clusters.
+
+    Due to the nature of hierarchical clustering, in many cases this is going
+    to be just the distance between the two child clusters that were merged
+    to form the current one - that is, Z[:,2].
+
+    However, for non-monotonic cluster assignments such as
+    `scipy.cluster.hierarchy.median` clustering this is not always the
+    case: There may be cluster formations were the distance between the two
+    clusters merged is smaller than the distance between their children.
+
+    We can see this in an example:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> maxdists(Z)
+    array([1.        , 1.        , 1.        , 1.        , 1.11803399,
+           1.11803399, 1.11803399, 1.11803399, 3.        , 3.5       ,
+           3.5       ])
+
+    Note that while the distance between the two clusters merged when creating the
+    last cluster is 3.25, there are two children (clusters 16 and 17) whose distance
+    is larger (3.5). Thus, `scipy.cluster.hierarchy.maxdists` returns 3.5 in
+    this case.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    n = Z.shape[0] + 1
+    MD = np.zeros((n - 1,))
+    Z = np.asarray(Z)
+    _hierarchy.get_max_dist_for_each_cluster(Z, MD, int(n))
+    MD = xp.asarray(MD)
+    return MD
+
+
+def maxinconsts(Z, R):
+    """
+    Return the maximum inconsistency coefficient for each
+    non-singleton cluster and its children.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    R : ndarray
+        The inconsistency matrix.
+
+    Returns
+    -------
+    MI : ndarray
+        A monotonic ``(n-1)``-sized numpy array of doubles.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxinconsts
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    Here, `scipy.cluster.hierarchy.maxinconsts` can be used to compute
+    the maximum value of the inconsistency statistic (the last column of
+    ``R``) for each non-singleton cluster and its children:
+
+    >>> maxinconsts(Z, R)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+    is_valid_im(R, throw=True, name='R')
+
+    n = Z.shape[0] + 1
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+    MI = np.zeros((n - 1,))
+    Z = np.asarray(Z)
+    R = np.asarray(R)
+    _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, int(n), 3)
+    MI = xp.asarray(MI)
+    return MI
+
+
+def maxRstat(Z, R, i):
+    """
+    Return the maximum statistic for each non-singleton cluster and its
+    children.
+
+    Parameters
+    ----------
+    Z : array_like
+        The hierarchical clustering encoded as a matrix. See `linkage` for more
+        information.
+    R : array_like
+        The inconsistency matrix.
+    i : int
+        The column of `R` to use as the statistic.
+
+    Returns
+    -------
+    MR : ndarray
+        Calculates the maximum statistic for the i'th column of the
+        inconsistency matrix `R` for each non-singleton cluster
+        node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]``, where
+        ``Q(j)`` the set of all node ids corresponding to nodes below
+        and including ``j``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxRstat
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    `scipy.cluster.hierarchy.maxRstat` can be used to compute
+    the maximum value of each column of ``R``, for each non-singleton
+    cluster and its children:
+
+    >>> maxRstat(Z, R, 0)
+    array([1.        , 1.        , 1.        , 1.        , 1.05901699,
+           1.05901699, 1.05901699, 1.05901699, 1.74535599, 1.91202266,
+           3.25      ])
+    >>> maxRstat(Z, R, 1)
+    array([0.        , 0.        , 0.        , 0.        , 0.08346263,
+           0.08346263, 0.08346263, 0.08346263, 1.08655358, 1.37522872,
+           1.37522872])
+    >>> maxRstat(Z, R, 3)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+    is_valid_im(R, throw=True, name='R')
+
+    if not isinstance(i, int):
+        raise TypeError('The third argument must be an integer.')
+
+    if i < 0 or i > 3:
+        raise ValueError('i must be an integer between 0 and 3 inclusive.')
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+
+    n = Z.shape[0] + 1
+    MR = np.zeros((n - 1,))
+    Z = np.asarray(Z)
+    R = np.asarray(R)
+    _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MR, int(n), i)
+    MR = xp.asarray(MR)
+    return MR
+
+
+def leaders(Z, T):
+    """
+    Return the root nodes in a hierarchical clustering.
+
+    Returns the root nodes in a hierarchical clustering corresponding
+    to a cut defined by a flat cluster assignment vector ``T``. See
+    the ``fcluster`` function for more information on the format of ``T``.
+
+    For each flat cluster :math:`j` of the :math:`k` flat clusters
+    represented in the n-sized flat cluster assignment vector ``T``,
+    this function finds the lowest cluster node :math:`i` in the linkage
+    tree Z, such that:
+
+      * leaf descendants belong only to flat cluster j
+        (i.e., ``T[p]==j`` for all :math:`p` in :math:`S(i)`, where
+        :math:`S(i)` is the set of leaf ids of descendant leaf nodes
+        with cluster node :math:`i`)
+
+      * there does not exist a leaf that is not a descendant with
+        :math:`i` that also belongs to cluster :math:`j`
+        (i.e., ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If
+        this condition is violated, ``T`` is not a valid cluster
+        assignment vector, and an exception will be thrown.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    T : ndarray
+        The flat cluster assignment vector.
+
+    Returns
+    -------
+    L : ndarray
+        The leader linkage node id's stored as a k-element 1-D array,
+        where ``k`` is the number of flat clusters found in ``T``.
+
+        ``L[j]=i`` is the linkage cluster node id that is the
+        leader of flat cluster with id M[j]. If ``i < n``, ``i``
+        corresponds to an original observation, otherwise it
+        corresponds to a non-singleton cluster.
+    M : ndarray
+        The leader linkage node id's stored as a k-element 1-D array, where
+        ``k`` is the number of flat clusters found in ``T``. This allows the
+        set of flat cluster ids to be any arbitrary set of ``k`` integers.
+
+        For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with
+        id 8's leader is linkage node 2.
+
+    See Also
+    --------
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster, leaders
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z`` - obtained after apply a clustering method
+    to a dataset ``X`` - and a flat cluster assignment array ``T``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    >>> T = fcluster(Z, 3, criterion='distance')
+    >>> T
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    `scipy.cluster.hierarchy.leaders` returns the indices of the nodes
+    in the dendrogram that are the leaders of each flat cluster:
+
+    >>> L, M = leaders(Z, T)
+    >>> L
+    array([16, 17, 18, 19], dtype=int32)
+
+    (remember that indices 0-11 point to the 12 data points in ``X``,
+    whereas indices 12-22 point to the 11 rows of ``Z``)
+
+    `scipy.cluster.hierarchy.leaders` also returns the indices of
+    the flat clusters in ``T``:
+
+    >>> M
+    array([1, 2, 3, 4], dtype=int32)
+
+    """
+    xp = array_namespace(Z, T)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    T = _asarray(T, order='C', xp=xp)
+    is_valid_linkage(Z, throw=True, name='Z')
+
+    if T.dtype != xp.int32:
+        raise TypeError('T must be a 1-D array of dtype int32.')
+
+    if T.shape[0] != Z.shape[0] + 1:
+        raise ValueError('Mismatch: len(T)!=Z.shape[0] + 1.')
+
+    n_clusters = int(xp.unique_values(T).shape[0])
+    n_obs = int(Z.shape[0] + 1)
+    L = np.zeros(n_clusters, dtype=np.int32)
+    M = np.zeros(n_clusters, dtype=np.int32)
+    Z = np.asarray(Z)
+    T = np.asarray(T, dtype=np.int32)
+    s = _hierarchy.leaders(Z, T, L, M, n_clusters, n_obs)
+    if s >= 0:
+        raise ValueError(('T is not a valid assignment vector. Error found '
+                          'when examining linkage node %d (< 2n-1).') % s)
+    L, M = xp.asarray(L), xp.asarray(M)
+    return (L, M)
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27d89d0908eb7eeb60137d07e111dc86e6065cba
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad66a66ade4a3851c39137d830f724cdf8abb498
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51ba93fc2b35674dd73a1a5559c5c7436fc4b8b8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_hierarchy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_hierarchy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fc9f8e1cea50d9b5a4e56a1d7ca60e1af529e74
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_hierarchy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1dd003b3f5dd2b7183245979a10ebd90e6e908e3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/hierarchy_test_data.py b/venv/lib/python3.10/site-packages/scipy/cluster/tests/hierarchy_test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d874ca5eb7141a44559307d1c28dd412171396f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/tests/hierarchy_test_data.py
@@ -0,0 +1,145 @@
+from numpy import array
+
+
+Q_X = array([[5.26563660e-01, 3.14160190e-01, 8.00656370e-02],
+             [7.50205180e-01, 4.60299830e-01, 8.98696460e-01],
+             [6.65461230e-01, 6.94011420e-01, 9.10465700e-01],
+             [9.64047590e-01, 1.43082200e-03, 7.39874220e-01],
+             [1.08159060e-01, 5.53028790e-01, 6.63804780e-02],
+             [9.31359130e-01, 8.25424910e-01, 9.52315440e-01],
+             [6.78086960e-01, 3.41903970e-01, 5.61481950e-01],
+             [9.82730940e-01, 7.04605210e-01, 8.70978630e-02],
+             [6.14691610e-01, 4.69989230e-02, 6.02406450e-01],
+             [5.80161260e-01, 9.17354970e-01, 5.88163850e-01],
+             [1.38246310e+00, 1.96358160e+00, 1.94437880e+00],
+             [2.10675860e+00, 1.67148730e+00, 1.34854480e+00],
+             [1.39880070e+00, 1.66142050e+00, 1.32224550e+00],
+             [1.71410460e+00, 1.49176380e+00, 1.45432170e+00],
+             [1.54102340e+00, 1.84374950e+00, 1.64658950e+00],
+             [2.08512480e+00, 1.84524350e+00, 2.17340850e+00],
+             [1.30748740e+00, 1.53801650e+00, 2.16007740e+00],
+             [1.41447700e+00, 1.99329070e+00, 1.99107420e+00],
+             [1.61943490e+00, 1.47703280e+00, 1.89788160e+00],
+             [1.59880600e+00, 1.54988980e+00, 1.57563350e+00],
+             [3.37247380e+00, 2.69635310e+00, 3.39981700e+00],
+             [3.13705120e+00, 3.36528090e+00, 3.06089070e+00],
+             [3.29413250e+00, 3.19619500e+00, 2.90700170e+00],
+             [2.65510510e+00, 3.06785900e+00, 2.97198540e+00],
+             [3.30941040e+00, 2.59283970e+00, 2.57714110e+00],
+             [2.59557220e+00, 3.33477370e+00, 3.08793190e+00],
+             [2.58206180e+00, 3.41615670e+00, 3.26441990e+00],
+             [2.71127000e+00, 2.77032450e+00, 2.63466500e+00],
+             [2.79617850e+00, 3.25473720e+00, 3.41801560e+00],
+             [2.64741750e+00, 2.54538040e+00, 3.25354110e+00]])
+
+ytdist = array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754.,
+                564., 138., 219., 869., 669.])
+
+linkage_ytdist_single = array([[2., 5., 138., 2.],
+                               [3., 4., 219., 2.],
+                               [0., 7., 255., 3.],
+                               [1., 8., 268., 4.],
+                               [6., 9., 295., 6.]])
+
+linkage_ytdist_complete = array([[2., 5., 138., 2.],
+                                 [3., 4., 219., 2.],
+                                 [1., 6., 400., 3.],
+                                 [0., 7., 412., 3.],
+                                 [8., 9., 996., 6.]])
+
+linkage_ytdist_average = array([[2., 5., 138., 2.],
+                                [3., 4., 219., 2.],
+                                [0., 7., 333.5, 3.],
+                                [1., 6., 347.5, 3.],
+                                [8., 9., 680.77777778, 6.]])
+
+linkage_ytdist_weighted = array([[2., 5., 138., 2.],
+                                 [3., 4., 219., 2.],
+                                 [0., 7., 333.5, 3.],
+                                 [1., 6., 347.5, 3.],
+                                 [8., 9., 670.125, 6.]])
+
+# the optimal leaf ordering of linkage_ytdist_single
+linkage_ytdist_single_olo = array([[5., 2., 138., 2.],
+                                   [4., 3., 219., 2.],
+                                   [7., 0., 255., 3.],
+                                   [1., 8., 268., 4.],
+                                   [6., 9., 295., 6.]])
+
+X = array([[1.43054825, -7.5693489],
+           [6.95887839, 6.82293382],
+           [2.87137846, -9.68248579],
+           [7.87974764, -6.05485803],
+           [8.24018364, -6.09495602],
+           [7.39020262, 8.54004355]])
+ 
+linkage_X_centroid = array([[3., 4., 0.36265956, 2.],
+                            [1., 5., 1.77045373, 2.],
+                            [0., 2., 2.55760419, 2.],
+                            [6., 8., 6.43614494, 4.],
+                            [7., 9., 15.17363237, 6.]])
+
+linkage_X_median = array([[3., 4., 0.36265956, 2.],
+                          [1., 5., 1.77045373, 2.],
+                          [0., 2., 2.55760419, 2.],
+                          [6., 8., 6.43614494, 4.],
+                          [7., 9., 15.17363237, 6.]])
+
+linkage_X_ward = array([[3., 4., 0.36265956, 2.],
+                        [1., 5., 1.77045373, 2.],
+                        [0., 2., 2.55760419, 2.],
+                        [6., 8., 9.10208346, 4.],
+                        [7., 9., 24.7784379, 6.]])
+
+# the optimal leaf ordering of linkage_X_ward
+linkage_X_ward_olo = array([[4., 3., 0.36265956, 2.],
+                            [5., 1., 1.77045373, 2.],
+                            [2., 0., 2.55760419, 2.],
+                            [6., 8., 9.10208346, 4.],
+                            [7., 9., 24.7784379, 6.]])
+
+inconsistent_ytdist = {
+    1: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [255., 0., 1., 0.],
+              [268., 0., 1., 0.],
+              [295., 0., 1., 0.]]),
+    2: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [261.5, 9.19238816, 2., 0.70710678],
+              [233.66666667, 83.9424406, 3., 0.7306594]]),
+    3: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [247.33333333, 25.38372182, 3., 0.81417007],
+              [239., 69.36377537, 4., 0.80733783]]),
+    4: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [247.33333333, 25.38372182, 3., 0.81417007],
+              [235., 60.73302232, 5., 0.98793042]])}
+
+fcluster_inconsistent = {
+    0.8: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    1.0: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    2.0: 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])}
+
+fcluster_distance = {
+    0.6: array([4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 3,
+                1, 1, 1, 2, 1, 1, 1, 1, 1]),
+    1.0: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    2.0: 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])}
+
+fcluster_maxclust = {
+    8.0: array([5, 5, 5, 5, 5, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 4,
+                1, 1, 1, 3, 1, 1, 1, 1, 2]),
+    4.0: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    1.0: 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])}
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_disjoint_set.py b/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_disjoint_set.py
new file mode 100644
index 0000000000000000000000000000000000000000..a73512d35eef168f625a1942a87d248e73a71aa2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_disjoint_set.py
@@ -0,0 +1,202 @@
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.cluster.hierarchy import DisjointSet
+import string
+
+
+def generate_random_token():
+    k = len(string.ascii_letters)
+    tokens = list(np.arange(k, dtype=int))
+    tokens += list(np.arange(k, dtype=float))
+    tokens += list(string.ascii_letters)
+    tokens += [None for i in range(k)]
+    tokens = np.array(tokens, dtype=object)
+    rng = np.random.RandomState(seed=0)
+
+    while 1:
+        size = rng.randint(1, 3)
+        element = rng.choice(tokens, size)
+        if size == 1:
+            yield element[0]
+        else:
+            yield tuple(element)
+
+
+def get_elements(n):
+    # dict is deterministic without difficulty of comparing numpy ints
+    elements = {}
+    for element in generate_random_token():
+        if element not in elements:
+            elements[element] = len(elements)
+            if len(elements) >= n:
+                break
+    return list(elements.keys())
+
+
+def test_init():
+    n = 10
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert dis.n_subsets == n
+    assert list(dis) == elements
+
+
+def test_len():
+    n = 10
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert len(dis) == n
+
+    dis.add("dummy")
+    assert len(dis) == n + 1
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_contains(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    for x in elements:
+        assert x in dis
+
+    assert "dummy" not in dis
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_add(n):
+    elements = get_elements(n)
+    dis1 = DisjointSet(elements)
+
+    dis2 = DisjointSet()
+    for i, x in enumerate(elements):
+        dis2.add(x)
+        assert len(dis2) == i + 1
+
+        # test idempotency by adding element again
+        dis2.add(x)
+        assert len(dis2) == i + 1
+
+    assert list(dis1) == list(dis2)
+
+
+def test_element_not_present():
+    elements = get_elements(n=10)
+    dis = DisjointSet(elements)
+
+    with assert_raises(KeyError):
+        dis["dummy"]
+
+    with assert_raises(KeyError):
+        dis.merge(elements[0], "dummy")
+
+    with assert_raises(KeyError):
+        dis.connected(elements[0], "dummy")
+
+
+@pytest.mark.parametrize("direction", ["forwards", "backwards"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_linear_union_sequence(n, direction):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert elements == list(dis)
+
+    indices = list(range(n - 1))
+    if direction == "backwards":
+        indices = indices[::-1]
+
+    for it, i in enumerate(indices):
+        assert not dis.connected(elements[i], elements[i + 1])
+        assert dis.merge(elements[i], elements[i + 1])
+        assert dis.connected(elements[i], elements[i + 1])
+        assert dis.n_subsets == n - 1 - it
+
+    roots = [dis[i] for i in elements]
+    if direction == "forwards":
+        assert all(elements[0] == r for r in roots)
+    else:
+        assert all(elements[-2] == r for r in roots)
+    assert not dis.merge(elements[0], elements[-1])
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_self_unions(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    for x in elements:
+        assert dis.connected(x, x)
+        assert not dis.merge(x, x)
+        assert dis.connected(x, x)
+    assert dis.n_subsets == len(elements)
+
+    assert elements == list(dis)
+    roots = [dis[x] for x in elements]
+    assert elements == roots
+
+
+@pytest.mark.parametrize("order", ["ab", "ba"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_equal_size_ordering(n, order):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    rng = np.random.RandomState(seed=0)
+    indices = np.arange(n)
+    rng.shuffle(indices)
+
+    for i in range(0, len(indices), 2):
+        a, b = elements[indices[i]], elements[indices[i + 1]]
+        if order == "ab":
+            assert dis.merge(a, b)
+        else:
+            assert dis.merge(b, a)
+
+        expected = elements[min(indices[i], indices[i + 1])]
+        assert dis[a] == expected
+        assert dis[b] == expected
+
+
+@pytest.mark.parametrize("kmax", [5, 10])
+def test_binary_tree(kmax):
+    n = 2**kmax
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    rng = np.random.RandomState(seed=0)
+
+    for k in 2**np.arange(kmax):
+        for i in range(0, n, 2 * k):
+            r1, r2 = rng.randint(0, k, size=2)
+            a, b = elements[i + r1], elements[i + k + r2]
+            assert not dis.connected(a, b)
+            assert dis.merge(a, b)
+            assert dis.connected(a, b)
+
+        assert elements == list(dis)
+        roots = [dis[i] for i in elements]
+        expected_indices = np.arange(n) - np.arange(n) % (2 * k)
+        expected = [elements[i] for i in expected_indices]
+        assert roots == expected
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_subsets(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    rng = np.random.RandomState(seed=0)
+    for i, j in rng.randint(0, n, (n, 2)):
+        x = elements[i]
+        y = elements[j]
+
+        expected = {element for element in dis if {dis[element]} == {dis[x]}}
+        assert dis.subset_size(x) == len(dis.subset(x))
+        assert expected == dis.subset(x)
+
+        expected = {dis[element]: set() for element in dis}
+        for element in dis:
+            expected[dis[element]].add(element)
+        expected = list(expected.values())
+        assert expected == dis.subsets()
+
+        dis.merge(x, y)
+        assert dis.subset(x) == dis.subset(y)
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_hierarchy.py b/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dd0e37c59f3b004b09ce1662a98b53505398453
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_hierarchy.py
@@ -0,0 +1,1300 @@
+#
+# Author: Damian Eads
+# Date: April 17, 2008
+#
+# Copyright (C) 2008 Damian Eads
+#
+# 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 numpy.testing import (assert_allclose, assert_equal, assert_array_equal, assert_,
+                           assert_warns)
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.cluster.hierarchy
+from scipy.cluster.hierarchy import (
+    ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage,
+    num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster,
+    is_isomorphic, single, leaders,
+    correspond, is_monotonic, maxdists, maxinconsts, maxRstat,
+    is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram,
+    set_link_color_palette, cut_tree, optimal_leaf_ordering,
+    _order_cluster_tree, _hierarchy, _LINKAGE_METHODS)
+from scipy.spatial.distance import pdist
+from scipy.cluster._hierarchy import Heap
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal
+
+from threading import Lock
+
+from . import hierarchy_test_data
+
+
+# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so
+# check if it's available
+try:
+    import matplotlib
+    # and set the backend to be Agg (no gui)
+    matplotlib.use('Agg')
+    # before importing pyplot
+    import matplotlib.pyplot as plt
+    have_matplotlib = True
+except Exception:
+    have_matplotlib = False
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestLinkage:
+
+    @skip_xp_backends(cpu_only=True)
+    def test_linkage_non_finite_elements_in_distance_matrix(self, xp):
+        # Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf).
+        # Exception expected.
+        y = xp.asarray([xp.nan] + [0.0]*5)
+        assert_raises(ValueError, linkage, y)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_linkage_empty_distance_matrix(self, xp):
+        # Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected.
+        y = xp.zeros((0,))
+        assert_raises(ValueError, linkage, y)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_linkage_tdist(self, xp):
+        for method in ['single', 'complete', 'average', 'weighted']:
+            self.check_linkage_tdist(method, xp)
+
+    def check_linkage_tdist(self, method, xp):
+        # Tests linkage(Y, method) on the tdist data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_linkage_X(self, xp):
+        for method in ['centroid', 'median', 'ward']:
+            self.check_linkage_q(method, xp)
+
+    def check_linkage_q(self, method, xp):
+        # Tests linkage(Y, method) on the Q data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.X), method)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+        y = scipy.spatial.distance.pdist(hierarchy_test_data.X,
+                                         metric="euclidean")
+        Z = linkage(xp.asarray(y), method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_compare_with_trivial(self, xp):
+        rng = np.random.RandomState(0)
+        n = 20
+        X = rng.rand(n, 2)
+        d = pdist(X)
+
+        for method, code in _LINKAGE_METHODS.items():
+            Z_trivial = _hierarchy.linkage(d, n, code)
+            Z = linkage(xp.asarray(d), method)
+            xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_optimal_leaf_ordering(self, xp):
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo')
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestLinkageTies:
+
+    _expectations = {
+        'single': np.array([[0, 1, 1.41421356, 2],
+                            [2, 3, 1.41421356, 3]]),
+        'complete': np.array([[0, 1, 1.41421356, 2],
+                              [2, 3, 2.82842712, 3]]),
+        'average': np.array([[0, 1, 1.41421356, 2],
+                             [2, 3, 2.12132034, 3]]),
+        'weighted': np.array([[0, 1, 1.41421356, 2],
+                              [2, 3, 2.12132034, 3]]),
+        'centroid': np.array([[0, 1, 1.41421356, 2],
+                              [2, 3, 2.12132034, 3]]),
+        'median': np.array([[0, 1, 1.41421356, 2],
+                            [2, 3, 2.12132034, 3]]),
+        'ward': np.array([[0, 1, 1.41421356, 2],
+                          [2, 3, 2.44948974, 3]]),
+    }
+
+    def test_linkage_ties(self, xp):
+        for method in ['single', 'complete', 'average', 'weighted',
+                       'centroid', 'median', 'ward']:
+            self.check_linkage_ties(method, xp)
+
+    def check_linkage_ties(self, method, xp):
+        X = xp.asarray([[-1, -1], [0, 0], [1, 1]])
+        Z = linkage(X, method=method)
+        expectedZ = self._expectations[method]
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestInconsistent:
+
+    def test_inconsistent_tdist(self, xp):
+        for depth in hierarchy_test_data.inconsistent_ytdist:
+            self.check_inconsistent_tdist(depth, xp)
+
+    def check_inconsistent_tdist(self, depth, xp):
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        xp_assert_close(inconsistent(Z, depth),
+                        xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth]))
+
+
+@skip_xp_backends(cpu_only=True)
+class TestCopheneticDistance:
+
+    def test_linkage_cophenet_tdist_Z(self, xp):
+        # Tests cophenet(Z) on tdist data set.
+        expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+                                295, 138, 219, 295, 295])
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        M = cophenet(Z)
+        xp_assert_close(M, xp.asarray(expectedM, dtype=xp.float64), atol=1e-10)
+
+    def test_linkage_cophenet_tdist_Z_Y(self, xp):
+        # Tests cophenet(Z, Y) on tdist data set.
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        (c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist))
+        expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+                                295, 138, 219, 295, 295], dtype=xp.float64)
+        expectedc = xp.asarray(0.639931296433393415057366837573, dtype=xp.float64)[()]
+        xp_assert_close(c, expectedc, atol=1e-10)
+        xp_assert_close(M, expectedM, atol=1e-10)
+
+    def test_gh_22183(self, xp):
+        # check for lack of segfault
+        # (out of bounds memory access)
+        # and correct interception of
+        # invalid linkage matrix
+        arr=[[0.0, 1.0, 1.0, 2.0],
+             [2.0, 12.0, 1.0, 3.0],
+             [3.0, 4.0, 1.0, 2.0],
+             [5.0, 14.0, 1.0, 3.0],
+             [6.0, 7.0, 1.0, 2.0],
+             [8.0, 16.0, 1.0, 3.0],
+             [9.0, 10.0, 1.0, 2.0],
+             [11.0, 18.0, 1.0, 3.0],
+             [13.0, 15.0, 2.0, 6.0],
+             [17.0, 20.0, 2.0, 32.0],
+             [19.0, 21.0, 2.0, 12.0]]
+        with pytest.raises(ValueError, match="excessive observations"):
+            cophenet(xp.asarray(arr))
+
+
+class TestMLabLinkageConversion:
+
+    def test_mlab_linkage_conversion_empty(self, xp):
+        # Tests from/to_mlab_linkage on empty linkage array.
+        X = xp.asarray([], dtype=xp.float64)
+        xp_assert_equal(from_mlab_linkage(X), X)
+        xp_assert_equal(to_mlab_linkage(X), X)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_mlab_linkage_conversion_single_row(self, xp):
+        # Tests from/to_mlab_linkage on linkage array with single row.
+        Z = xp.asarray([[0., 1., 3., 2.]])
+        Zm = xp.asarray([[1, 2, 3]])
+        xp_assert_close(from_mlab_linkage(Zm), xp.asarray(Z, dtype=xp.float64),
+                        rtol=1e-15)
+        xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+                        rtol=1e-15)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_mlab_linkage_conversion_multiple_rows(self, xp):
+        # Tests from/to_mlab_linkage on linkage array with multiple rows.
+        Zm = xp.asarray([[3, 6, 138], [4, 5, 219],
+                         [1, 8, 255], [2, 9, 268], [7, 10, 295]])
+        Z = xp.asarray([[2., 5., 138., 2.],
+                        [3., 4., 219., 2.],
+                        [0., 7., 255., 3.],
+                        [1., 8., 268., 4.],
+                        [6., 9., 295., 6.]],
+                       dtype=xp.float64)
+        xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15)
+        xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+                        rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestFcluster:
+
+    def test_fclusterdata(self, xp):
+        for t in hierarchy_test_data.fcluster_inconsistent:
+            self.check_fclusterdata(t, 'inconsistent', xp)
+        for t in hierarchy_test_data.fcluster_distance:
+            self.check_fclusterdata(t, 'distance', xp)
+        for t in hierarchy_test_data.fcluster_maxclust:
+            self.check_fclusterdata(t, 'maxclust', xp)
+
+    def check_fclusterdata(self, t, criterion, xp):
+        # Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set
+        expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        T = fclusterdata(X, criterion=criterion, t=t)
+        assert_(is_isomorphic(T, expectedT))
+
+    def test_fcluster(self, xp):
+        for t in hierarchy_test_data.fcluster_inconsistent:
+            self.check_fcluster(t, 'inconsistent', xp)
+        for t in hierarchy_test_data.fcluster_distance:
+            self.check_fcluster(t, 'distance', xp)
+        for t in hierarchy_test_data.fcluster_maxclust:
+            self.check_fcluster(t, 'maxclust', xp)
+
+    def check_fcluster(self, t, criterion, xp):
+        # Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set.
+        expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, criterion=criterion, t=t)
+        assert_(is_isomorphic(T, expectedT))
+
+    def test_fcluster_monocrit(self, xp):
+        for t in hierarchy_test_data.fcluster_distance:
+            self.check_fcluster_monocrit(t, xp)
+        for t in hierarchy_test_data.fcluster_maxclust:
+            self.check_fcluster_maxclust_monocrit(t, xp)
+
+    def check_fcluster_monocrit(self, t, xp):
+        expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z))
+        assert_(is_isomorphic(T, expectedT))
+
+    def check_fcluster_maxclust_monocrit(self, t, xp):
+        expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z))
+        assert_(is_isomorphic(T, expectedT))
+
+    def test_fcluster_maxclust_gh_12651(self, xp):
+        y = xp.asarray([[1], [4], [5]])
+        Z = single(y)
+        assert_array_equal(fcluster(Z, t=1, criterion="maxclust"),
+                           xp.asarray([1, 1, 1]))
+        assert_array_equal(fcluster(Z, t=2, criterion="maxclust"),
+                           xp.asarray([2, 1, 1]))
+        assert_array_equal(fcluster(Z, t=3, criterion="maxclust"),
+                           xp.asarray([1, 2, 3]))
+        assert_array_equal(fcluster(Z, t=5, criterion="maxclust"),
+                           xp.asarray([1, 2, 3]))
+
+
+@skip_xp_backends(cpu_only=True)
+class TestLeaders:
+
+    def test_leaders_single(self, xp):
+        # Tests leaders using a flat clustering generated by single linkage.
+        X = hierarchy_test_data.Q_X
+        Y = pdist(X)
+        Y = xp.asarray(Y)
+        Z = linkage(Y)
+        T = fcluster(Z, criterion='maxclust', t=3)
+        Lright = (xp.asarray([53, 55, 56]), xp.asarray([2, 3, 1]))
+        T = xp.asarray(T, dtype=xp.int32)
+        L = leaders(Z, T)
+        assert_allclose(np.concatenate(L), np.concatenate(Lright), rtol=1e-15)
+
+
+@skip_xp_backends(np_only=True,
+                  reason='`is_isomorphic` only supports NumPy backend')
+class TestIsIsomorphic:
+
+    @skip_xp_backends(np_only=True,
+                      reason='array-likes only supported for NumPy backend')
+    def test_array_like(self, xp):
+        assert is_isomorphic([1, 1, 1], [2, 2, 2])
+        assert is_isomorphic([], [])
+
+    def test_is_isomorphic_1(self, xp):
+        # Tests is_isomorphic on test case #1 (one flat cluster, different labellings)
+        a = xp.asarray([1, 1, 1])
+        b = xp.asarray([2, 2, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_2(self, xp):
+        # Tests is_isomorphic on test case #2 (two flat clusters, different labelings)
+        a = xp.asarray([1, 7, 1])
+        b = xp.asarray([2, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_3(self, xp):
+        # Tests is_isomorphic on test case #3 (no flat clusters)
+        a = xp.asarray([])
+        b = xp.asarray([])
+        assert is_isomorphic(a, b)
+
+    def test_is_isomorphic_4A(self, xp):
+        # Tests is_isomorphic on test case #4A
+        # (3 flat clusters, different labelings, isomorphic)
+        a = xp.asarray([1, 2, 3])
+        b = xp.asarray([1, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_4B(self, xp):
+        # Tests is_isomorphic on test case #4B
+        # (3 flat clusters, different labelings, nonisomorphic)
+        a = xp.asarray([1, 2, 3, 3])
+        b = xp.asarray([1, 3, 2, 3])
+        assert is_isomorphic(a, b) is False
+        assert is_isomorphic(b, a) is False
+
+    def test_is_isomorphic_4C(self, xp):
+        # Tests is_isomorphic on test case #4C
+        # (3 flat clusters, different labelings, isomorphic)
+        a = xp.asarray([7, 2, 3])
+        b = xp.asarray([6, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_5(self, xp):
+        # Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random
+        # clusters, random permutation of the labeling).
+        for nc in [2, 3, 5]:
+            self.help_is_isomorphic_randperm(1000, nc, xp=xp)
+
+    def test_is_isomorphic_6(self, xp):
+        # Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random
+        # clusters, random permutation of the labeling, slightly
+        # nonisomorphic.)
+        for nc in [2, 3, 5]:
+            self.help_is_isomorphic_randperm(1000, nc, True, 5, xp=xp)
+
+    def test_is_isomorphic_7(self, xp):
+        # Regression test for gh-6271
+        a = xp.asarray([1, 2, 3])
+        b = xp.asarray([1, 1, 1])
+        assert not is_isomorphic(a, b)
+
+    def help_is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0,
+                                    *, xp):
+        for k in range(3):
+            a = (np.random.rand(nobs) * nclusters).astype(int)
+            b = np.zeros(a.size, dtype=int)
+            P = np.random.permutation(nclusters)
+            for i in range(0, a.shape[0]):
+                b[i] = P[a[i]]
+            if noniso:
+                Q = np.random.permutation(nobs)
+                b[Q[0:nerrors]] += 1
+                b[Q[0:nerrors]] %= nclusters
+            a = xp.asarray(a)
+            b = xp.asarray(b)
+            assert is_isomorphic(a, b) == (not noniso)
+            assert is_isomorphic(b, a) == (not noniso)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestIsValidLinkage:
+
+    def test_is_valid_linkage_various_size(self, xp):
+        for nrow, ncol, valid in [(2, 5, False), (2, 3, False),
+                                  (1, 4, True), (2, 4, True)]:
+            self.check_is_valid_linkage_various_size(nrow, ncol, valid, xp)
+
+    def check_is_valid_linkage_various_size(self, nrow, ncol, valid, xp):
+        # Tests is_valid_linkage(Z) with linkage matrices of various sizes
+        Z = xp.asarray([[0, 1, 3.0, 2, 5],
+                        [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+        Z = Z[:nrow, :ncol]
+        assert_(is_valid_linkage(Z) == valid)
+        if not valid:
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_int_type(self, xp):
+        # Tests is_valid_linkage(Z) with integer type.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.int64)
+        assert_(is_valid_linkage(Z) is False)
+        assert_raises(TypeError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_empty(self, xp):
+        # Tests is_valid_linkage(Z) with empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_(is_valid_linkage(Z) is False)
+        assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            assert_(is_valid_linkage(Z) is True)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_is_valid_linkage_4_and_up_neg_index_left(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative indices (left).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            Z[i//2,0] = -2
+            assert_(is_valid_linkage(Z) is False)
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_is_valid_linkage_4_and_up_neg_index_right(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative indices (right).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            Z[i//2,1] = -2
+            assert_(is_valid_linkage(Z) is False)
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_is_valid_linkage_4_and_up_neg_dist(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative distances.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            Z[i//2,2] = -0.5
+            assert_(is_valid_linkage(Z) is False)
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_is_valid_linkage_4_and_up_neg_counts(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative counts.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            Z[i//2,3] = -2
+            assert_(is_valid_linkage(Z) is False)
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestIsValidInconsistent:
+
+    def test_is_valid_im_int_type(self, xp):
+        # Tests is_valid_im(R) with integer type.
+        R = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.int64)
+        assert_(is_valid_im(R) is False)
+        assert_raises(TypeError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_various_size(self, xp):
+        for nrow, ncol, valid in [(2, 5, False), (2, 3, False),
+                                  (1, 4, True), (2, 4, True)]:
+            self.check_is_valid_im_various_size(nrow, ncol, valid, xp)
+
+    def check_is_valid_im_various_size(self, nrow, ncol, valid, xp):
+        # Tests is_valid_im(R) with linkage matrices of various sizes
+        R = xp.asarray([[0, 1, 3.0, 2, 5],
+                        [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+        R = R[:nrow, :ncol]
+        assert_(is_valid_im(R) == valid)
+        if not valid:
+            assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_empty(self, xp):
+        # Tests is_valid_im(R) with empty inconsistency matrix.
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_(is_valid_im(R) is False)
+        assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_4_and_up(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            assert_(is_valid_im(R) is True)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+    def test_is_valid_im_4_and_up_neg_index_left(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link height means.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R[i//2,0] = -2.0
+            assert_(is_valid_im(R) is False)
+            assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+    def test_is_valid_im_4_and_up_neg_index_right(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link height standard deviations.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R[i//2,1] = -2.0
+            assert_(is_valid_im(R) is False)
+            assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+    def test_is_valid_im_4_and_up_neg_dist(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link counts.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R[i//2,2] = -0.5
+            assert_(is_valid_im(R) is False)
+            assert_raises(ValueError, is_valid_im, R, throw=True)
+
+
+class TestNumObsLinkage:
+
+    @skip_xp_backends(cpu_only=True)
+    def test_num_obs_linkage_empty(self, xp):
+        # Tests num_obs_linkage(Z) with empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, num_obs_linkage, Z)
+
+    def test_num_obs_linkage_1x4(self, xp):
+        # Tests num_obs_linkage(Z) on linkage over 2 observations.
+        Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+        assert_equal(num_obs_linkage(Z), 2)
+
+    def test_num_obs_linkage_2x4(self, xp):
+        # Tests num_obs_linkage(Z) on linkage over 3 observations.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.float64)
+        assert_equal(num_obs_linkage(Z), 3)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_num_obs_linkage_4_and_up(self, xp):
+        # Tests num_obs_linkage(Z) on linkage on observation sets between sizes
+        # 4 and 15 (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            assert_equal(num_obs_linkage(Z), i)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestLeavesList:
+
+    def test_leaves_list_1x4(self, xp):
+        # Tests leaves_list(Z) on a 1x4 linkage.
+        Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+        to_tree(Z)
+        assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15)
+
+    def test_leaves_list_2x4(self, xp):
+        # Tests leaves_list(Z) on a 2x4 linkage.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.float64)
+        to_tree(Z)
+        assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15)
+
+    def test_leaves_list_Q(self, xp):
+        for method in ['single', 'complete', 'average', 'weighted', 'centroid',
+                       'median', 'ward']:
+            self.check_leaves_list_Q(method, xp)
+
+    def check_leaves_list_Q(self, method, xp):
+        # Tests leaves_list(Z) on the Q data set
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        Z = linkage(X, method)
+        node = to_tree(Z)
+        assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15)
+
+    def test_Q_subtree_pre_order(self, xp):
+        # Tests that pre_order() works when called on sub-trees.
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        Z = linkage(X, 'single')
+        node = to_tree(Z)
+        assert_allclose(node.pre_order(), (node.get_left().pre_order()
+                                           + node.get_right().pre_order()),
+                        rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestCorrespond:
+
+    def test_correspond_empty(self, xp):
+        # Tests correspond(Z, y) with empty linkage and condensed distance matrix.
+        y = xp.zeros((0,), dtype=xp.float64)
+        Z = xp.zeros((0,4), dtype=xp.float64)
+        assert_raises(ValueError, correspond, Z, y)
+
+    def test_correspond_2_and_up(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes.
+        for i in range(2, 4):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            assert_(correspond(Z, y))
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            y = xp.asarray(y)
+            Z = linkage(y)
+            assert_(correspond(Z, y))
+
+    def test_correspond_4_and_up(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes. Correspondence should be false.
+        for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) +
+                       list(zip(list(range(3, 5)), list(range(2, 4))))):
+            y = np.random.rand(i*(i-1)//2)
+            y2 = np.random.rand(j*(j-1)//2)
+            y = xp.asarray(y)
+            y2 = xp.asarray(y2)
+            Z = linkage(y)
+            Z2 = linkage(y2)
+            assert not correspond(Z, y2)
+            assert not correspond(Z2, y)
+
+    def test_correspond_4_and_up_2(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes. Correspondence should be false.
+        for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) +
+                       list(zip(list(range(2, 7)), list(range(16, 21))))):
+            y = np.random.rand(i*(i-1)//2)
+            y2 = np.random.rand(j*(j-1)//2)
+            y = xp.asarray(y)
+            y2 = xp.asarray(y2)
+            Z = linkage(y)
+            Z2 = linkage(y2)
+            assert not correspond(Z, y2)
+            assert not correspond(Z2, y)
+
+    def test_num_obs_linkage_multi_matrix(self, xp):
+        # Tests num_obs_linkage with observation matrices of multiple sizes.
+        for n in range(2, 10):
+            X = np.random.rand(n, 4)
+            Y = pdist(X)
+            Y = xp.asarray(Y)
+            Z = linkage(Y)
+            assert_equal(num_obs_linkage(Z), n)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestIsMonotonic:
+
+    def test_is_monotonic_empty(self, xp):
+        # Tests is_monotonic(Z) on an empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, is_monotonic, Z)
+
+    def test_is_monotonic_1x4(self, xp):
+        # Tests is_monotonic(Z) on 1x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_2x4_T(self, xp):
+        # Tests is_monotonic(Z) on 2x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 3]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_2x4_F(self, xp):
+        # Tests is_monotonic(Z) on 2x4 linkage. Expecting False.
+        Z = xp.asarray([[0, 1, 0.4, 2],
+                        [2, 3, 0.3, 3]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_T(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F1(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.2, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F2(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False.
+        Z = xp.asarray([[0, 1, 0.8, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F3(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.2, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_tdist_linkage1(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # tdist data set. Expecting True.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+        assert is_monotonic(Z)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+    def test_is_monotonic_tdist_linkage2(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # tdist data set. Perturbing. Expecting False.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+        Z[2,2] = 0.0
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_Q_linkage(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # Q data set. Expecting True.
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        Z = linkage(X, 'single')
+        assert is_monotonic(Z)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestMaxDists:
+
+    def test_maxdists_empty_linkage(self, xp):
+        # Tests maxdists(Z) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxdists, Z)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+    def test_maxdists_one_cluster_linkage(self, xp):
+        # Tests maxdists(Z) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        MD = maxdists(Z)
+        expectedMD = calculate_maximum_distances(Z, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+    def test_maxdists_Q_linkage(self, xp):
+        for method in ['single', 'complete', 'ward', 'centroid', 'median']:
+            self.check_maxdists_Q_linkage(method, xp)
+
+    def check_maxdists_Q_linkage(self, method, xp):
+        # Tests maxdists(Z) on the Q data set
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        Z = linkage(X, method)
+        MD = maxdists(Z)
+        expectedMD = calculate_maximum_distances(Z, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+class TestMaxInconsts:
+
+    @skip_xp_backends(cpu_only=True)
+    def test_maxinconsts_empty_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxinconsts, Z, R)
+
+    def test_maxinconsts_difrow_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on linkage and inconsistency matrices with
+        # different numbers of clusters. Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = np.random.rand(2, 4)
+        R = xp.asarray(R)
+        assert_raises(ValueError, maxinconsts, Z, R)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+                      cpu_only=True)
+    def test_maxinconsts_one_cluster_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        MD = maxinconsts(Z, R)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+                      cpu_only=True)
+    def test_maxinconsts_Q_linkage(self, xp):
+        for method in ['single', 'complete', 'ward', 'centroid', 'median']:
+            self.check_maxinconsts_Q_linkage(method, xp)
+
+    def check_maxinconsts_Q_linkage(self, method, xp):
+        # Tests maxinconsts(Z, R) on the Q data set
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        Z = linkage(X, method)
+        R = inconsistent(Z)
+        MD = maxinconsts(Z, R)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+class TestMaxRStat:
+
+    def test_maxRstat_invalid_index(self, xp):
+        for i in [3.3, -1, 4]:
+            self.check_maxRstat_invalid_index(i, xp)
+
+    def check_maxRstat_invalid_index(self, i, xp):
+        # Tests maxRstat(Z, R, i). Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        if isinstance(i, int):
+            assert_raises(ValueError, maxRstat, Z, R, i)
+        else:
+            assert_raises(TypeError, maxRstat, Z, R, i)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_maxRstat_empty_linkage(self, xp):
+        for i in range(4):
+            self.check_maxRstat_empty_linkage(i, xp)
+
+    def check_maxRstat_empty_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxRstat, Z, R, i)
+
+    def test_maxRstat_difrow_linkage(self, xp):
+        for i in range(4):
+            self.check_maxRstat_difrow_linkage(i, xp)
+
+    def check_maxRstat_difrow_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with
+        # different numbers of clusters. Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = np.random.rand(2, 4)
+        R = xp.asarray(R)
+        assert_raises(ValueError, maxRstat, Z, R, i)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+                      cpu_only=True)
+    def test_maxRstat_one_cluster_linkage(self, xp):
+        for i in range(4):
+            self.check_maxRstat_one_cluster_linkage(i, xp)
+
+    def check_maxRstat_one_cluster_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        MD = maxRstat(Z, R, 1)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+                      cpu_only=True)
+    def test_maxRstat_Q_linkage(self, xp):
+        for method in ['single', 'complete', 'ward', 'centroid', 'median']:
+            for i in range(4):
+                self.check_maxRstat_Q_linkage(method, i, xp)
+
+    def check_maxRstat_Q_linkage(self, method, i, xp):
+        # Tests maxRstat(Z, R, i) on the Q data set
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        Z = linkage(X, method)
+        R = inconsistent(Z)
+        MD = maxRstat(Z, R, 1)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestDendrogram:
+
+    def test_dendrogram_single_linkage_tdist(self, xp):
+        # Tests dendrogram calculation on single linkage of the tdist data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+        R = dendrogram(Z, no_plot=True)
+        leaves = R["leaves"]
+        assert_equal(leaves, [2, 5, 1, 0, 3, 4])
+
+    def test_valid_orientation(self, xp):
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+        assert_raises(ValueError, dendrogram, Z, orientation="foo")
+
+    def test_labels_as_array_or_list(self, xp):
+        # test for gh-12418
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+        labels = [1, 3, 2, 6, 4, 5]
+        result1 = dendrogram(Z, labels=xp.asarray(labels), no_plot=True)
+        result2 = dendrogram(Z, labels=labels, no_plot=True)
+        assert result1 == result2
+
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_valid_label_size(self, xp):
+        link = xp.asarray([
+            [0, 1, 1.0, 4],
+            [2, 3, 1.0, 5],
+            [4, 5, 2.0, 6],
+        ])
+        plt.figure()
+        with pytest.raises(ValueError) as exc_info:
+            dendrogram(link, labels=list(range(100)))
+        assert "Dimensions of Z and labels must be consistent."\
+               in str(exc_info.value)
+
+        with pytest.raises(
+                ValueError,
+                match="Dimensions of Z and labels must be consistent."):
+            dendrogram(link, labels=[])
+
+        plt.close()
+
+    @skip_xp_backends('torch',
+         reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+                ' and NumPy 2.0'
+    )
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_dendrogram_plot(self, xp):
+        for orientation in ['top', 'bottom', 'left', 'right']:
+            self.check_dendrogram_plot(orientation, xp)
+
+    def check_dendrogram_plot(self, orientation, xp):
+        # Tests dendrogram plotting.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+        expected = {'color_list': ['C1', 'C0', 'C0', 'C0', 'C0'],
+                    'dcoord': [[0.0, 138.0, 138.0, 0.0],
+                               [0.0, 219.0, 219.0, 0.0],
+                               [0.0, 255.0, 255.0, 219.0],
+                               [0.0, 268.0, 268.0, 255.0],
+                               [138.0, 295.0, 295.0, 268.0]],
+                    'icoord': [[5.0, 5.0, 15.0, 15.0],
+                               [45.0, 45.0, 55.0, 55.0],
+                               [35.0, 35.0, 50.0, 50.0],
+                               [25.0, 25.0, 42.5, 42.5],
+                               [10.0, 10.0, 33.75, 33.75]],
+                    'ivl': ['2', '5', '1', '0', '3', '4'],
+                    'leaves': [2, 5, 1, 0, 3, 4],
+                    'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0', 'C0'],
+                    }
+
+        fig = plt.figure()
+        ax = fig.add_subplot(221)
+
+        # test that dendrogram accepts ax keyword
+        R1 = dendrogram(Z, ax=ax, orientation=orientation)
+        R1['dcoord'] = np.asarray(R1['dcoord'])
+        assert_equal(R1, expected)
+
+        # test that dendrogram accepts and handle the leaf_font_size and
+        # leaf_rotation keywords
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_font_size=20, leaf_rotation=90)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_rotation(), 90)
+        assert_equal(testlabel.get_size(), 20)
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_rotation=90)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_rotation(), 90)
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_font_size=20)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_size(), 20)
+        plt.close()
+
+        # test plotting to gca (will import pylab)
+        R2 = dendrogram(Z, orientation=orientation)
+        plt.close()
+        R2['dcoord'] = np.asarray(R2['dcoord'])
+        assert_equal(R2, expected)
+
+    @skip_xp_backends('torch',
+          reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+                 ' and NumPy 2.0'
+     )
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_dendrogram_truncate_mode(self, xp):
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+
+        R = dendrogram(Z, 2, 'lastp', show_contracted=True)
+        plt.close()
+        R['dcoord'] = np.asarray(R['dcoord'])
+        assert_equal(R, {'color_list': ['C0'],
+                         'dcoord': [[0.0, 295.0, 295.0, 0.0]],
+                         'icoord': [[5.0, 5.0, 15.0, 15.0]],
+                         'ivl': ['(2)', '(4)'],
+                         'leaves': [6, 9],
+                         'leaves_color_list': ['C0', 'C0'],
+                         })
+
+        R = dendrogram(Z, 2, 'mtica', show_contracted=True)
+        plt.close()
+        R['dcoord'] = np.asarray(R['dcoord'])
+        assert_equal(R, {'color_list': ['C1', 'C0', 'C0', 'C0'],
+                         'dcoord': [[0.0, 138.0, 138.0, 0.0],
+                                    [0.0, 255.0, 255.0, 0.0],
+                                    [0.0, 268.0, 268.0, 255.0],
+                                    [138.0, 295.0, 295.0, 268.0]],
+                         'icoord': [[5.0, 5.0, 15.0, 15.0],
+                                    [35.0, 35.0, 45.0, 45.0],
+                                    [25.0, 25.0, 40.0, 40.0],
+                                    [10.0, 10.0, 32.5, 32.5]],
+                         'ivl': ['2', '5', '1', '0', '(2)'],
+                         'leaves': [2, 5, 1, 0, 7],
+                         'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0'],
+                         })
+
+    @pytest.fixture
+    def dendrogram_lock(self):
+        return Lock()
+
+    def test_dendrogram_colors(self, xp, dendrogram_lock):
+        # Tests dendrogram plots with alternate colors
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+
+        with dendrogram_lock:
+            # Global color palette might be changed concurrently
+            set_link_color_palette(['c', 'm', 'y', 'k'])
+            R = dendrogram(Z, no_plot=True,
+                        above_threshold_color='g', color_threshold=250)
+            set_link_color_palette(['g', 'r', 'c', 'm', 'y', 'k'])
+
+            color_list = R['color_list']
+            assert_equal(color_list, ['c', 'm', 'g', 'g', 'g'])
+
+            # reset color palette (global list)
+            set_link_color_palette(None)
+
+    def test_dendrogram_leaf_colors_zero_dist(self, xp):
+        # tests that the colors of leafs are correct for tree
+        # with two identical points
+        x = xp.asarray([[1, 0, 0],
+                        [0, 0, 1],
+                        [0, 2, 0],
+                        [0, 0, 1],
+                        [0, 1, 0],
+                        [0, 1, 0]])
+        z = linkage(x, "single")
+        d = dendrogram(z, no_plot=True)
+        exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+        colors = d["leaves_color_list"]
+        assert_equal(colors, exp_colors)
+
+    def test_dendrogram_leaf_colors(self, xp):
+        # tests that the colors are correct for a tree
+        # with two near points ((0, 0, 1.1) and (0, 0, 1))
+        x = xp.asarray([[1, 0, 0],
+                        [0, 0, 1.1],
+                        [0, 2, 0],
+                        [0, 0, 1],
+                        [0, 1, 0],
+                        [0, 1, 0]])
+        z = linkage(x, "single")
+        d = dendrogram(z, no_plot=True)
+        exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+        colors = d["leaves_color_list"]
+        assert_equal(colors, exp_colors)
+
+
+def calculate_maximum_distances(Z, xp):
+    # Used for testing correctness of maxdists.
+    n = Z.shape[0] + 1
+    B = xp.zeros((n-1,), dtype=Z.dtype)
+    q = xp.zeros((3,))
+    for i in range(0, n - 1):
+        q[:] = 0.0
+        left = Z[i, 0]
+        right = Z[i, 1]
+        if left >= n:
+            q[0] = B[xp.asarray(left, dtype=xp.int64) - n]
+        if right >= n:
+            q[1] = B[xp.asarray(right, dtype=xp.int64) - n]
+        q[2] = Z[i, 2]
+        B[i] = xp.max(q)
+    return B
+
+
+def calculate_maximum_inconsistencies(Z, R, k=3, xp=np):
+    # Used for testing correctness of maxinconsts.
+    n = Z.shape[0] + 1
+    dtype = xp.result_type(Z, R)
+    B = xp.zeros((n-1,), dtype=dtype)
+    q = xp.zeros((3,))
+    for i in range(0, n - 1):
+        q[:] = 0.0
+        left = Z[i, 0]
+        right = Z[i, 1]
+        if left >= n:
+            q[0] = B[xp.asarray(left, dtype=xp.int64) - n]
+        if right >= n:
+            q[1] = B[xp.asarray(right, dtype=xp.int64) - n]
+        q[2] = R[i, k]
+        B[i] = xp.max(q)
+    return B
+
+
+@pytest.mark.thread_unsafe
+@skip_xp_backends(cpu_only=True)
+def test_unsupported_uncondensed_distance_matrix_linkage_warning(xp):
+    assert_warns(ClusterWarning, linkage, xp.asarray([[0, 1], [1, 0]]))
+
+
+def test_euclidean_linkage_value_error(xp):
+    for method in scipy.cluster.hierarchy._EUCLIDEAN_METHODS:
+        assert_raises(ValueError, linkage, xp.asarray([[1, 1], [1, 1]]),
+                      method=method, metric='cityblock')
+
+
+@skip_xp_backends(cpu_only=True)
+def test_2x2_linkage(xp):
+    Z1 = linkage(xp.asarray([1]), method='single', metric='euclidean')
+    Z2 = linkage(xp.asarray([[0, 1], [0, 0]]), method='single', metric='euclidean')
+    xp_assert_close(Z1, Z2, rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+def test_node_compare(xp):
+    np.random.seed(23)
+    nobs = 50
+    X = np.random.randn(nobs, 4)
+    X = xp.asarray(X)
+    Z = scipy.cluster.hierarchy.ward(X)
+    tree = to_tree(Z)
+    assert_(tree > tree.get_left())
+    assert_(tree.get_right() > tree.get_left())
+    assert_(tree.get_right() == tree.get_right())
+    assert_(tree.get_right() != tree.get_left())
+
+
+@skip_xp_backends(np_only=True, reason='`cut_tree` uses non-standard indexing')
+def test_cut_tree(xp):
+    np.random.seed(23)
+    nobs = 50
+    X = np.random.randn(nobs, 4)
+    X = xp.asarray(X)
+    Z = scipy.cluster.hierarchy.ward(X)
+    cutree = cut_tree(Z)
+
+    # cutree.dtype varies between int32 and int64 over platforms
+    xp_assert_close(cutree[:, 0], xp.arange(nobs), rtol=1e-15, check_dtype=False)
+    xp_assert_close(cutree[:, -1], xp.zeros(nobs), rtol=1e-15, check_dtype=False)
+    assert_equal(np.asarray(cutree).max(0), np.arange(nobs - 1, -1, -1))
+
+    xp_assert_close(cutree[:, [-5]], cut_tree(Z, n_clusters=5), rtol=1e-15)
+    xp_assert_close(cutree[:, [-5, -10]], cut_tree(Z, n_clusters=[5, 10]), rtol=1e-15)
+    xp_assert_close(cutree[:, [-10, -5]], cut_tree(Z, n_clusters=[10, 5]), rtol=1e-15)
+
+    nodes = _order_cluster_tree(Z)
+    heights = xp.asarray([node.dist for node in nodes])
+
+    xp_assert_close(cutree[:, np.searchsorted(heights, [5])],
+                    cut_tree(Z, height=5), rtol=1e-15)
+    xp_assert_close(cutree[:, np.searchsorted(heights, [5, 10])],
+                    cut_tree(Z, height=[5, 10]), rtol=1e-15)
+    xp_assert_close(cutree[:, np.searchsorted(heights, [10, 5])],
+                    cut_tree(Z, height=[10, 5]), rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+def test_optimal_leaf_ordering(xp):
+    # test with the distance vector y
+    Z = optimal_leaf_ordering(linkage(xp.asarray(hierarchy_test_data.ytdist)),
+                              xp.asarray(hierarchy_test_data.ytdist))
+    expectedZ = hierarchy_test_data.linkage_ytdist_single_olo
+    xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    # test with the observation matrix X
+    Z = optimal_leaf_ordering(linkage(xp.asarray(hierarchy_test_data.X), 'ward'),
+                              xp.asarray(hierarchy_test_data.X))
+    expectedZ = hierarchy_test_data.linkage_X_ward_olo
+    xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+
+@skip_xp_backends(np_only=True, reason='`Heap` only supports NumPy backend')
+def test_Heap(xp):
+    values = xp.asarray([2, -1, 0, -1.5, 3])
+    heap = Heap(values)
+
+    pair = heap.get_min()
+    assert_equal(pair['key'], 3)
+    assert_equal(pair['value'], -1.5)
+
+    heap.remove_min()
+    pair = heap.get_min()
+    assert_equal(pair['key'], 1)
+    assert_equal(pair['value'], -1)
+
+    heap.change_value(1, 2.5)
+    pair = heap.get_min()
+    assert_equal(pair['key'], 2)
+    assert_equal(pair['value'], 0)
+
+    heap.remove_min()
+    heap.remove_min()
+
+    heap.change_value(1, 10)
+    pair = heap.get_min()
+    assert_equal(pair['key'], 4)
+    assert_equal(pair['value'], 3)
+
+    heap.remove_min()
+    pair = heap.get_min()
+    assert_equal(pair['key'], 1)
+    assert_equal(pair['value'], 10)
+
+
+@skip_xp_backends(cpu_only=True)
+def test_centroid_neg_distance(xp):
+    # gh-21011
+    values = xp.asarray([0, 0, -1])
+    with pytest.raises(ValueError):
+        # This is just checking that this doesn't crash
+        linkage(values, method='centroid')
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_vq.py b/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0321e7d81d79472ffc773baeee806aad14212fc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/tests/test_vq.py
@@ -0,0 +1,450 @@
+import warnings
+import sys
+from copy import deepcopy
+from threading import Lock
+
+import numpy as np
+from numpy.testing import (
+    assert_array_equal, assert_equal, assert_, suppress_warnings
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.cluster.vq import (kmeans, kmeans2, py_vq, vq, whiten,
+                              ClusterError, _krandinit)
+from scipy.cluster import _vq
+from scipy.conftest import array_api_compatible
+from scipy.sparse._sputils import matrix
+
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, array_namespace, xp_copy, xp_assert_close, xp_assert_equal
+)
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+TESTDATA_2D = np.array([
+    -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68,
+    -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45,
+    2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28,
+    -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07,
+    -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29,
+    -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25,
+    2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21,
+    -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67,
+    -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94,
+    -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33,
+    2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8,
+    -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29,
+    2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75,
+    -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17,
+    0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44,
+    -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83,
+    0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28,
+    3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62,
+    -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35,
+    3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84,
+    -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75,
+    -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86,
+    -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83,
+    0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75,
+    -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03,
+    3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0,
+    3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99,
+    -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21,
+    1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75,
+    4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37,
+    -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0,
+    -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84,
+    2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69,
+    -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51,
+    -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71,
+    -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61,
+    2.11]).reshape((200, 2))
+
+
+# Global data
+X = np.array([[3.0, 3], [4, 3], [4, 2],
+              [9, 2], [5, 1], [6, 2], [9, 4],
+              [5, 2], [5, 4], [7, 4], [6, 5]])
+
+CODET1 = np.array([[3.0000, 3.0000],
+                   [6.2000, 4.0000],
+                   [5.8000, 1.8000]])
+
+CODET2 = np.array([[11.0/3, 8.0/3],
+                   [6.7500, 4.2500],
+                   [6.2500, 1.7500]])
+
+LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1])
+
+
+class TestWhiten:
+
+    def test_whiten(self, xp):
+        desired = xp.asarray([[5.08738849, 2.97091878],
+                            [3.19909255, 0.69660580],
+                            [4.51041982, 0.02640918],
+                            [4.38567074, 0.95120889],
+                            [2.32191480, 1.63195503]])
+
+        obs = xp.asarray([[0.98744510, 0.82766775],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+        xp_assert_close(whiten(obs), desired, rtol=1e-5)
+
+    @pytest.fixture
+    def whiten_lock(self):
+        return Lock()
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_whiten_zero_std(self, xp, whiten_lock):
+        desired = xp.asarray([[0., 1.0, 2.86666544],
+                              [0., 1.0, 1.32460034],
+                              [0., 1.0, 3.74382172]])
+
+        obs = xp.asarray([[0., 1., 0.74109533],
+                          [0., 1., 0.34243798],
+                          [0., 1., 0.96785929]])
+
+        with whiten_lock:
+            with warnings.catch_warnings(record=True) as w:
+                warnings.simplefilter('always')
+
+                xp_assert_close(whiten(obs), desired, rtol=1e-5)
+
+                assert_equal(len(w), 1)
+                assert_(issubclass(w[-1].category, RuntimeWarning))
+
+    def test_whiten_not_finite(self, xp):
+        for bad_value in xp.nan, xp.inf, -xp.inf:
+            obs = xp.asarray([[0.98744510, bad_value],
+                              [0.62093317, 0.19406729],
+                              [0.87545741, 0.00735733],
+                              [0.85124403, 0.26499712],
+                              [0.45067590, 0.45464607]])
+            assert_raises(ValueError, whiten, obs)
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_whiten_not_finite_matrix(self, xp):
+        for bad_value in np.nan, np.inf, -np.inf:
+            obs = matrix([[0.98744510, bad_value],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+            assert_raises(ValueError, whiten, obs)
+
+
+class TestVq:
+
+    @skip_xp_backends(cpu_only=True)
+    def test_py_vq(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        # label1.dtype varies between int32 and int64 over platforms
+        label1 = py_vq(xp.asarray(X), xp.asarray(initc))[0]
+        xp_assert_equal(label1, xp.asarray(LABEL1, dtype=xp.int64),
+                        check_dtype=False)
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_py_vq_matrix(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        # label1.dtype varies between int32 and int64 over platforms
+        label1 = py_vq(matrix(X), matrix(initc))[0]
+        assert_array_equal(label1, LABEL1)
+
+    @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend')
+    def test_vq(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        label1, _ = _vq.vq(xp.asarray(X), xp.asarray(initc))
+        assert_array_equal(label1, LABEL1)
+        _, _ = vq(xp.asarray(X), xp.asarray(initc))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_vq_matrix(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        label1, _ = _vq.vq(matrix(X), matrix(initc))
+        assert_array_equal(label1, LABEL1)
+        _, _ = vq(matrix(X), matrix(initc))
+
+    @skip_xp_backends(cpu_only=True)
+    def test_vq_1d(self, xp):
+        # Test special rank 1 vq algo, python implementation.
+        data = X[:, 0]
+        initc = data[:3]
+        a, b = _vq.vq(data, initc)
+        data = xp.asarray(data)
+        initc = xp.asarray(initc)
+        ta, tb = py_vq(data[:, np.newaxis], initc[:, np.newaxis])
+        # ta.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(ta, xp.asarray(a, dtype=xp.int64), check_dtype=False)
+        xp_assert_equal(tb, xp.asarray(b))
+
+    @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend')
+    def test__vq_sametype(self, xp):
+        a = xp.asarray([1.0, 2.0], dtype=xp.float64)
+        b = a.astype(xp.float32)
+        assert_raises(TypeError, _vq.vq, a, b)
+
+    @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend')
+    def test__vq_invalid_type(self, xp):
+        a = xp.asarray([1, 2], dtype=int)
+        assert_raises(TypeError, _vq.vq, a, a)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_vq_large_nfeat(self, xp):
+        X = np.random.rand(20, 20)
+        code_book = np.random.rand(3, 20)
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+        X = X.astype(np.float32)
+        code_book = code_book.astype(np.float32)
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0, dtype=xp.float64), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+    @skip_xp_backends(cpu_only=True)
+    def test_vq_large_features(self, xp):
+        X = np.random.rand(10, 5) * 1000000
+        code_book = np.random.rand(2, 5) * 1000000
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+
+# Whole class skipped on GPU for now;
+# once pdist/cdist are hooked up for CuPy, more tests will work
+@skip_xp_backends(cpu_only=True)
+class TestKMean:
+
+    def test_large_features(self, xp):
+        # Generate a data set with large values, and run kmeans on it to
+        # (regression for 1077).
+        d = 300
+        n = 100
+
+        m1 = np.random.randn(d)
+        m2 = np.random.randn(d)
+        x = 10000 * np.random.randn(n, d) - 20000 * m1
+        y = 10000 * np.random.randn(n, d) + 20000 * m2
+
+        data = np.empty((x.shape[0] + y.shape[0], d), np.float64)
+        data[:x.shape[0]] = x
+        data[x.shape[0]:] = y
+
+        # use `seed` to ensure backwards compatibility after SPEC7
+        kmeans(xp.asarray(data), 2, seed=1)
+
+    def test_kmeans_simple(self, xp):
+        rng = np.random.default_rng(54321)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans(xp.asarray(X), xp.asarray(initc), iter=1, rng=rng)[0]
+        xp_assert_close(code1, xp.asarray(CODET2))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_kmeans_simple_matrix(self, xp):
+        rng = np.random.default_rng(54321)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+        xp_assert_close(code1, CODET2)
+
+    def test_kmeans_lost_cluster(self, xp):
+        # This will cause kmeans to have a cluster with no points.
+        data = xp.asarray(TESTDATA_2D)
+        initk = xp.asarray([[-1.8127404, -0.67128041],
+                            [2.04621601, 0.07401111],
+                            [-2.31149087, -0.05160469]])
+
+        kmeans(data, initk)
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "One of the clusters is empty. Re-run kmeans with a "
+                       "different initialization")
+            kmeans2(data, initk, missing='warn')
+
+        assert_raises(ClusterError, kmeans2, data, initk, missing='raise')
+
+    def test_kmeans2_simple(self, xp):
+        rng = np.random.default_rng(12345678)
+        initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]]))
+        arrays = [xp.asarray] if SCIPY_ARRAY_API else [np.asarray, matrix]
+        for tp in arrays:
+            code1 = kmeans2(tp(X), tp(initc), iter=1, rng=rng)[0]
+            code2 = kmeans2(tp(X), tp(initc), iter=2, rng=rng)[0]
+
+            xp_assert_close(code1, xp.asarray(CODET1))
+            xp_assert_close(code2, xp.asarray(CODET2))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_kmeans2_simple_matrix(self, xp):
+        rng = np.random.default_rng(12345678)
+        initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]]))
+        code1 = kmeans2(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+        code2 = kmeans2(matrix(X), matrix(initc), iter=2, rng=rng)[0]
+
+        xp_assert_close(code1, CODET1)
+        xp_assert_close(code2, CODET2)
+
+    def test_kmeans2_rank1(self, xp):
+        data = xp.asarray(TESTDATA_2D)
+        data1 = data[:, 0]
+
+        initc = data1[:3]
+        code = xp_copy(initc, xp=xp)
+
+        # use `seed` to ensure backwards compatibility after SPEC7
+        kmeans2(data1, code, iter=1, seed=1)[0]
+        kmeans2(data1, code, iter=2)[0]
+
+    def test_kmeans2_rank1_2(self, xp):
+        data = xp.asarray(TESTDATA_2D)
+        data1 = data[:, 0]
+        kmeans2(data1, 2, iter=1)
+
+    def test_kmeans2_high_dim(self, xp):
+        # test kmeans2 when the number of dimensions exceeds the number
+        # of input points
+        data = xp.asarray(TESTDATA_2D)
+        data = xp.reshape(data, (20, 20))[:10, :]
+        kmeans2(data, 2)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_kmeans2_init(self, xp):
+        rng = np.random.default_rng(12345678)
+        data = xp.asarray(TESTDATA_2D)
+        k = 3
+
+        kmeans2(data, k, minit='points', rng=rng)
+        kmeans2(data[:, 1], k, minit='points', rng=rng)  # special case (1-D)
+
+        kmeans2(data, k, minit='++', rng=rng)
+        kmeans2(data[:, 1], k, minit='++', rng=rng)  # special case (1-D)
+
+        # minit='random' can give warnings, filter those
+        with suppress_warnings() as sup:
+            sup.filter(message="One of the clusters is empty. Re-run.")
+            kmeans2(data, k, minit='random', rng=rng)
+            kmeans2(data[:, 1], k, minit='random', rng=rng)  # special case (1-D)
+
+    @pytest.fixture
+    def krand_lock(self):
+        return Lock()
+
+    @pytest.mark.skipif(sys.platform == 'win32',
+                        reason='Fails with MemoryError in Wine.')
+    def test_krandinit(self, xp, krand_lock):
+        data = xp.asarray(TESTDATA_2D)
+        datas = [xp.reshape(data, (200, 2)),
+                 xp.reshape(data, (20, 20))[:10, :]]
+        k = int(1e6)
+        xp_test = array_namespace(data)
+        with krand_lock:
+            for data in datas:
+                rng = np.random.default_rng(1234)
+                init = _krandinit(data, k, rng, xp_test)
+                orig_cov = xpx.cov(data.T, xp=xp_test)
+                init_cov = xpx.cov(init.T, xp=xp_test)
+                xp_assert_close(orig_cov, init_cov, atol=1.1e-2)
+
+    def test_kmeans2_empty(self, xp):
+        # Regression test for gh-1032.
+        assert_raises(ValueError, kmeans2, xp.asarray([]), 2)
+
+    def test_kmeans_0k(self, xp):
+        # Regression test for gh-1073: fail when k arg is 0.
+        assert_raises(ValueError, kmeans, xp.asarray(X), 0)
+        assert_raises(ValueError, kmeans2, xp.asarray(X), 0)
+        assert_raises(ValueError, kmeans2, xp.asarray(X), xp.asarray([]))
+
+    def test_kmeans_large_thres(self, xp):
+        # Regression test for gh-1774
+        x = xp.asarray([1, 2, 3, 4, 10], dtype=xp.float64)
+        res = kmeans(x, 1, thresh=1e16)
+        xp_assert_close(res[0], xp.asarray([4.], dtype=xp.float64))
+        xp_assert_close(res[1], xp.asarray(2.3999999999999999, dtype=xp.float64)[()])
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_kmeans2_kpp_low_dim(self, xp):
+        # Regression test for gh-11462
+        rng = np.random.default_rng(2358792345678234568)
+        prev_res = xp.asarray([[-1.95266667, 0.898],
+                               [-3.153375, 3.3945]], dtype=xp.float64)
+        res, _ = kmeans2(xp.asarray(TESTDATA_2D), 2, minit='++', rng=rng)
+        xp_assert_close(res, prev_res)
+
+    @pytest.mark.thread_unsafe
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_kmeans2_kpp_high_dim(self, xp):
+        # Regression test for gh-11462
+        rng = np.random.default_rng(23587923456834568)
+        n_dim = 100
+        size = 10
+        centers = np.vstack([5 * np.ones(n_dim),
+                             -5 * np.ones(n_dim)])
+
+        data = np.vstack([
+            rng.multivariate_normal(centers[0], np.eye(n_dim), size=size),
+            rng.multivariate_normal(centers[1], np.eye(n_dim), size=size)
+        ])
+
+        data = xp.asarray(data)
+        res, _ = kmeans2(data, 2, minit='++', rng=rng)
+        xp_assert_equal(xp.sign(res), xp.sign(xp.asarray(centers)))
+
+    def test_kmeans_diff_convergence(self, xp):
+        # Regression test for gh-8727
+        obs = xp.asarray([-3, -1, 0, 1, 1, 8], dtype=xp.float64)
+        res = kmeans(obs, xp.asarray([-3., 0.99]))
+        xp_assert_close(res[0], xp.asarray([-0.4,  8.], dtype=xp.float64))
+        xp_assert_close(res[1], xp.asarray(1.0666666666666667, dtype=xp.float64)[()])
+
+    @skip_xp_backends('jax.numpy',
+                      reason='jax arrays do not support item assignment')
+    def test_kmeans_and_kmeans2_random_seed(self, xp):
+
+        seed_list = [
+            1234, np.random.RandomState(1234), np.random.default_rng(1234)
+        ]
+
+        for seed in seed_list:
+            seed1 = deepcopy(seed)
+            seed2 = deepcopy(seed)
+            data = xp.asarray(TESTDATA_2D)
+            # test for kmeans
+            res1, _ = kmeans(data, 2, seed=seed1)
+            res2, _ = kmeans(data, 2, seed=seed2)
+            xp_assert_close(res1, res2)  # should be same results
+            # test for kmeans2
+            for minit in ["random", "points", "++"]:
+                res1, _ = kmeans2(data, 2, minit=minit, seed=seed1)
+                res2, _ = kmeans2(data, 2, minit=minit, seed=seed2)
+                xp_assert_close(res1, res2)  # should be same results
diff --git a/venv/lib/python3.10/site-packages/scipy/cluster/vq.py b/venv/lib/python3.10/site-packages/scipy/cluster/vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..a791e2956070d0785556dd9c4f877004ae50cd9f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/cluster/vq.py
@@ -0,0 +1,828 @@
+"""
+K-means clustering and vector quantization (:mod:`scipy.cluster.vq`)
+====================================================================
+
+Provides routines for k-means clustering, generating code books
+from k-means models and quantizing vectors by comparing them with
+centroids in a code book.
+
+.. autosummary::
+   :toctree: generated/
+
+   whiten -- Normalize a group of observations so each feature has unit variance
+   vq -- Calculate code book membership of a set of observation vectors
+   kmeans -- Perform k-means on a set of observation vectors forming k clusters
+   kmeans2 -- A different implementation of k-means with more methods
+           -- for initializing centroids
+
+Background information
+----------------------
+The k-means algorithm takes as input the number of clusters to
+generate, k, and a set of observation vectors to cluster. It
+returns a set of centroids, one for each of the k clusters. An
+observation vector is classified with the cluster number or
+centroid index of the centroid closest to it.
+
+A vector v belongs to cluster i if it is closer to centroid i than
+any other centroid. If v belongs to i, we say centroid i is the
+dominating centroid of v. The k-means algorithm tries to
+minimize distortion, which is defined as the sum of the squared distances
+between each observation vector and its dominating centroid.
+The minimization is achieved by iteratively reclassifying
+the observations into clusters and recalculating the centroids until
+a configuration is reached in which the centroids are stable. One can
+also define a maximum number of iterations.
+
+Since vector quantization is a natural application for k-means,
+information theory terminology is often used. The centroid index
+or cluster index is also referred to as a "code" and the table
+mapping codes to centroids and, vice versa, is often referred to as a
+"code book". The result of k-means, a set of centroids, can be
+used to quantize vectors. Quantization aims to find an encoding of
+vectors that reduces the expected distortion.
+
+All routines expect obs to be an M by N array, where the rows are
+the observation vectors. The codebook is a k by N array, where the
+ith row is the centroid of code word i. The observation vectors
+and centroids have the same feature dimension.
+
+As an example, suppose we wish to compress a 24-bit color image
+(each pixel is represented by one byte for red, one for blue, and
+one for green) before sending it over the web. By using a smaller
+8-bit encoding, we can reduce the amount of data by two
+thirds. Ideally, the colors for each of the 256 possible 8-bit
+encoding values should be chosen to minimize distortion of the
+color. Running k-means with k=256 generates a code book of 256
+codes, which fills up all possible 8-bit sequences. Instead of
+sending a 3-byte value for each pixel, the 8-bit centroid index
+(or code word) of the dominating centroid is transmitted. The code
+book is also sent over the wire so each 8-bit code can be
+translated back to a 24-bit pixel value representation. If the
+image of interest was of an ocean, we would expect many 24-bit
+blues to be represented by 8-bit codes. If it was an image of a
+human face, more flesh-tone colors would be represented in the
+code book.
+
+"""
+import warnings
+import numpy as np
+from collections import deque
+from scipy._lib._array_api import (
+    _asarray, array_namespace, xp_size, xp_copy
+)
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng)
+from scipy._lib import array_api_extra as xpx
+from scipy.spatial.distance import cdist
+
+from . import _vq
+
+__docformat__ = 'restructuredtext'
+
+__all__ = ['whiten', 'vq', 'kmeans', 'kmeans2']
+
+
+class ClusterError(Exception):
+    pass
+
+
+def whiten(obs, check_finite=True):
+    """
+    Normalize a group of observations on a per feature basis.
+
+    Before running k-means, it is beneficial to rescale each feature
+    dimension of the observation set by its standard deviation (i.e. "whiten"
+    it - as in "white noise" where each frequency has equal power).
+    Each feature is divided by its standard deviation across all observations
+    to give it unit variance.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the array is an observation.  The
+        columns are the features seen during each observation.
+
+        >>> #         f0    f1    f2
+        >>> obs = [[  1.,   1.,   1.],  #o0
+        ...        [  2.,   2.,   2.],  #o1
+        ...        [  3.,   3.,   3.],  #o2
+        ...        [  4.,   4.,   4.]]  #o3
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    result : ndarray
+        Contains the values in `obs` scaled by the standard deviation
+        of each column.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import whiten
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7,]])
+    >>> whiten(features)
+    array([[ 4.17944278,  2.69811351,  7.21248917],
+           [ 3.29956009,  2.93273208,  9.33380951],
+           [ 1.75976538,  0.7038557 ,  7.21248917]])
+
+    """
+    xp = array_namespace(obs)
+    obs = _asarray(obs, check_finite=check_finite, xp=xp)
+    std_dev = xp.std(obs, axis=0)
+    zero_std_mask = std_dev == 0
+    if xp.any(zero_std_mask):
+        std_dev[zero_std_mask] = 1.0
+        warnings.warn("Some columns have standard deviation zero. "
+                      "The values of these columns will not change.",
+                      RuntimeWarning, stacklevel=2)
+    return obs / std_dev
+
+
+def vq(obs, code_book, check_finite=True):
+    """
+    Assign codes from a code book to observations.
+
+    Assigns a code from a code book to each observation. Each
+    observation vector in the 'M' by 'N' `obs` array is compared with the
+    centroids in the code book and assigned the code of the closest
+    centroid.
+
+    The features in `obs` should have unit variance, which can be
+    achieved by passing them through the whiten function. The code
+    book can be created with the k-means algorithm or a different
+    encoding algorithm.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the 'M' x 'N' array is an observation. The columns are
+        the "features" seen during each observation. The features must be
+        whitened first using the whiten function or something equivalent.
+    code_book : ndarray
+        The code book is usually generated using the k-means algorithm.
+        Each row of the array holds a different code, and the columns are
+        the features of the code.
+
+         >>> #              f0    f1    f2   f3
+         >>> code_book = [
+         ...             [  1.,   2.,   3.,   4.],  #c0
+         ...             [  1.,   2.,   3.,   4.],  #c1
+         ...             [  1.,   2.,   3.,   4.]]  #c2
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        A length M array holding the code book index for each observation.
+    dist : ndarray
+        The distortion (distance) between the observation and its nearest
+        code.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq
+    >>> code_book = np.array([[1., 1., 1.],
+    ...                       [2., 2., 2.]])
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7]])
+    >>> vq(features, code_book)
+    (array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239]))
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+    ct = xp.result_type(obs, code_book)
+
+    c_obs = xp.astype(obs, ct, copy=False)
+    c_code_book = xp.astype(code_book, ct, copy=False)
+
+    if xp.isdtype(ct, kind='real floating'):
+        c_obs = np.asarray(c_obs)
+        c_code_book = np.asarray(c_code_book)
+        result = _vq.vq(c_obs, c_code_book)
+        return xp.asarray(result[0]), xp.asarray(result[1])
+    return py_vq(obs, code_book, check_finite=False)
+
+
+def py_vq(obs, code_book, check_finite=True):
+    """ Python version of vq algorithm.
+
+    The algorithm computes the Euclidean distance between each
+    observation and every frame in the code_book.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Expects a rank 2 array. Each row is one observation.
+    code_book : ndarray
+        Code book to use. Same format than obs. Should have same number of
+        features (e.g., columns) than obs.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        code[i] gives the label of the ith obversation; its code is
+        code_book[code[i]].
+    mind_dist : ndarray
+        min_dist[i] gives the distance between the ith observation and its
+        corresponding code.
+
+    Notes
+    -----
+    This function is slower than the C version but works for
+    all input types. If the inputs have the wrong types for the
+    C versions of the function, this one is called as a last resort.
+
+    It is about 20 times slower than the C version.
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+
+    if obs.ndim != code_book.ndim:
+        raise ValueError("Observation and code_book should have the same rank")
+
+    if obs.ndim == 1:
+        obs = obs[:, xp.newaxis]
+        code_book = code_book[:, xp.newaxis]
+
+    # Once `cdist` has array API support, this `xp.asarray` call can be removed
+    dist = xp.asarray(cdist(obs, code_book))
+    code = xp.argmin(dist, axis=1)
+    min_dist = xp.min(dist, axis=1)
+    return code, min_dist
+
+
+def _kmeans(obs, guess, thresh=1e-5, xp=None):
+    """ "raw" version of k-means.
+
+    Returns
+    -------
+    code_book
+        The lowest distortion codebook found.
+    avg_dist
+        The average distance a observation is from a code in the book.
+        Lower means the code_book matches the data better.
+
+    See Also
+    --------
+    kmeans : wrapper around k-means
+
+    Examples
+    --------
+    Note: not whitened in this example.
+
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import _kmeans
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 1.0,1.0]])
+    >>> book = np.array((features[0],features[2]))
+    >>> _kmeans(features,book)
+    (array([[ 1.7       ,  2.4       ],
+           [ 0.73333333,  1.13333333]]), 0.40563916697728591)
+
+    """
+    xp = np if xp is None else xp
+    code_book = guess
+    diff = xp.inf
+    prev_avg_dists = deque([diff], maxlen=2)
+    while diff > thresh:
+        # compute membership and distances between obs and code_book
+        obs_code, distort = vq(obs, code_book, check_finite=False)
+        prev_avg_dists.append(xp.mean(distort, axis=-1))
+        # recalc code_book as centroids of associated obs
+        obs = np.asarray(obs)
+        obs_code = np.asarray(obs_code)
+        code_book, has_members = _vq.update_cluster_means(obs, obs_code,
+                                                          code_book.shape[0])
+        obs = xp.asarray(obs)
+        obs_code = xp.asarray(obs_code)
+        code_book = xp.asarray(code_book)
+        has_members = xp.asarray(has_members)
+        code_book = code_book[has_members]
+        diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1])
+
+    return code_book, prev_avg_dists[1]
+
+
+@_transition_to_rng("seed")
+def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True,
+           *, rng=None):
+    """
+    Performs k-means on a set of observation vectors forming k clusters.
+
+    The k-means algorithm adjusts the classification of the observations
+    into clusters and updates the cluster centroids until the position of
+    the centroids is stable over successive iterations. In this
+    implementation of the algorithm, the stability of the centroids is
+    determined by comparing the absolute value of the change in the average
+    Euclidean distance between the observations and their corresponding
+    centroids against a threshold. This yields
+    a code book mapping centroids to codes and vice versa.
+
+    Parameters
+    ----------
+    obs : ndarray
+       Each row of the M by N array is an observation vector. The
+       columns are the features seen during each observation.
+       The features must be whitened first with the `whiten` function.
+
+    k_or_guess : int or ndarray
+       The number of centroids to generate. A code is assigned to
+       each centroid, which is also the row index of the centroid
+       in the code_book matrix generated.
+
+       The initial k centroids are chosen by randomly selecting
+       observations from the observation matrix. Alternatively,
+       passing a k by N array specifies the initial k centroids.
+
+    iter : int, optional
+       The number of times to run k-means, returning the codebook
+       with the lowest distortion. This argument is ignored if
+       initial centroids are specified with an array for the
+       ``k_or_guess`` parameter. This parameter does not represent the
+       number of iterations of the k-means algorithm.
+
+    thresh : float, optional
+       Terminates the k-means algorithm if the change in
+       distortion since the last k-means iteration is less than
+       or equal to threshold.
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    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``.
+
+    Returns
+    -------
+    codebook : ndarray
+       A k by N array of k centroids. The ith centroid
+       codebook[i] is represented with the code i. The centroids
+       and codes generated represent the lowest distortion seen,
+       not necessarily the globally minimal distortion.
+       Note that the number of centroids is not necessarily the same as the
+       ``k_or_guess`` parameter, because centroids assigned to no observations
+       are removed during iterations.
+
+    distortion : float
+       The mean (non-squared) Euclidean distance between the observations
+       passed and the centroids generated. Note the difference to the standard
+       definition of distortion in the context of the k-means algorithm, which
+       is the sum of the squared distances.
+
+    See Also
+    --------
+    kmeans2 : a different implementation of k-means clustering
+       with more methods for generating initial centroids but without
+       using a distortion change threshold as a stopping criterion.
+
+    whiten : must be called prior to passing an observation matrix
+       to kmeans.
+
+    Notes
+    -----
+    For more functionalities or optimal performance, you can use
+    `sklearn.cluster.KMeans `_.
+    `This `_
+    is a benchmark result of several implementations.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq, kmeans, whiten
+    >>> import matplotlib.pyplot as plt
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 0.1,0.1],
+    ...                       [ 0.2,1.8],
+    ...                       [ 2.0,0.5],
+    ...                       [ 0.3,1.5],
+    ...                       [ 1.0,1.0]])
+    >>> whitened = whiten(features)
+    >>> book = np.array((whitened[0],whitened[2]))
+    >>> kmeans(whitened,book)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 0.93218041,  1.24398691]]), 0.85684700941625547)
+
+    >>> codes = 3
+    >>> kmeans(whitened,codes)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 1.32544402,  0.65607529],
+           [ 0.40782893,  2.02786907]]), 0.5196582527686241)
+
+    >>> # Create 50 datapoints in two clusters a and b
+    >>> pts = 50
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts)
+    >>> b = rng.multivariate_normal([30, 10],
+    ...                             [[10, 2], [2, 1]],
+    ...                             size=pts)
+    >>> features = np.concatenate((a, b))
+    >>> # Whiten data
+    >>> whitened = whiten(features)
+    >>> # Find 2 clusters in the data
+    >>> codebook, distortion = kmeans(whitened, 2)
+    >>> # Plot whitened data and cluster centers in red
+    >>> plt.scatter(whitened[:, 0], whitened[:, 1])
+    >>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
+    >>> plt.show()
+
+    """
+    if isinstance(k_or_guess, int):
+        xp = array_namespace(obs)
+    else:
+        xp = array_namespace(obs, k_or_guess)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite)
+    if iter < 1:
+        raise ValueError(f"iter must be at least 1, got {iter}")
+
+    # Determine whether a count (scalar) or an initial guess (array) was passed.
+    if xp_size(guess) != 1:
+        if xp_size(guess) < 1:
+            raise ValueError(f"Asked for 0 clusters. Initial book was {guess}")
+        return _kmeans(obs, guess, thresh=thresh, xp=xp)
+
+    # k_or_guess is a scalar, now verify that it's an integer
+    k = int(guess)
+    if k != guess:
+        raise ValueError("If k_or_guess is a scalar, it must be an integer.")
+    if k < 1:
+        raise ValueError("Asked for %d clusters." % k)
+
+    rng = check_random_state(rng)
+
+    # initialize best distance value to a large value
+    best_dist = xp.inf
+    for i in range(iter):
+        # the initial code book is randomly selected from observations
+        guess = _kpoints(obs, k, rng, xp)
+        book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp)
+        if dist < best_dist:
+            best_book = book
+            best_dist = dist
+    return best_book, best_dist
+
+
+def _kpoints(data, k, rng, xp):
+    """Pick k points at random in data (one row = one observation).
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
+        dimensional data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    idx = rng.choice(data.shape[0], size=int(k), replace=False)
+    # convert to array with default integer dtype (avoids numpy#25607)
+    idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype)
+    return xp.take(data, idx, axis=0)
+
+
+def _krandinit(data, k, rng, xp):
+    """Returns k samples of a random variable whose parameters depend on data.
+
+    More precisely, it returns k observations sampled from a Gaussian random
+    variable whose mean and covariances are the ones estimated from the data.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    mu = xp.mean(data, axis=0)
+    k = np.asarray(k)
+
+    if data.ndim == 1:
+        _cov = xpx.cov(data, xp=xp)
+        x = rng.standard_normal(size=k)
+        x = xp.asarray(x)
+        x *= xp.sqrt(_cov)
+    elif data.shape[1] > data.shape[0]:
+        # initialize when the covariance matrix is rank deficient
+        _, s, vh = xp.linalg.svd(data - mu, full_matrices=False)
+        x = rng.standard_normal(size=(k, xp_size(s)))
+        x = xp.asarray(x)
+        sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.))
+        x = x @ sVh
+    else:
+        _cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp)
+
+        # k rows, d cols (one row = one obs)
+        # Generate k sample of a random variable ~ Gaussian(mu, cov)
+        x = rng.standard_normal(size=(k, xp_size(mu)))
+        x = xp.asarray(x)
+        x = x @ xp.linalg.cholesky(_cov).T
+
+    x += mu
+    return x
+
+
+def _kpp(data, k, rng, xp):
+    """ Picks k points in the data based on the kmeans++ method.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    init : ndarray
+        A 'k' by 'N' containing the initial centroids.
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+    """
+
+    ndim = len(data.shape)
+    if ndim == 1:
+        data = data[:, None]
+
+    dims = data.shape[1]
+
+    init = xp.empty((int(k), dims))
+
+    for i in range(k):
+        if i == 0:
+            init[i, :] = data[rng_integers(rng, data.shape[0]), :]
+
+        else:
+            D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0)
+            probs = D2/D2.sum()
+            cumprobs = probs.cumsum()
+            r = rng.uniform()
+            cumprobs = np.asarray(cumprobs)
+            init[i, :] = data[np.searchsorted(cumprobs, r), :]
+
+    if ndim == 1:
+        init = init[:, 0]
+    return init
+
+
+_valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp}
+
+
+def _missing_warn():
+    """Print a warning when called."""
+    warnings.warn("One of the clusters is empty. "
+                  "Re-run kmeans with a different initialization.",
+                  stacklevel=3)
+
+
+def _missing_raise():
+    """Raise a ClusterError when called."""
+    raise ClusterError("One of the clusters is empty. "
+                       "Re-run kmeans with a different initialization.")
+
+
+_valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise}
+
+
+@_transition_to_rng("seed")
+def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
+            missing='warn', check_finite=True, *, rng=None):
+    """
+    Classify a set of observations into k clusters using the k-means algorithm.
+
+    The algorithm attempts to minimize the Euclidean distance between
+    observations and centroids. Several initialization methods are
+    included.
+
+    Parameters
+    ----------
+    data : ndarray
+        A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
+        'M' array of 'M' 1-D observations.
+    k : int or ndarray
+        The number of clusters to form as well as the number of
+        centroids to generate. If `minit` initialization string is
+        'matrix', or if a ndarray is given instead, it is
+        interpreted as initial cluster to use instead.
+    iter : int, optional
+        Number of iterations of the k-means algorithm to run. Note
+        that this differs in meaning from the iters parameter to
+        the kmeans function.
+    thresh : float, optional
+        (not used yet)
+    minit : str, optional
+        Method for initialization. Available methods are 'random',
+        'points', '++' and 'matrix':
+
+        'random': generate k centroids from a Gaussian with mean and
+        variance estimated from the data.
+
+        'points': choose k observations (rows) at random from data for
+        the initial centroids.
+
+        '++': choose k observations accordingly to the kmeans++ method
+        (careful seeding)
+
+        'matrix': interpret the k parameter as a k by M (or length k
+        array for 1-D data) array of initial centroids.
+    missing : str, optional
+        Method to deal with empty clusters. Available methods are
+        'warn' and 'raise':
+
+        'warn': give a warning and continue.
+
+        'raise': raise an ClusterError and terminate the algorithm.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    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``.
+
+    Returns
+    -------
+    centroid : ndarray
+        A 'k' by 'N' array of centroids found at the last iteration of
+        k-means.
+    label : ndarray
+        label[i] is the code or index of the centroid the
+        ith observation is closest to.
+
+    See Also
+    --------
+    kmeans
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+
+    Examples
+    --------
+    >>> from scipy.cluster.vq import kmeans2
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    Create z, an array with shape (100, 2) containing a mixture of samples
+    from three multivariate normal distributions.
+
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45)
+    >>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30)
+    >>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25)
+    >>> z = np.concatenate((a, b, c))
+    >>> rng.shuffle(z)
+
+    Compute three clusters.
+
+    >>> centroid, label = kmeans2(z, 3, minit='points')
+    >>> centroid
+    array([[ 2.22274463, -0.61666946],  # may vary
+           [ 0.54069047,  5.86541444],
+           [ 6.73846769,  4.01991898]])
+
+    How many points are in each cluster?
+
+    >>> counts = np.bincount(label)
+    >>> counts
+    array([29, 51, 20])  # may vary
+
+    Plot the clusters.
+
+    >>> w0 = z[label == 0]
+    >>> w1 = z[label == 1]
+    >>> w2 = z[label == 2]
+    >>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0')
+    >>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1')
+    >>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2')
+    >>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids')
+    >>> plt.axis('equal')
+    >>> plt.legend(shadow=True)
+    >>> plt.show()
+
+    """
+    if int(iter) < 1:
+        raise ValueError(f"Invalid iter ({iter}), must be a positive integer.")
+    try:
+        miss_meth = _valid_miss_meth[missing]
+    except KeyError as e:
+        raise ValueError(f"Unknown missing method {missing!r}") from e
+
+    if isinstance(k, int):
+        xp = array_namespace(data)
+    else:
+        xp = array_namespace(data, k)
+    data = _asarray(data, xp=xp, check_finite=check_finite)
+    code_book = xp_copy(k, xp=xp)
+    if data.ndim == 1:
+        d = 1
+    elif data.ndim == 2:
+        d = data.shape[1]
+    else:
+        raise ValueError("Input of rank > 2 is not supported.")
+
+    if xp_size(data) < 1 or xp_size(code_book) < 1:
+        raise ValueError("Empty input is not supported.")
+
+    # If k is not a single value, it should be compatible with data's shape
+    if minit == 'matrix' or xp_size(code_book) > 1:
+        if data.ndim != code_book.ndim:
+            raise ValueError("k array doesn't match data rank")
+        nc = code_book.shape[0]
+        if data.ndim > 1 and code_book.shape[1] != d:
+            raise ValueError("k array doesn't match data dimension")
+    else:
+        nc = int(code_book)
+
+        if nc < 1:
+            raise ValueError("Cannot ask kmeans2 for %d clusters"
+                             " (k was %s)" % (nc, code_book))
+        elif nc != code_book:
+            warnings.warn("k was not an integer, was converted.", stacklevel=2)
+
+        try:
+            init_meth = _valid_init_meth[minit]
+        except KeyError as e:
+            raise ValueError(f"Unknown init method {minit!r}") from e
+        else:
+            rng = check_random_state(rng)
+            code_book = init_meth(data, code_book, rng, xp)
+
+    data = np.asarray(data)
+    code_book = np.asarray(code_book)
+    for i in range(iter):
+        # Compute the nearest neighbor for each obs using the current code book
+        label = vq(data, code_book, check_finite=check_finite)[0]
+        # Update the code book by computing centroids
+        new_code_book, has_members = _vq.update_cluster_means(data, label, nc)
+        if not has_members.all():
+            miss_meth()
+            # Set the empty clusters to their previous positions
+            new_code_book[~has_members] = code_book[~has_members]
+        code_book = new_code_book
+
+    return xp.asarray(code_book), xp.asarray(label)
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/__init__.py b/venv/lib/python3.10/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf939b249c17256b622c2f2756a5f34c4a128cc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/__init__.py
@@ -0,0 +1,358 @@
+r"""
+==================================
+Constants (:mod:`scipy.constants`)
+==================================
+
+.. currentmodule:: scipy.constants
+
+Physical and mathematical constants and units.
+
+
+Mathematical constants
+======================
+
+================  =================================================================
+``pi``            Pi
+``golden``        Golden ratio
+``golden_ratio``  Golden ratio
+================  =================================================================
+
+
+Physical constants
+==================
+The following physical constants are available as attributes of `scipy.constants`.
+All units are `SI `_.
+
+===========================  ================================================================  ===============
+Attribute                    Quantity                                                          Units
+===========================  ================================================================  ===============
+``c``                        speed of light in vacuum                                          m s^-1
+``speed_of_light``           speed of light in vacuum                                          m s^-1
+``mu_0``                     the magnetic constant :math:`\mu_0`                               N A^-2
+``epsilon_0``                the electric constant (vacuum permittivity), :math:`\epsilon_0`   F m^-1
+``h``                        the Planck constant :math:`h`                                     J Hz^-1
+``Planck``                   the Planck constant :math:`h`                                     J Hz^-1
+``hbar``                     the reduced Planck constant, :math:`\hbar = h/(2\pi)`             J s
+``G``                        Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``gravitational_constant``   Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``g``                        standard acceleration of gravity                                  m s^-2
+``e``                        elementary charge                                                 C
+``elementary_charge``        elementary charge                                                 C
+``R``                        molar gas constant                                                J mol^-1 K^-1
+``gas_constant``             molar gas constant                                                J mol^-1 K^-1
+``alpha``                    fine-structure constant                                           (unitless)
+``fine_structure``           fine-structure constant                                           (unitless)
+``N_A``                      Avogadro constant                                                 mol^-1
+``Avogadro``                 Avogadro constant                                                 mol^-1
+``k``                        Boltzmann constant                                                J K^-1
+``Boltzmann``                Boltzmann constant                                                J K^-1
+``sigma``                    Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Stefan_Boltzmann``         Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Wien``                     Wien wavelength displacement law constant                         m K
+``Rydberg``                  Rydberg constant                                                  m^-1
+``m_e``                      electron mass                                                     kg
+``electron_mass``            electron mass                                                     kg
+``m_p``                      proton mass                                                       kg
+``proton_mass``              proton mass                                                       kg
+``m_n``                      neutron mass                                                      kg
+``neutron_mass``             neutron mass                                                      kg
+===========================  ================================================================  ===============
+
+
+Constants database
+------------------
+
+In addition to the above variables, :mod:`scipy.constants` also contains the
+2022 CODATA recommended values [CODATA2022]_ database containing more physical
+constants.
+
+.. autosummary::
+   :toctree: generated/
+
+   value      -- Value in physical_constants indexed by key
+   unit       -- Unit in physical_constants indexed by key
+   precision  -- Relative precision in physical_constants indexed by key
+   find       -- Return list of physical_constant keys with a given string
+   ConstantWarning -- Constant sought not in newest CODATA data set
+
+.. data:: physical_constants
+
+   Dictionary of physical constants, of the format
+   ``physical_constants[name] = (value, unit, uncertainty)``.
+   The CODATA database uses ellipses to indicate that a value is defined
+   (exactly) in terms of others but cannot be represented exactly with the
+   allocated number of digits. In these cases, SciPy calculates the derived
+   value and reports it to the full precision of a Python ``float``. Although 
+   ``physical_constants`` lists the uncertainty as ``0.0`` to indicate that
+   the CODATA value is exact, the value in ``physical_constants`` is still
+   subject to the truncation error inherent in double-precision representation.
+
+Available constants:
+
+======================================================================  ====
+%(constant_names)s
+======================================================================  ====
+
+
+Units
+=====
+
+SI prefixes
+-----------
+
+============  =================================================================
+``quetta``    :math:`10^{30}`
+``ronna``     :math:`10^{27}`
+``yotta``     :math:`10^{24}`
+``zetta``     :math:`10^{21}`
+``exa``       :math:`10^{18}`
+``peta``      :math:`10^{15}`
+``tera``      :math:`10^{12}`
+``giga``      :math:`10^{9}`
+``mega``      :math:`10^{6}`
+``kilo``      :math:`10^{3}`
+``hecto``     :math:`10^{2}`
+``deka``      :math:`10^{1}`
+``deci``      :math:`10^{-1}`
+``centi``     :math:`10^{-2}`
+``milli``     :math:`10^{-3}`
+``micro``     :math:`10^{-6}`
+``nano``      :math:`10^{-9}`
+``pico``      :math:`10^{-12}`
+``femto``     :math:`10^{-15}`
+``atto``      :math:`10^{-18}`
+``zepto``     :math:`10^{-21}`
+``yocto``     :math:`10^{-24}`
+``ronto``     :math:`10^{-27}`
+``quecto``    :math:`10^{-30}`
+============  =================================================================
+
+Binary prefixes
+---------------
+
+============  =================================================================
+``kibi``      :math:`2^{10}`
+``mebi``      :math:`2^{20}`
+``gibi``      :math:`2^{30}`
+``tebi``      :math:`2^{40}`
+``pebi``      :math:`2^{50}`
+``exbi``      :math:`2^{60}`
+``zebi``      :math:`2^{70}`
+``yobi``      :math:`2^{80}`
+============  =================================================================
+
+Mass
+----
+
+=================  ============================================================
+``gram``           :math:`10^{-3}` kg
+``metric_ton``     :math:`10^{3}` kg
+``grain``          one grain in kg
+``lb``             one pound (avoirdupous) in kg
+``pound``          one pound (avoirdupous) in kg
+``blob``           one inch version of a slug in kg (added in 1.0.0)
+``slinch``         one inch version of a slug in kg (added in 1.0.0)
+``slug``           one slug in kg (added in 1.0.0)
+``oz``             one ounce in kg
+``ounce``          one ounce in kg
+``stone``          one stone in kg
+``grain``          one grain in kg
+``long_ton``       one long ton in kg
+``short_ton``      one short ton in kg
+``troy_ounce``     one Troy ounce in kg
+``troy_pound``     one Troy pound in kg
+``carat``          one carat in kg
+``m_u``            atomic mass constant (in kg)
+``u``              atomic mass constant (in kg)
+``atomic_mass``    atomic mass constant (in kg)
+=================  ============================================================
+
+Angle
+-----
+
+=================  ============================================================
+``degree``         degree in radians
+``arcmin``         arc minute in radians
+``arcminute``      arc minute in radians
+``arcsec``         arc second in radians
+``arcsecond``      arc second in radians
+=================  ============================================================
+
+
+Time
+----
+
+=================  ============================================================
+``minute``         one minute in seconds
+``hour``           one hour in seconds
+``day``            one day in seconds
+``week``           one week in seconds
+``year``           one year (365 days) in seconds
+``Julian_year``    one Julian year (365.25 days) in seconds
+=================  ============================================================
+
+
+Length
+------
+
+=====================  ============================================================
+``inch``               one inch in meters
+``foot``               one foot in meters
+``yard``               one yard in meters
+``mile``               one mile in meters
+``mil``                one mil in meters
+``pt``                 one point in meters
+``point``              one point in meters
+``survey_foot``        one survey foot in meters
+``survey_mile``        one survey mile in meters
+``nautical_mile``      one nautical mile in meters
+``fermi``              one Fermi in meters
+``angstrom``           one Angstrom in meters
+``micron``             one micron in meters
+``au``                 one astronomical unit in meters
+``astronomical_unit``  one astronomical unit in meters
+``light_year``         one light year in meters
+``parsec``             one parsec in meters
+=====================  ============================================================
+
+Pressure
+--------
+
+=================  ============================================================
+``atm``            standard atmosphere in pascals
+``atmosphere``     standard atmosphere in pascals
+``bar``            one bar in pascals
+``torr``           one torr (mmHg) in pascals
+``mmHg``           one torr (mmHg) in pascals
+``psi``            one psi in pascals
+=================  ============================================================
+
+Area
+----
+
+=================  ============================================================
+``hectare``        one hectare in square meters
+``acre``           one acre in square meters
+=================  ============================================================
+
+
+Volume
+------
+
+===================    ========================================================
+``liter``              one liter in cubic meters
+``litre``              one liter in cubic meters
+``gallon``             one gallon (US) in cubic meters
+``gallon_US``          one gallon (US) in cubic meters
+``gallon_imp``         one gallon (UK) in cubic meters
+``fluid_ounce``        one fluid ounce (US) in cubic meters
+``fluid_ounce_US``     one fluid ounce (US) in cubic meters
+``fluid_ounce_imp``    one fluid ounce (UK) in cubic meters
+``bbl``                one barrel in cubic meters
+``barrel``             one barrel in cubic meters
+===================    ========================================================
+
+Speed
+-----
+
+==================    ==========================================================
+``kmh``               kilometers per hour in meters per second
+``mph``               miles per hour in meters per second
+``mach``              one Mach (approx., at 15 C, 1 atm) in meters per second
+``speed_of_sound``    one Mach (approx., at 15 C, 1 atm) in meters per second
+``knot``              one knot in meters per second
+==================    ==========================================================
+
+
+Temperature
+-----------
+
+=====================  =======================================================
+``zero_Celsius``       zero of Celsius scale in Kelvin
+``degree_Fahrenheit``  one Fahrenheit (only differences) in Kelvins
+=====================  =======================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   convert_temperature
+
+Energy
+------
+
+====================  =======================================================
+``eV``                one electron volt in Joules
+``electron_volt``     one electron volt in Joules
+``calorie``           one calorie (thermochemical) in Joules
+``calorie_th``        one calorie (thermochemical) in Joules
+``calorie_IT``        one calorie (International Steam Table calorie, 1956) in Joules
+``erg``               one erg in Joules
+``Btu``               one British thermal unit (International Steam Table) in Joules
+``Btu_IT``            one British thermal unit (International Steam Table) in Joules
+``Btu_th``            one British thermal unit (thermochemical) in Joules
+``ton_TNT``           one ton of TNT in Joules
+====================  =======================================================
+
+Power
+-----
+
+====================  =======================================================
+``hp``                one horsepower in watts
+``horsepower``        one horsepower in watts
+====================  =======================================================
+
+Force
+-----
+
+====================  =======================================================
+``dyn``               one dyne in newtons
+``dyne``              one dyne in newtons
+``lbf``               one pound force in newtons
+``pound_force``       one pound force in newtons
+``kgf``               one kilogram force in newtons
+``kilogram_force``    one kilogram force in newtons
+====================  =======================================================
+
+Optics
+------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambda2nu
+   nu2lambda
+
+References
+==========
+
+.. [CODATA2022] CODATA Recommended Values of the Fundamental
+   Physical Constants 2022.
+
+   https://physics.nist.gov/cuu/Constants/
+
+"""  # noqa: E501
+# Modules contributed by BasSw (wegwerp@gmail.com)
+from ._codata import *
+from ._constants import *
+from ._codata import _obsolete_constants, physical_constants
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import codata, constants
+
+_constant_names_list = [(_k.lower(), _k, _v)
+                        for _k, _v in physical_constants.items()
+                        if _k not in _obsolete_constants]
+_constant_names = "\n".join(["``{}``{}  {} {}".format(_x[1], " "*(66-len(_x[1])),
+                                                  _x[2][0], _x[2][1])
+                             for _x in sorted(_constant_names_list)])
+if __doc__:
+    __doc__ = __doc__ % dict(constant_names=_constant_names)
+
+del _constant_names
+del _constant_names_list
+
+__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.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ba789b539062fbeb5862cccf67453b534768af8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0ec8901ab7116b75789b0564fab7f8d6a797b6e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cf1be1b4cdfa2d708a90f9da96483cc2256f2fb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d73daeb9f829848daebe7eedf05c00e90d96a1d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/_codata.py b/venv/lib/python3.10/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..4457a8089d9c4b7ba159519e6ec1606fb7b74070
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/_codata.py
@@ -0,0 +1,2266 @@
+"""
+Fundamental Physical Constants
+------------------------------
+
+These constants are taken from CODATA Recommended Values of the Fundamental
+Physical Constants 2022.
+
+Object
+------
+physical_constants : dict
+    A dictionary containing physical constants. Keys are the names of physical
+    constants, values are tuples (value, units, precision).
+
+Functions
+---------
+value(key):
+    Returns the value of the physical constant(key).
+unit(key):
+    Returns the units of the physical constant(key).
+precision(key):
+    Returns the relative precision of the physical constant(key).
+find(sub):
+    Prints or returns list of keys containing the string sub, default is all.
+
+Source
+------
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set. Also available is an introduction to the
+constants for non-experts at
+
+https://physics.nist.gov/cuu/Constants/introduction.html
+
+References
+----------
+Theoretical and experimental publications relevant to the fundamental constants
+and closely related precision measurements published since the mid 1980s, but
+also including many older papers of particular interest, some of which date
+back to the 1800s. To search the bibliography, visit
+
+https://physics.nist.gov/cuu/Constants/
+
+"""
+
+# Compiled by Charles Harris, dated October 3, 2002
+# updated to 2002 values by BasSw, 2006
+# Updated to 2006 values by Vincent Davis June 2010
+# Updated to 2014 values by Joseph Booker, 2015
+# Updated to 2018 values by Jakob Jakobson, 2019
+# Updated to 2022 values by Jakob Jakobson, 2024
+
+import warnings
+import math
+
+from typing import Any
+from collections.abc import Callable
+
+__all__ = ['physical_constants', 'value', 'unit', 'precision', 'find',
+           'ConstantWarning']
+
+"""
+Source:  https://physics.nist.gov/cuu/Constants/
+
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set.
+"""
+
+#
+# Source:  https://physics.nist.gov/cuu/Constants/
+#
+
+# Quantity                                             Value                 Uncertainty          Unit
+# ---------------------------------------------------- --------------------- -------------------- -------------
+txt2002 = """\
+Wien displacement law constant                         2.897 7685e-3         0.000 0051e-3         m K
+atomic unit of 1st hyperpolarizablity                  3.206 361 51e-53      0.000 000 28e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizablity                  6.235 3808e-65        0.000 0011e-65        C^4 m^4 J^-3
+atomic unit of electric dipole moment                  8.478 353 09e-30      0.000 000 73e-30      C m
+atomic unit of electric polarizablity                  1.648 777 274e-41     0.000 000 016e-41     C^2 m^2 J^-1
+atomic unit of electric quadrupole moment              4.486 551 24e-40      0.000 000 39e-40      C m^2
+atomic unit of magn. dipole moment                     1.854 801 90e-23      0.000 000 16e-23      J T^-1
+atomic unit of magn. flux density                      2.350 517 42e5        0.000 000 20e5        T
+deuteron magn. moment                                  0.433 073 482e-26     0.000 000 038e-26     J T^-1
+deuteron magn. moment to Bohr magneton ratio           0.466 975 4567e-3     0.000 000 0050e-3
+deuteron magn. moment to nuclear magneton ratio        0.857 438 2329        0.000 000 0092
+deuteron-electron magn. moment ratio                   -4.664 345 548e-4     0.000 000 050e-4
+deuteron-proton magn. moment ratio                     0.307 012 2084        0.000 000 0045
+deuteron-neutron magn. moment ratio                    -0.448 206 52         0.000 000 11
+electron gyromagn. ratio                               1.760 859 74e11       0.000 000 15e11       s^-1 T^-1
+electron gyromagn. ratio over 2 pi                     28 024.9532           0.0024                MHz T^-1
+electron magn. moment                                  -928.476 412e-26      0.000 080e-26         J T^-1
+electron magn. moment to Bohr magneton ratio           -1.001 159 652 1859   0.000 000 000 0038
+electron magn. moment to nuclear magneton ratio        -1838.281 971 07      0.000 000 85
+electron magn. moment anomaly                          1.159 652 1859e-3     0.000 000 0038e-3
+electron to shielded proton magn. moment ratio         -658.227 5956         0.000 0071
+electron to shielded helion magn. moment ratio         864.058 255           0.000 010
+electron-deuteron magn. moment ratio                   -2143.923 493         0.000 023
+electron-muon magn. moment ratio                       206.766 9894          0.000 0054
+electron-neutron magn. moment ratio                    960.920 50            0.000 23
+electron-proton magn. moment ratio                     -658.210 6862         0.000 0066
+magn. constant                                         12.566 370 614...e-7  (exact)               N A^-2
+magn. flux quantum                                     2.067 833 72e-15      0.000 000 18e-15      Wb
+muon magn. moment                                      -4.490 447 99e-26     0.000 000 40e-26      J T^-1
+muon magn. moment to Bohr magneton ratio               -4.841 970 45e-3      0.000 000 13e-3
+muon magn. moment to nuclear magneton ratio            -8.890 596 98         0.000 000 23
+muon-proton magn. moment ratio                         -3.183 345 118        0.000 000 089
+neutron gyromagn. ratio                                1.832 471 83e8        0.000 000 46e8        s^-1 T^-1
+neutron gyromagn. ratio over 2 pi                      29.164 6950           0.000 0073            MHz T^-1
+neutron magn. moment                                   -0.966 236 45e-26     0.000 000 24e-26      J T^-1
+neutron magn. moment to Bohr magneton ratio            -1.041 875 63e-3      0.000 000 25e-3
+neutron magn. moment to nuclear magneton ratio         -1.913 042 73         0.000 000 45
+neutron to shielded proton magn. moment ratio          -0.684 996 94         0.000 000 16
+neutron-electron magn. moment ratio                    1.040 668 82e-3       0.000 000 25e-3
+neutron-proton magn. moment ratio                      -0.684 979 34         0.000 000 16
+proton gyromagn. ratio                                 2.675 222 05e8        0.000 000 23e8        s^-1 T^-1
+proton gyromagn. ratio over 2 pi                       42.577 4813           0.000 0037            MHz T^-1
+proton magn. moment                                    1.410 606 71e-26      0.000 000 12e-26      J T^-1
+proton magn. moment to Bohr magneton ratio             1.521 032 206e-3      0.000 000 015e-3
+proton magn. moment to nuclear magneton ratio          2.792 847 351         0.000 000 028
+proton magn. shielding correction                      25.689e-6             0.015e-6
+proton-neutron magn. moment ratio                      -1.459 898 05         0.000 000 34
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded helion magn. moment                           -1.074 553 024e-26    0.000 000 093e-26     J T^-1
+shielded helion magn. moment to Bohr magneton ratio    -1.158 671 474e-3     0.000 000 014e-3
+shielded helion magn. moment to nuclear magneton ratio -2.127 497 723        0.000 000 025
+shielded helion to proton magn. moment ratio           -0.761 766 562        0.000 000 012
+shielded helion to shielded proton magn. moment ratio  -0.761 786 1313       0.000 000 0033
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded proton magn. moment                           1.410 570 47e-26      0.000 000 12e-26      J T^-1
+shielded proton magn. moment to Bohr magneton ratio    1.520 993 132e-3      0.000 000 016e-3
+shielded proton magn. moment to nuclear magneton ratio 2.792 775 604         0.000 000 030
+{220} lattice spacing of silicon                       192.015 5965e-12      0.000 0070e-12        m"""
+
+
+def exact2002(exact):
+    replace = {
+        'magn. constant': 4e-7 * math.pi,
+    }
+    return replace
+
+
+txt2006 = """\
+lattice spacing of silicon                             192.015 5762 e-12     0.000 0050 e-12       m
+alpha particle-electron mass ratio                     7294.299 5365         0.000 0031
+alpha particle mass                                    6.644 656 20 e-27     0.000 000 33 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 17 e-10     0.000 000 30 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 109          0.000 093             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 51      0.000 000 000 41
+Angstrom star                                          1.000 014 98 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 028           0.000 023             MeV
+atomic mass unit-electron volt relationship            931.494 028 e6        0.000 023 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 7149 e7     0.000 000 0049 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7369 e23    0.000 000 0032 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 671 e14     0.000 000 011 e14     m^-1
+atomic mass unit-joule relationship                    1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass unit-kelvin relationship                   1.080 9527 e13        0.000 0019 e13        K
+atomic mass unit-kilogram relationship                 1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 533 e-53    0.000 000 081 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 95 e-65     0.000 000 31 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 628 e-34    0.000 000 053 e-34    J s
+atomic unit of charge                                  1.602 176 487 e-19    0.000 000 040 e-19    C
+atomic unit of charge density                          1.081 202 300 e12     0.000 000 027 e12     C m^-3
+atomic unit of current                                 6.623 617 63 e-3      0.000 000 17 e-3      A
+atomic unit of electric dipole mom.                    8.478 352 81 e-30     0.000 000 21 e-30     C m
+atomic unit of electric field                          5.142 206 32 e11      0.000 000 13 e11      V m^-1
+atomic unit of electric field gradient                 9.717 361 66 e21      0.000 000 24 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2536 e-41   0.000 000 0034 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 383 86         0.000 000 68          V
+atomic unit of electric quadrupole mom.                4.486 551 07 e-40     0.000 000 11 e-40     C m^2
+atomic unit of energy                                  4.359 743 94 e-18     0.000 000 22 e-18     J
+atomic unit of force                                   8.238 722 06 e-8      0.000 000 41 e-8      N
+atomic unit of length                                  0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 830 e-23    0.000 000 046 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 382 e5      0.000 000 059 e5      T
+atomic unit of magnetizability                         7.891 036 433 e-29    0.000 000 027 e-29    J T^-2
+atomic unit of mass                                    9.109 382 15 e-31     0.000 000 45 e-31     kg
+atomic unit of momentum                                1.992 851 565 e-24    0.000 000 099 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 505 e-17 0.000 000 000 016 e-17 s
+atomic unit of velocity                                2.187 691 2541 e6     0.000 000 0015 e6     m s^-1
+Avogadro constant                                      6.022 141 79 e23      0.000 000 30 e23      mol^-1
+Bohr magneton                                          927.400 915 e-26      0.000 023 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 7555 e-5    0.000 000 0079 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 246 04 e9      0.000 000 35 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4515           0.000 0012            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 7131            0.000 0012            K T^-1
+Bohr radius                                            0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+Boltzmann constant                                     1.380 6504 e-23       0.000 0024 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 343 e-5         0.000 015 e-5         eV K^-1
+Boltzmann constant in Hz/K                             2.083 6644 e10        0.000 0036 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 56             0.000 12              m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 2894 e-15   0.000 000 0058 e-15   m
+Compton wavelength                                     2.426 310 2175 e-12   0.000 000 0033 e-12   m
+Compton wavelength over 2 pi                           386.159 264 59 e-15   0.000 000 53 e-15     m
+conductance quantum                                    7.748 091 7004 e-5    0.000 000 0053 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 99 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9654         0.000 0016
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 465 e-26    0.000 000 011 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 20 e-27     0.000 000 17 e-27     kg
+deuteron mass energy equivalent                        3.005 062 72 e-10     0.000 000 15 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 793          0.000 047             MeV
+deuteron mass in u                                     2.013 553 212 724     0.000 000 000 078     u
+deuteron molar mass                                    2.013 553 212 724 e-3 0.000 000 000 078 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 501 08      0.000 000 000 22
+deuteron rms charge radius                             2.1402 e-15           0.0028 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 150 e11    0.000 000 044 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1093 e-4    0.000 000 0012 e-4
+electron g factor                                      -2.002 319 304 3622   0.000 000 000 0015
+electron gyromag. ratio                                1.760 859 770 e11     0.000 000 044 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.953 64         0.000 70              MHz T^-1
+electron mag. mom.                                     -928.476 377 e-26     0.000 023 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 181 11 e-3  0.000 000 000 74 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 181 11 0.000 000 000 000 74
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 92      0.000 000 80
+electron mass                                          9.109 382 15 e-31     0.000 000 45 e-31     kg
+electron mass energy equivalent                        8.187 104 38 e-14     0.000 000 41 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 910         0.000 000 013         MeV
+electron mass in u                                     5.485 799 0943 e-4    0.000 000 0023 e-4    u
+electron molar mass                                    5.485 799 0943 e-7    0.000 000 0023 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9877          0.000 0052
+electron-muon mass ratio                               4.836 331 71 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4459 e-4    0.000 000 0033 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2177 e-4    0.000 000 0024 e-4
+electron-tau mass ratio                                2.875 64 e-4          0.000 47 e-4
+electron to alpha particle mass ratio                  1.370 933 555 70 e-4  0.000 000 000 58 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron volt                                          1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 188 e-9     0.000 000 027 e-9     u
+electron volt-hartree relationship                     3.674 932 540 e-2     0.000 000 092 e-2     E_h
+electron volt-hertz relationship                       2.417 989 454 e14     0.000 000 060 e14     Hz
+electron volt-inverse meter relationship               8.065 544 65 e5       0.000 000 20 e5       m^-1
+electron volt-joule relationship                       1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-kelvin relationship                      1.160 4505 e4         0.000 0020 e4         K
+electron volt-kilogram relationship                    1.782 661 758 e-36    0.000 000 044 e-36    kg
+elementary charge                                      1.602 176 487 e-19    0.000 000 040 e-19    C
+elementary charge over h                               2.417 989 454 e14     0.000 000 060 e14     A J^-1
+Faraday constant                                       96 485.3399           0.0024                C mol^-1
+Faraday constant for conventional electric current     96 485.3401           0.0048                C_90 mol^-1
+Fermi coupling constant                                1.166 37 e-5          0.000 01 e-5          GeV^-2
+fine-structure constant                                7.297 352 5376 e-3    0.000 000 0050 e-3
+first radiation constant                               3.741 771 18 e-16     0.000 000 19 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 759 e-16    0.000 000 059 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 2986 e-8    0.000 000 0042 e-8    u
+hartree-electron volt relationship                     27.211 383 86         0.000 000 68          eV
+Hartree energy                                         4.359 743 94 e-18     0.000 000 22 e-18     J
+Hartree energy in eV                                   27.211 383 86         0.000 000 68          eV
+hartree-hertz relationship                             6.579 683 920 722 e15 0.000 000 000 044 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 705 e7  0.000 000 000 015 e7  m^-1
+hartree-joule relationship                             4.359 743 94 e-18     0.000 000 22 e-18     J
+hartree-kelvin relationship                            3.157 7465 e5         0.000 0055 e5         K
+hartree-kilogram relationship                          4.850 869 34 e-35     0.000 000 24 e-35     kg
+helion-electron mass ratio                             5495.885 2765         0.000 0052
+helion mass                                            5.006 411 92 e-27     0.000 000 25 e-27     kg
+helion mass energy equivalent                          4.499 538 64 e-10     0.000 000 22 e-10     J
+helion mass energy equivalent in MeV                   2808.391 383          0.000 070             MeV
+helion mass in u                                       3.014 932 2473        0.000 000 0026        u
+helion molar mass                                      3.014 932 2473 e-3    0.000 000 0026 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6713        0.000 000 0026
+hertz-atomic mass unit relationship                    4.439 821 6294 e-24   0.000 000 0064 e-24   u
+hertz-electron volt relationship                       4.135 667 33 e-15     0.000 000 10 e-15     eV
+hertz-hartree relationship                             1.519 829 846 006 e-16 0.000 000 000010e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 068 96 e-34     0.000 000 33 e-34     J
+hertz-kelvin relationship                              4.799 2374 e-11       0.000 0084 e-11       K
+hertz-kilogram relationship                            7.372 496 00 e-51     0.000 000 37 e-51     kg
+inverse fine-structure constant                        137.035 999 679       0.000 000 094
+inverse meter-atomic mass unit relationship            1.331 025 0394 e-15   0.000 000 0019 e-15   u
+inverse meter-electron volt relationship               1.239 841 875 e-6     0.000 000 031 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 760 e-8 0.000 000 000 030 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 501 e-25    0.000 000 099 e-25    J
+inverse meter-kelvin relationship                      1.438 7752 e-2        0.000 0025 e-2        K
+inverse meter-kilogram relationship                    2.210 218 70 e-42     0.000 000 11 e-42     kg
+inverse of conductance quantum                         12 906.403 7787       0.000 0088            ohm
+Josephson constant                                     483 597.891 e9        0.012 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 536 41 e9       0.000 000 33 e9       u
+joule-electron volt relationship                       6.241 509 65 e18      0.000 000 16 e18      eV
+joule-hartree relationship                             2.293 712 69 e17      0.000 000 11 e17      E_h
+joule-hertz relationship                               1.509 190 450 e33     0.000 000 075 e33     Hz
+joule-inverse meter relationship                       5.034 117 47 e24      0.000 000 25 e24      m^-1
+joule-kelvin relationship                              7.242 963 e22         0.000 013 e22         K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 098 e-14        0.000 016 e-14        u
+kelvin-electron volt relationship                      8.617 343 e-5         0.000 015 e-5         eV
+kelvin-hartree relationship                            3.166 8153 e-6        0.000 0055 e-6        E_h
+kelvin-hertz relationship                              2.083 6644 e10        0.000 0036 e10        Hz
+kelvin-inverse meter relationship                      69.503 56             0.000 12              m^-1
+kelvin-joule relationship                              1.380 6504 e-23       0.000 0024 e-23       J
+kelvin-kilogram relationship                           1.536 1807 e-40       0.000 0027 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 79 e26      0.000 000 30 e26      u
+kilogram-electron volt relationship                    5.609 589 12 e35      0.000 000 14 e35      eV
+kilogram-hartree relationship                          2.061 486 16 e34      0.000 000 10 e34      E_h
+kilogram-hertz relationship                            1.356 392 733 e50     0.000 000 068 e50     Hz
+kilogram-inverse meter relationship                    4.524 439 15 e41      0.000 000 23 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 651 e39         0.000 011 e39         K
+lattice parameter of silicon                           543.102 064 e-12      0.000 014 e-12        m
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7774 e25        0.000 0047 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 667 e-15    0.000 000 052 e-15    Wb
+molar gas constant                                     8.314 472             0.000 015             J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 6821 e-10   0.000 000 0057 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 564 72      0.000 000 000 17      J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 981 e-3        0.000 040 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 996 e-3        0.000 039 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 8349 e-6       0.000 0011 e-6        m^3 mol^-1
+Mo x unit                                              1.002 099 55 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 04 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 295 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2823          0.000 0052
+muon g factor                                          -2.002 331 8414       0.000 000 0012
+muon mag. mom.                                         -4.490 447 86 e-26    0.000 000 16 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 69 e-3      0.000 000 60 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 49 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 23
+muon mass                                              1.883 531 30 e-28     0.000 000 11 e-28     kg
+muon mass energy equivalent                            1.692 833 510 e-11    0.000 000 095 e-11    J
+muon mass energy equivalent in MeV                     105.658 3668          0.000 0038            MeV
+muon mass in u                                         0.113 428 9256        0.000 000 0029        u
+muon molar mass                                        0.113 428 9256 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0029
+muon-proton mag. mom. ratio                            -3.183 345 137        0.000 000 085
+muon-proton mass ratio                                 0.112 609 5261        0.000 000 0029
+muon-tau mass ratio                                    5.945 92 e-2          0.000 97 e-2
+natural unit of action                                 1.054 571 628 e-34    0.000 000 053 e-34    J s
+natural unit of action in eV s                         6.582 118 99 e-16     0.000 000 16 e-16     eV s
+natural unit of energy                                 8.187 104 38 e-14     0.000 000 41 e-14     J
+natural unit of energy in MeV                          0.510 998 910         0.000 000 013         MeV
+natural unit of length                                 386.159 264 59 e-15   0.000 000 53 e-15     m
+natural unit of mass                                   9.109 382 15 e-31     0.000 000 45 e-31     kg
+natural unit of momentum                               2.730 924 06 e-22     0.000 000 14 e-22     kg m s^-1
+natural unit of momentum in MeV/c                      0.510 998 910         0.000 000 013         MeV/c
+natural unit of time                                   1.288 088 6570 e-21   0.000 000 0018 e-21   s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 8951 e-15   0.000 000 0020 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 413 82 e-15 0.000 000 000 31 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 85 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6954           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 41 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 211 e-27    0.000 000 084 e-27    kg
+neutron mass energy equivalent                         1.505 349 505 e-10    0.000 000 075 e-10    J
+neutron mass energy equivalent in MeV                  939.565 346           0.000 023             MeV
+neutron mass in u                                      1.008 664 915 97      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 915 97 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 09          0.000 000 23
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass ratio                              1.001 378 419 18      0.000 000 000 46
+neutron-tau mass ratio                                 0.528 740             0.000 086
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 28 e-11         0.000 67 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 81 e-39         0.000 67 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 24 e-27     0.000 000 13 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2326 e-8    0.000 000 0045 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 616 e-2     0.000 000 064 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2637 e-4        0.000 0064 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 84          0.000 000 19          MHz T^-1
+Planck constant                                        6.626 068 96 e-34     0.000 000 33 e-34     J s
+Planck constant in eV s                                4.135 667 33 e-15     0.000 000 10 e-15     eV s
+Planck constant over 2 pi                              1.054 571 628 e-34    0.000 000 053 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 118 99 e-16     0.000 000 16 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9631          0.000 0049            MeV fm
+Planck length                                          1.616 252 e-35        0.000 081 e-35        m
+Planck mass                                            2.176 44 e-8          0.000 11 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 892 e19         0.000 061 e19         GeV
+Planck temperature                                     1.416 785 e32         0.000 071 e32         K
+Planck time                                            5.391 24 e-44         0.000 27 e-44         s
+proton charge to mass quotient                         9.578 833 92 e7       0.000 000 24 e7       C kg^-1
+proton Compton wavelength                              1.321 409 8446 e-15   0.000 000 0019 e-15   m
+proton Compton wavelength over 2 pi                    0.210 308 908 61 e-15 0.000 000 000 30 e-15 m
+proton-electron mass ratio                             1836.152 672 47       0.000 000 80
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 099 e8      0.000 000 070 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4821           0.000 0011            MHz T^-1
+proton mag. mom.                                       1.410 606 662 e-26    0.000 000 037 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 209 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 637 e-27    0.000 000 083 e-27    kg
+proton mass energy equivalent                          1.503 277 359 e-10    0.000 000 075 e-10    J
+proton mass energy equivalent in MeV                   938.272 013           0.000 023             MeV
+proton mass in u                                       1.007 276 466 77      0.000 000 000 10      u
+proton molar mass                                      1.007 276 466 77 e-3  0.000 000 000 10 e-3  kg mol^-1
+proton-muon mass ratio                                 8.880 243 39          0.000 000 23
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 24      0.000 000 000 46
+proton rms charge radius                               0.8768 e-15           0.0069 e-15           m
+proton-tau mass ratio                                  0.528 012             0.000 086
+quantum of circulation                                 3.636 947 5199 e-4    0.000 000 0050 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 040 e-4     0.000 000 010 e-4     m^2 s^-1
+Rydberg constant                                       10 973 731.568 527    0.000 073             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 361 e15 0.000 000 000 022 e15 Hz
+Rydberg constant times hc in eV                        13.605 691 93         0.000 000 34          eV
+Rydberg constant times hc in J                         2.179 871 97 e-18     0.000 000 11 e-18     J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7047           0.000 0044
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8677           0.000 0044
+second radiation constant                              1.438 7752 e-2        0.000 0025 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 730 e8      0.000 000 056 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 101 98         0.000 000 90          MHz T^-1
+shielded helion mag. mom.                              -1.074 552 982 e-26   0.000 000 030 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 362 e8      0.000 000 073 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3881           0.000 0012            MHz T^-1
+shielded proton mag. mom.                              1.410 570 419 e-26    0.000 000 038 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 400 e-8         0.000 040 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 72 e-15         0.000 11 e-15         m
+tau Compton wavelength over 2 pi                       0.111 046 e-15        0.000 018 e-15        m
+tau-electron mass ratio                                3477.48               0.57
+tau mass                                               3.167 77 e-27         0.000 52 e-27         kg
+tau mass energy equivalent                             2.847 05 e-10         0.000 46 e-10         J
+tau mass energy equivalent in MeV                      1776.99               0.29                  MeV
+tau mass in u                                          1.907 68              0.000 31              u
+tau molar mass                                         1.907 68 e-3          0.000 31 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8183               0.0027
+tau-neutron mass ratio                                 1.891 29              0.000 31
+tau-proton mass ratio                                  1.893 90              0.000 31
+Thomson cross section                                  0.665 245 8558 e-28   0.000 000 0027 e-28   m^2
+triton-electron mag. mom. ratio                        -1.620 514 423 e-3    0.000 000 021 e-3
+triton-electron mass ratio                             5496.921 5269         0.000 0051
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 361 e-26    0.000 000 042 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 355 88 e-27     0.000 000 25 e-27     kg
+triton mass energy equivalent                          4.500 387 03 e-10     0.000 000 22 e-10     J
+triton mass energy equivalent in MeV                   2808.920 906          0.000 070             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-neutron mag. mom. ratio                         -1.557 185 53         0.000 000 37
+triton-proton mag. mom. ratio                          1.066 639 908         0.000 000 010
+triton-proton mass ratio                               2.993 717 0309        0.000 000 0025
+unified atomic mass unit                               1.660 538 782 e-27    0.000 000 083 e-27    kg
+von Klitzing constant                                  25 812.807 557        0.000 018             ohm
+weak mixing angle                                      0.222 55              0.000 56
+Wien frequency displacement law constant               5.878 933 e10         0.000 010 e10         Hz K^-1
+Wien wavelength displacement law constant              2.897 7685 e-3        0.000 0051 e-3        m K"""
+
+
+def exact2006(exact):
+    mu0 = 4e-7 * math.pi
+    c = exact['speed of light in vacuum']
+    epsilon0 = 1 / (mu0 * c**2)
+    replace = {
+        'mag. constant': mu0,
+        'electric constant': epsilon0,
+        'atomic unit of permittivity': 4*math.pi*epsilon0,
+        'characteristic impedance of vacuum': math.sqrt(mu0 / epsilon0),
+        'hertz-inverse meter relationship': 1/c,
+        'joule-kilogram relationship': 1/c**2,
+        'kilogram-joule relationship': c**2,
+    }
+    return replace
+
+
+txt2010 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 5361         0.000 0029
+alpha particle mass                                    6.644 656 75 e-27     0.000 000 29 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 67 e-10     0.000 000 26 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 240          0.000 082             MeV
+alpha particle mass in u                               4.001 506 179 125     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 125 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 33      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 061           0.000 021             MeV
+atomic mass unit-electron volt relationship            931.494 061 e6        0.000 021 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 6845 e7     0.000 000 0024 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7168 e23    0.000 000 0016 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6042 e14    0.000 000 0053 e14    m^-1
+atomic mass unit-joule relationship                    1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 08 e13      0.000 000 98 e13      K
+atomic mass unit-kilogram relationship                 1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 449 e-53    0.000 000 071 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 54 e-65     0.000 000 28 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 726 e-34    0.000 000 047 e-34    J s
+atomic unit of charge                                  1.602 176 565 e-19    0.000 000 035 e-19    C
+atomic unit of charge density                          1.081 202 338 e12     0.000 000 024 e12     C m^-3
+atomic unit of current                                 6.623 617 95 e-3      0.000 000 15 e-3      A
+atomic unit of electric dipole mom.                    8.478 353 26 e-30     0.000 000 19 e-30     C m
+atomic unit of electric field                          5.142 206 52 e11      0.000 000 11 e11      V m^-1
+atomic unit of electric field gradient                 9.717 362 00 e21      0.000 000 21 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2754 e-41   0.000 000 0016 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 385 05         0.000 000 60          V
+atomic unit of electric quadrupole mom.                4.486 551 331 e-40    0.000 000 099 e-40    C m^2
+atomic unit of energy                                  4.359 744 34 e-18     0.000 000 19 e-18     J
+atomic unit of force                                   8.238 722 78 e-8      0.000 000 36 e-8      N
+atomic unit of length                                  0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 936 e-23    0.000 000 041 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 464 e5      0.000 000 052 e5      T
+atomic unit of magnetizability                         7.891 036 607 e-29    0.000 000 013 e-29    J T^-2
+atomic unit of mass                                    9.109 382 91 e-31     0.000 000 40 e-31     kg
+atomic unit of mom.um                                  1.992 851 740 e-24    0.000 000 088 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 502e-17 0.000 000 000 012e-17 s
+atomic unit of velocity                                2.187 691 263 79 e6   0.000 000 000 71 e6   m s^-1
+Avogadro constant                                      6.022 141 29 e23      0.000 000 27 e23      mol^-1
+Bohr magneton                                          927.400 968 e-26      0.000 020 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 8066 e-5    0.000 000 0038 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 55 e9      0.000 000 31 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4498           0.000 0010            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 713 88          0.000 000 61          K T^-1
+Bohr radius                                            0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+Boltzmann constant                                     1.380 6488 e-23       0.000 0013 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 3324 e-5        0.000 0078 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6618 e10        0.000 0019 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 476            0.000 063             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3267 e-15   0.000 000 0027 e-15   m
+Compton wavelength                                     2.426 310 2389 e-12   0.000 000 0016 e-12   m
+Compton wavelength over 2 pi                           386.159 268 00 e-15   0.000 000 25 e-15     m
+conductance quantum                                    7.748 091 7346 e-5    0.000 000 0025 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9652         0.000 0015
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 489 e-26    0.000 000 010 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 48 e-27     0.000 000 15 e-27     kg
+deuteron mass energy equivalent                        3.005 062 97 e-10     0.000 000 13 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 859          0.000 041             MeV
+deuteron mass in u                                     2.013 553 212 712     0.000 000 000 077     u
+deuteron molar mass                                    2.013 553 212 712 e-3 0.000 000 000 077 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 500 97      0.000 000 000 18
+deuteron rms charge radius                             2.1424 e-15           0.0021 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 088 e11    0.000 000 039 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1095 e-4    0.000 000 0011 e-4
+electron g factor                                      -2.002 319 304 361 53 0.000 000 000 000 53
+electron gyromag. ratio                                1.760 859 708 e11     0.000 000 039 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.952 66         0.000 62              MHz T^-1
+electron-helion mass ratio                             1.819 543 0761 e-4    0.000 000 0017 e-4
+electron mag. mom.                                     -928.476 430 e-26     0.000 021 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 180 76 e-3  0.000 000 000 27 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 76 0.000 000 000 000 27
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 90      0.000 000 75
+electron mass                                          9.109 382 91 e-31     0.000 000 40 e-31     kg
+electron mass energy equivalent                        8.187 105 06 e-14     0.000 000 36 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 928         0.000 000 011         MeV
+electron mass in u                                     5.485 799 0946 e-4    0.000 000 0022 e-4    u
+electron molar mass                                    5.485 799 0946 e-7    0.000 000 0022 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9896          0.000 0052
+electron-muon mass ratio                               4.836 331 66 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4461 e-4    0.000 000 0032 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2178 e-4    0.000 000 0022 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 555 78 e-4  0.000 000 000 55 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 0653 e-4    0.000 000 0017 e-4
+electron volt                                          1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 150 e-9     0.000 000 024 e-9     u
+electron volt-hartree relationship                     3.674 932 379 e-2     0.000 000 081 e-2     E_h
+electron volt-hertz relationship                       2.417 989 348 e14     0.000 000 053 e14     Hz
+electron volt-inverse meter relationship               8.065 544 29 e5       0.000 000 18 e5       m^-1
+electron volt-joule relationship                       1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-kelvin relationship                      1.160 4519 e4         0.000 0011 e4         K
+electron volt-kilogram relationship                    1.782 661 845 e-36    0.000 000 039 e-36    kg
+elementary charge                                      1.602 176 565 e-19    0.000 000 035 e-19    C
+elementary charge over h                               2.417 989 348 e14     0.000 000 053 e14     A J^-1
+Faraday constant                                       96 485.3365           0.0021                C mol^-1
+Faraday constant for conventional electric current     96 485.3321           0.0043                C_90 mol^-1
+Fermi coupling constant                                1.166 364 e-5         0.000 005 e-5         GeV^-2
+fine-structure constant                                7.297 352 5698 e-3    0.000 000 0024 e-3
+first radiation constant                               3.741 771 53 e-16     0.000 000 17 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 869 e-16    0.000 000 053 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3246 e-8    0.000 000 0021 e-8    u
+hartree-electron volt relationship                     27.211 385 05         0.000 000 60          eV
+Hartree energy                                         4.359 744 34 e-18     0.000 000 19 e-18     J
+Hartree energy in eV                                   27.211 385 05         0.000 000 60          eV
+hartree-hertz relationship                             6.579 683 920 729 e15 0.000 000 000 033 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 708 e7  0.000 000 000 011 e7  m^-1
+hartree-joule relationship                             4.359 744 34 e-18     0.000 000 19 e-18     J
+hartree-kelvin relationship                            3.157 7504 e5         0.000 0029 e5         K
+hartree-kilogram relationship                          4.850 869 79 e-35     0.000 000 21 e-35     kg
+helion-electron mass ratio                             5495.885 2754         0.000 0050
+helion g factor                                        -4.255 250 613        0.000 000 050
+helion mag. mom.                                       -1.074 617 486 e-26   0.000 000 027 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 306        0.000 000 025
+helion mass                                            5.006 412 34 e-27     0.000 000 22 e-27     kg
+helion mass energy equivalent                          4.499 539 02 e-10     0.000 000 20 e-10     J
+helion mass energy equivalent in MeV                   2808.391 482          0.000 062             MeV
+helion mass in u                                       3.014 932 2468        0.000 000 0025        u
+helion molar mass                                      3.014 932 2468 e-3    0.000 000 0025 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6707        0.000 000 0025
+hertz-atomic mass unit relationship                    4.439 821 6689 e-24   0.000 000 0031 e-24   u
+hertz-electron volt relationship                       4.135 667 516 e-15    0.000 000 091 e-15    eV
+hertz-hartree relationship                             1.519 829 8460045e-16 0.000 000 0000076e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 069 57 e-34     0.000 000 29 e-34     J
+hertz-kelvin relationship                              4.799 2434 e-11       0.000 0044 e-11       K
+hertz-kilogram relationship                            7.372 496 68 e-51     0.000 000 33 e-51     kg
+inverse fine-structure constant                        137.035 999 074       0.000 000 044
+inverse meter-atomic mass unit relationship            1.331 025 051 20 e-15 0.000 000 000 94 e-15 u
+inverse meter-electron volt relationship               1.239 841 930 e-6     0.000 000 027 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 755 e-8 0.000 000 000 023 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 684 e-25    0.000 000 088 e-25    J
+inverse meter-kelvin relationship                      1.438 7770 e-2        0.000 0013 e-2        K
+inverse meter-kilogram relationship                    2.210 218 902 e-42    0.000 000 098 e-42    kg
+inverse of conductance quantum                         12 906.403 7217       0.000 0042            ohm
+Josephson constant                                     483 597.870 e9        0.011 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 85 e9       0.000 000 30 e9       u
+joule-electron volt relationship                       6.241 509 34 e18      0.000 000 14 e18      eV
+joule-hartree relationship                             2.293 712 48 e17      0.000 000 10 e17      E_h
+joule-hertz relationship                               1.509 190 311 e33     0.000 000 067 e33     Hz
+joule-inverse meter relationship                       5.034 117 01 e24      0.000 000 22 e24      m^-1
+joule-kelvin relationship                              7.242 9716 e22        0.000 0066 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0868 e-14       0.000 0084 e-14       u
+kelvin-electron volt relationship                      8.617 3324 e-5        0.000 0078 e-5        eV
+kelvin-hartree relationship                            3.166 8114 e-6        0.000 0029 e-6        E_h
+kelvin-hertz relationship                              2.083 6618 e10        0.000 0019 e10        Hz
+kelvin-inverse meter relationship                      69.503 476            0.000 063             m^-1
+kelvin-joule relationship                              1.380 6488 e-23       0.000 0013 e-23       J
+kelvin-kilogram relationship                           1.536 1790 e-40       0.000 0014 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 29 e26      0.000 000 27 e26      u
+kilogram-electron volt relationship                    5.609 588 85 e35      0.000 000 12 e35      eV
+kilogram-hartree relationship                          2.061 485 968 e34     0.000 000 091 e34     E_h
+kilogram-hertz relationship                            1.356 392 608 e50     0.000 000 060 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 73 e41      0.000 000 20 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6582 e39        0.000 0059 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6462 e25        0.000 0024 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7805 e25        0.000 0024 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 758 e-15    0.000 000 046 e-15    Wb
+molar gas constant                                     8.314 4621            0.000 0075            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7176 e-10   0.000 000 0028 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 779     0.000 000 000 084     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 953 e-3        0.000 021 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 968 e-3        0.000 020 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 833 01 e-6     0.000 000 80 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 03 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 294 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2843          0.000 0052
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 07 e-26    0.000 000 15 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 91 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 44 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 596 97         0.000 000 22
+muon mass                                              1.883 531 475 e-28    0.000 000 096 e-28    kg
+muon mass energy equivalent                            1.692 833 667 e-11    0.000 000 086 e-11    J
+muon mass energy equivalent in MeV                     105.658 3715          0.000 0035            MeV
+muon mass in u                                         0.113 428 9267        0.000 000 0029        u
+muon molar mass                                        0.113 428 9267 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5177        0.000 000 0028
+muon-proton mag. mom. ratio                            -3.183 345 107        0.000 000 084
+muon-proton mass ratio                                 0.112 609 5272        0.000 000 0028
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 726 e-34    0.000 000 047 e-34    J s
+natural unit of action in eV s                         6.582 119 28 e-16     0.000 000 15 e-16     eV s
+natural unit of energy                                 8.187 105 06 e-14     0.000 000 36 e-14     J
+natural unit of energy in MeV                          0.510 998 928         0.000 000 011         MeV
+natural unit of length                                 386.159 268 00 e-15   0.000 000 25 e-15     m
+natural unit of mass                                   9.109 382 91 e-31     0.000 000 40 e-31     kg
+natural unit of mom.um                                 2.730 924 29 e-22     0.000 000 12 e-22     kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 928         0.000 000 011         MeV/c
+natural unit of time                                   1.288 088 668 33 e-21 0.000 000 000 83 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 9068 e-15   0.000 000 0011 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 415 68 e-15 0.000 000 000 17 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 79 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6943           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 47 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 72         0.000 000 45
+neutron mass                                           1.674 927 351 e-27    0.000 000 074 e-27    kg
+neutron mass energy equivalent                         1.505 349 631 e-10    0.000 000 066 e-10    J
+neutron mass energy equivalent in MeV                  939.565 379           0.000 021             MeV
+neutron mass in u                                      1.008 664 916 00      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 916 00 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 00          0.000 000 22
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 92 e-30     0.000 000 76 e-30
+neutron-proton mass difference energy equivalent       2.072 146 50 e-13     0.000 000 68 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 17          0.000 000 42
+neutron-proton mass difference in u                    0.001 388 449 19      0.000 000 000 45
+neutron-proton mass ratio                              1.001 378 419 17      0.000 000 000 45
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.673 84 e-11         0.000 80 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 37 e-39         0.000 80 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 53 e-27     0.000 000 11 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2605 e-8    0.000 000 0022 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 527 e-2     0.000 000 056 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2682 e-4        0.000 0033 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 57          0.000 000 17          MHz T^-1
+Planck constant                                        6.626 069 57 e-34     0.000 000 29 e-34     J s
+Planck constant in eV s                                4.135 667 516 e-15    0.000 000 091 e-15    eV s
+Planck constant over 2 pi                              1.054 571 726 e-34    0.000 000 047 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 28 e-16     0.000 000 15 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9718          0.000 0044            MeV fm
+Planck length                                          1.616 199 e-35        0.000 097 e-35        m
+Planck mass                                            2.176 51 e-8          0.000 13 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 932 e19         0.000 073 e19         GeV
+Planck temperature                                     1.416 833 e32         0.000 085 e32         K
+Planck time                                            5.391 06 e-44         0.000 32 e-44         s
+proton charge to mass quotient                         9.578 833 58 e7       0.000 000 21 e7       C kg^-1
+proton Compton wavelength                              1.321 409 856 23 e-15 0.000 000 000 94 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308 910 47 e-15 0.000 000 000 15 e-15 m
+proton-electron mass ratio                             1836.152 672 45       0.000 000 75
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 005 e8      0.000 000 063 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4806           0.000 0010            MHz T^-1
+proton mag. mom.                                       1.410 606 743 e-26    0.000 000 033 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 210 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 777 e-27    0.000 000 074 e-27    kg
+proton mass energy equivalent                          1.503 277 484 e-10    0.000 000 066 e-10    J
+proton mass energy equivalent in MeV                   938.272 046           0.000 021             MeV
+proton mass in u                                       1.007 276 466 812     0.000 000 000 090     u
+proton molar mass                                      1.007 276 466 812 e-3 0.000 000 000 090 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 31          0.000 000 22
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 26      0.000 000 000 45
+proton rms charge radius                               0.8775 e-15           0.0051 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5520 e-4    0.000 000 0024 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 1040 e-4    0.000 000 0047 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 539    0.000 055             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 364 e15 0.000 000 000 017 e15 Hz
+Rydberg constant times hc in eV                        13.605 692 53         0.000 000 30          eV
+Rydberg constant times hc in J                         2.179 872 171 e-18    0.000 000 096 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7078           0.000 0023
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8708           0.000 0023
+second radiation constant                              1.438 7770 e-2        0.000 0013 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 659 e8      0.000 000 051 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 100 84         0.000 000 81          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 044 e-26   0.000 000 027 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 268 e8      0.000 000 066 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3866           0.000 0010            MHz T^-1
+shielded proton mag. mom.                              1.410 570 499 e-26    0.000 000 035 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 373 e-8         0.000 021 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 8734 e-28   0.000 000 0013 e-28   m^2
+triton-electron mass ratio                             5496.921 5267         0.000 0050
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 447 e-26    0.000 000 038 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 356 30 e-27     0.000 000 22 e-27     kg
+triton mass energy equivalent                          4.500 387 41 e-10     0.000 000 20 e-10     J
+triton mass energy equivalent in MeV                   2808.921 005          0.000 062             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-proton mass ratio                               2.993 717 0308        0.000 000 0025
+unified atomic mass unit                               1.660 538 921 e-27    0.000 000 073 e-27    kg
+von Klitzing constant                                  25 812.807 4434       0.000 0084            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9254 e10        0.000 0053 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7721 e-3        0.000 0026 e-3        m K"""
+
+
+exact2010 = exact2006
+
+
+txt2014 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 541 36       0.000 000 24
+alpha particle mass                                    6.644 657 230 e-27    0.000 000 082 e-27    kg
+alpha particle mass energy equivalent                  5.971 920 097 e-10    0.000 000 073 e-10    J
+alpha particle mass energy equivalent in MeV           3727.379 378          0.000 023             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 063     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 063 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 07      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic mass constant energy equivalent                 1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 0954          0.000 0057            MeV
+atomic mass unit-electron volt relationship            931.494 0954 e6       0.000 0057 e6         eV
+atomic mass unit-hartree relationship                  3.423 177 6902 e7     0.000 000 0016 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7206 e23    0.000 000 0010 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6166 e14    0.000 000 0034 e14    m^-1
+atomic mass unit-joule relationship                    1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 38 e13      0.000 000 62 e13      K
+atomic mass unit-kilogram relationship                 1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 329 e-53    0.000 000 020 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 085 e-65    0.000 000 077 e-65    C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 800 e-34    0.000 000 013 e-34    J s
+atomic unit of charge                                  1.602 176 6208 e-19   0.000 000 0098 e-19   C
+atomic unit of charge density                          1.081 202 3770 e12    0.000 000 0067 e12    C m^-3
+atomic unit of current                                 6.623 618 183 e-3     0.000 000 041 e-3     A
+atomic unit of electric dipole mom.                    8.478 353 552 e-30    0.000 000 052 e-30    C m
+atomic unit of electric field                          5.142 206 707 e11     0.000 000 032 e11     V m^-1
+atomic unit of electric field gradient                 9.717 362 356 e21     0.000 000 060 e21     V m^-2
+atomic unit of electric polarizability                 1.648 777 2731 e-41   0.000 000 0011 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 386 02         0.000 000 17          V
+atomic unit of electric quadrupole mom.                4.486 551 484 e-40    0.000 000 028 e-40    C m^2
+atomic unit of energy                                  4.359 744 650 e-18    0.000 000 054 e-18    J
+atomic unit of force                                   8.238 723 36 e-8      0.000 000 10 e-8      N
+atomic unit of length                                  0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 999 e-23    0.000 000 011 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 550 e5      0.000 000 014 e5      T
+atomic unit of magnetizability                         7.891 036 5886 e-29   0.000 000 0090 e-29   J T^-2
+atomic unit of mass                                    9.109 383 56 e-31     0.000 000 11 e-31     kg
+atomic unit of mom.um                                  1.992 851 882 e-24    0.000 000 024 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326509e-17  0.000 000 000014e-17  s
+atomic unit of velocity                                2.187 691 262 77 e6   0.000 000 000 50 e6   m s^-1
+Avogadro constant                                      6.022 140 857 e23     0.000 000 074 e23     mol^-1
+Bohr magneton                                          927.400 9994 e-26     0.000 0057 e-26       J T^-1
+Bohr magneton in eV/T                                  5.788 381 8012 e-5    0.000 000 0026 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 042 e9     0.000 000 086 e9      Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 448 14         0.000 000 29          m^-1 T^-1
+Bohr magneton in K/T                                   0.671 714 05          0.000 000 39          K T^-1
+Bohr radius                                            0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+Boltzmann constant                                     1.380 648 52 e-23     0.000 000 79 e-23     J K^-1
+Boltzmann constant in eV/K                             8.617 3303 e-5        0.000 0050 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6612 e10        0.000 0012 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 457            0.000 040             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3227 e-15   0.000 000 0019 e-15   m
+Compton wavelength                                     2.426 310 2367 e-12   0.000 000 0011 e-12   m
+Compton wavelength over 2 pi                           386.159 267 64 e-15   0.000 000 18 e-15     m
+conductance quantum                                    7.748 091 7310 e-5    0.000 000 0018 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 535 e-4    0.000 000 026 e-4
+deuteron-electron mass ratio                           3670.482 967 85       0.000 000 13
+deuteron g factor                                      0.857 438 2311        0.000 000 0048
+deuteron mag. mom.                                     0.433 073 5040 e-26   0.000 000 0036 e-26   J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4554 e-3    0.000 000 0026 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2311        0.000 000 0048
+deuteron mass                                          3.343 583 719 e-27    0.000 000 041 e-27    kg
+deuteron mass energy equivalent                        3.005 063 183 e-10    0.000 000 037 e-10    J
+deuteron mass energy equivalent in MeV                 1875.612 928          0.000 012             MeV
+deuteron mass in u                                     2.013 553 212 745     0.000 000 000 040     u
+deuteron molar mass                                    2.013 553 212 745 e-3 0.000 000 000 040 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2077        0.000 000 0015
+deuteron-proton mass ratio                             1.999 007 500 87      0.000 000 000 19
+deuteron rms charge radius                             2.1413 e-15           0.0025 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 024 e11    0.000 000 011 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 499         0.000 012
+electron-deuteron mass ratio                           2.724 437 107 484 e-4 0.000 000 000 096 e-4
+electron g factor                                      -2.002 319 304 361 82 0.000 000 000 000 52
+electron gyromag. ratio                                1.760 859 644 e11     0.000 000 011 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.951 64         0.000 17              MHz T^-1
+electron-helion mass ratio                             1.819 543 074 854 e-4 0.000 000 000 088 e-4
+electron mag. mom.                                     -928.476 4620 e-26    0.000 0057 e-26       J T^-1
+electron mag. mom. anomaly                             1.159 652 180 91 e-3  0.000 000 000 26 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 91 0.000 000 000 000 26
+electron mag. mom. to nuclear magneton ratio           -1838.281 972 34      0.000 000 17
+electron mass                                          9.109 383 56 e-31     0.000 000 11 e-31     kg
+electron mass energy equivalent                        8.187 105 65 e-14     0.000 000 10 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 9461        0.000 000 0031        MeV
+electron mass in u                                     5.485 799 090 70 e-4  0.000 000 000 16 e-4  u
+electron molar mass                                    5.485 799 090 70 e-7  0.000 000 000 16 e-7  kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9880          0.000 0046
+electron-muon mass ratio                               4.836 331 70 e-3      0.000 000 11 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4428 e-4    0.000 000 0027 e-4
+electron-proton mag. mom. ratio                        -658.210 6866         0.000 0020
+electron-proton mass ratio                             5.446 170 213 52 e-4  0.000 000 000 52 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 554 798 e-4 0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 062 203 e-4 0.000 000 000 084 e-4
+electron volt                                          1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-atomic mass unit relationship            1.073 544 1105 e-9    0.000 000 0066 e-9    u
+electron volt-hartree relationship                     3.674 932 248 e-2     0.000 000 023 e-2     E_h
+electron volt-hertz relationship                       2.417 989 262 e14     0.000 000 015 e14     Hz
+electron volt-inverse meter relationship               8.065 544 005 e5      0.000 000 050 e5      m^-1
+electron volt-joule relationship                       1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-kelvin relationship                      1.160 452 21 e4       0.000 000 67 e4       K
+electron volt-kilogram relationship                    1.782 661 907 e-36    0.000 000 011 e-36    kg
+elementary charge                                      1.602 176 6208 e-19   0.000 000 0098 e-19   C
+elementary charge over h                               2.417 989 262 e14     0.000 000 015 e14     A J^-1
+Faraday constant                                       96 485.332 89         0.000 59              C mol^-1
+Faraday constant for conventional electric current     96 485.3251           0.0012                C_90 mol^-1
+Fermi coupling constant                                1.166 3787 e-5        0.000 0006 e-5        GeV^-2
+fine-structure constant                                7.297 352 5664 e-3    0.000 000 0017 e-3
+first radiation constant                               3.741 771 790 e-16    0.000 000 046 e-16    W m^2
+first radiation constant for spectral radiance         1.191 042 953 e-16    0.000 000 015 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3197 e-8    0.000 000 0013 e-8    u
+hartree-electron volt relationship                     27.211 386 02         0.000 000 17          eV
+Hartree energy                                         4.359 744 650 e-18    0.000 000 054 e-18    J
+Hartree energy in eV                                   27.211 386 02         0.000 000 17          eV
+hartree-hertz relationship                             6.579 683 920 711 e15 0.000 000 000 039 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 702 e7  0.000 000 000 013 e7  m^-1
+hartree-joule relationship                             4.359 744 650 e-18    0.000 000 054 e-18    J
+hartree-kelvin relationship                            3.157 7513 e5         0.000 0018 e5         K
+hartree-kilogram relationship                          4.850 870 129 e-35    0.000 000 060 e-35    kg
+helion-electron mass ratio                             5495.885 279 22       0.000 000 27
+helion g factor                                        -4.255 250 616        0.000 000 050
+helion mag. mom.                                       -1.074 617 522 e-26   0.000 000 014 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 308        0.000 000 025
+helion mass                                            5.006 412 700 e-27    0.000 000 062 e-27    kg
+helion mass energy equivalent                          4.499 539 341 e-10    0.000 000 055 e-10    J
+helion mass energy equivalent in MeV                   2808.391 586          0.000 017             MeV
+helion mass in u                                       3.014 932 246 73      0.000 000 000 12      u
+helion molar mass                                      3.014 932 246 73 e-3  0.000 000 000 12 e-3  kg mol^-1
+helion-proton mass ratio                               2.993 152 670 46      0.000 000 000 29
+hertz-atomic mass unit relationship                    4.439 821 6616 e-24   0.000 000 0020 e-24   u
+hertz-electron volt relationship                       4.135 667 662 e-15    0.000 000 025 e-15    eV
+hertz-hartree relationship                             1.5198298460088 e-16  0.0000000000090e-16   E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 070 040 e-34    0.000 000 081 e-34    J
+hertz-kelvin relationship                              4.799 2447 e-11       0.000 0028 e-11       K
+hertz-kilogram relationship                            7.372 497 201 e-51    0.000 000 091 e-51    kg
+inverse fine-structure constant                        137.035 999 139       0.000 000 031
+inverse meter-atomic mass unit relationship            1.331 025 049 00 e-15 0.000 000 000 61 e-15 u
+inverse meter-electron volt relationship               1.239 841 9739 e-6    0.000 000 0076 e-6    eV
+inverse meter-hartree relationship                     4.556 335 252 767 e-8 0.000 000 000 027 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 824 e-25    0.000 000 024 e-25    J
+inverse meter-kelvin relationship                      1.438 777 36 e-2      0.000 000 83 e-2      K
+inverse meter-kilogram relationship                    2.210 219 057 e-42    0.000 000 027 e-42    kg
+inverse of conductance quantum                         12 906.403 7278       0.000 0029            ohm
+Josephson constant                                     483 597.8525 e9       0.0030 e9             Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 363 e9      0.000 000 082 e9      u
+joule-electron volt relationship                       6.241 509 126 e18     0.000 000 038 e18     eV
+joule-hartree relationship                             2.293 712 317 e17     0.000 000 028 e17     E_h
+joule-hertz relationship                               1.509 190 205 e33     0.000 000 019 e33     Hz
+joule-inverse meter relationship                       5.034 116 651 e24     0.000 000 062 e24     m^-1
+joule-kelvin relationship                              7.242 9731 e22        0.000 0042 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0842 e-14       0.000 0053 e-14       u
+kelvin-electron volt relationship                      8.617 3303 e-5        0.000 0050 e-5        eV
+kelvin-hartree relationship                            3.166 8105 e-6        0.000 0018 e-6        E_h
+kelvin-hertz relationship                              2.083 6612 e10        0.000 0012 e10        Hz
+kelvin-inverse meter relationship                      69.503 457            0.000 040             m^-1
+kelvin-joule relationship                              1.380 648 52 e-23     0.000 000 79 e-23     J
+kelvin-kilogram relationship                           1.536 178 65 e-40     0.000 000 88 e-40     kg
+kilogram-atomic mass unit relationship                 6.022 140 857 e26     0.000 000 074 e26     u
+kilogram-electron volt relationship                    5.609 588 650 e35     0.000 000 034 e35     eV
+kilogram-hartree relationship                          2.061 485 823 e34     0.000 000 025 e34     E_h
+kilogram-hertz relationship                            1.356 392 512 e50     0.000 000 017 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 411 e41     0.000 000 056 e41     m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6595 e39        0.000 0037 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6467 e25        0.000 0015 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7811 e25        0.000 0015 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 831 e-15    0.000 000 013 e-15    Wb
+molar gas constant                                     8.314 4598            0.000 0048            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7110 e-10   0.000 000 0018 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 582     0.000 000 000 054     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 947 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 962 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 832 14 e-6     0.000 000 61 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 11 e-15    0.000 000 26 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 308 e-15    0.000 000 042 e-15    m
+muon-electron mass ratio                               206.768 2826          0.000 0046
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 26 e-26    0.000 000 10 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 89 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 48 e-3     0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 20
+muon mass                                              1.883 531 594 e-28    0.000 000 048 e-28    kg
+muon mass energy equivalent                            1.692 833 774 e-11    0.000 000 043 e-11    J
+muon mass energy equivalent in MeV                     105.658 3745          0.000 0024            MeV
+muon mass in u                                         0.113 428 9257        0.000 000 0025        u
+muon molar mass                                        0.113 428 9257 e-3    0.000 000 0025 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0025
+muon-proton mag. mom. ratio                            -3.183 345 142        0.000 000 071
+muon-proton mass ratio                                 0.112 609 5262        0.000 000 0025
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 800 e-34    0.000 000 013 e-34    J s
+natural unit of action in eV s                         6.582 119 514 e-16    0.000 000 040 e-16    eV s
+natural unit of energy                                 8.187 105 65 e-14     0.000 000 10 e-14     J
+natural unit of energy in MeV                          0.510 998 9461        0.000 000 0031        MeV
+natural unit of length                                 386.159 267 64 e-15   0.000 000 18 e-15     m
+natural unit of mass                                   9.109 383 56 e-31     0.000 000 11 e-31     kg
+natural unit of mom.um                                 2.730 924 488 e-22    0.000 000 034 e-22    kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 9461        0.000 000 0031        MeV/c
+natural unit of time                                   1.288 088 667 12 e-21 0.000 000 000 58 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 904 81 e-15 0.000 000 000 88 e-15 m
+neutron Compton wavelength over 2 pi                   0.210 019 415 36 e-15 0.000 000 000 14 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 661 58       0.000 000 90
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 72 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6933           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 50 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 471 e-27    0.000 000 021 e-27    kg
+neutron mass energy equivalent                         1.505 349 739 e-10    0.000 000 019 e-10    J
+neutron mass energy equivalent in MeV                  939.565 4133          0.000 0058            MeV
+neutron mass in u                                      1.008 664 915 88      0.000 000 000 49      u
+neutron molar mass                                     1.008 664 915 88 e-3  0.000 000 000 49 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 08          0.000 000 20
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 77 e-30     0.000 000 85 e-30
+neutron-proton mass difference energy equivalent       2.072 146 37 e-13     0.000 000 76 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 05         0.000 000 48
+neutron-proton mass difference in u                    0.001 388 449 00      0.000 000 000 51
+neutron-proton mass ratio                              1.001 378 418 98      0.000 000 000 51
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 08 e-11         0.000 31 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 61 e-39         0.000 31 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 699 e-27    0.000 000 031 e-27    J T^-1
+nuclear magneton in eV/T                               3.152 451 2550 e-8    0.000 000 0015 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 432 e-2     0.000 000 016 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2690 e-4        0.000 0021 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 285         0.000 000 047         MHz T^-1
+Planck constant                                        6.626 070 040 e-34    0.000 000 081 e-34    J s
+Planck constant in eV s                                4.135 667 662 e-15    0.000 000 025 e-15    eV s
+Planck constant over 2 pi                              1.054 571 800 e-34    0.000 000 013 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 514 e-16    0.000 000 040 e-16    eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9788          0.000 0012            MeV fm
+Planck length                                          1.616 229 e-35        0.000 038 e-35        m
+Planck mass                                            2.176 470 e-8         0.000 051 e-8         kg
+Planck mass energy equivalent in GeV                   1.220 910 e19         0.000 029 e19         GeV
+Planck temperature                                     1.416 808 e32         0.000 033 e32         K
+Planck time                                            5.391 16 e-44         0.000 13 e-44         s
+proton charge to mass quotient                         9.578 833 226 e7      0.000 000 059 e7      C kg^-1
+proton Compton wavelength                              1.321 409 853 96 e-15 0.000 000 000 61 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308910109e-15   0.000 000 000097e-15  m
+proton-electron mass ratio                             1836.152 673 89       0.000 000 17
+proton g factor                                        5.585 694 702         0.000 000 017
+proton gyromag. ratio                                  2.675 221 900 e8      0.000 000 018 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 478 92         0.000 000 29          MHz T^-1
+proton mag. mom.                                       1.410 606 7873 e-26   0.000 000 0097 e-26   J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 2053 e-3    0.000 000 0046 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 3508        0.000 000 0085
+proton mag. shielding correction                       25.691 e-6            0.011 e-6
+proton mass                                            1.672 621 898 e-27    0.000 000 021 e-27    kg
+proton mass energy equivalent                          1.503 277 593 e-10    0.000 000 018 e-10    J
+proton mass energy equivalent in MeV                   938.272 0813          0.000 0058            MeV
+proton mass in u                                       1.007 276 466 879     0.000 000 000 091     u
+proton molar mass                                      1.007 276 466 879 e-3 0.000 000 000 091 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 38          0.000 000 20
+proton-neutron mag. mom. ratio                         -1.459 898 05         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 44      0.000 000 000 51
+proton rms charge radius                               0.8751 e-15           0.0061 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5486 e-4    0.000 000 0017 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 0972 e-4    0.000 000 0033 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 508    0.000 065             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 355 e15 0.000 000 000 019 e15 Hz
+Rydberg constant times hc in eV                        13.605 693 009        0.000 000 084         eV
+Rydberg constant times hc in J                         2.179 872 325 e-18    0.000 000 027 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7084           0.000 0014
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8714           0.000 0014
+second radiation constant                              1.438 777 36 e-2      0.000 000 83 e-2      m K
+shielded helion gyromag. ratio                         2.037 894 585 e8      0.000 000 027 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 099 66         0.000 000 43          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 080 e-26   0.000 000 014 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 720        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 5603       0.000 000 0092
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 171 e8      0.000 000 033 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 385 07         0.000 000 53          MHz T^-1
+shielded proton mag. mom.                              1.410 570 547 e-26    0.000 000 018 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 600         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 367 e-8         0.000 013 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 871 58 e-28 0.000 000 000 91 e-28 m^2
+triton-electron mass ratio                             5496.921 535 88       0.000 000 26
+triton g factor                                        5.957 924 920         0.000 000 028
+triton mag. mom.                                       1.504 609 503 e-26    0.000 000 012 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 6616 e-3    0.000 000 0076 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 460         0.000 000 014
+triton mass                                            5.007 356 665 e-27    0.000 000 062 e-27    kg
+triton mass energy equivalent                          4.500 387 735 e-10    0.000 000 055 e-10    J
+triton mass energy equivalent in MeV                   2808.921 112          0.000 017             MeV
+triton mass in u                                       3.015 500 716 32      0.000 000 000 11      u
+triton molar mass                                      3.015 500 716 32 e-3  0.000 000 000 11 e-3  kg mol^-1
+triton-proton mass ratio                               2.993 717 033 48      0.000 000 000 22
+unified atomic mass unit                               1.660 539 040 e-27    0.000 000 020 e-27    kg
+von Klitzing constant                                  25 812.807 4555       0.000 0059            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9238 e10        0.000 0034 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7729 e-3        0.000 0017 e-3        m K"""
+
+
+exact2014 = exact2010
+
+
+txt2018 = """\
+alpha particle-electron mass ratio                          7294.299 541 42          0.000 000 24
+alpha particle mass                                         6.644 657 3357 e-27      0.000 000 0020 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1914 e-10      0.000 000 0018 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4066            0.000 0011               MeV
+alpha particle mass in u                                    4.001 506 179 127        0.000 000 000 063        u
+alpha particle molar mass                                   4.001 506 1777 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 09         0.000 000 000 22
+alpha particle relative atomic mass                         4.001 506 179 127        0.000 000 000 063
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 102 42           0.000 000 28             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0242 e8        0.000 000 0028 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6874 e7        0.000 000 0010 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 718 71 e23     0.000 000 000 68 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6104 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 019 16 e13     0.000 000 000 33 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 3061 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9905 e-65      0.000 000 0038 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 384 57 e12     0.000 000 000 49 e12     C m^-3
+atomic unit of current                                      6.623 618 237 510 e-3    0.000 000 000 013 e-3    A
+atomic unit of electric dipole mom.                         8.478 353 6255 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 747 63 e11     0.000 000 000 78 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4292 e21       0.000 000 0029 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 274 36 e-41    0.000 000 000 50 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 988       0.000 000 000 053        V
+atomic unit of electric quadrupole mom.                     4.486 551 5246 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+atomic unit of force                                        8.238 723 4983 e-8       0.000 000 0012 e-8       N
+atomic unit of length                                       5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 015 66 e-23    0.000 000 000 56 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 567 58 e5      0.000 000 000 71 e5      T
+atomic unit of magnetizability                              7.891 036 6008 e-29      0.000 000 0048 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 914 10 e-24    0.000 000 000 30 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 055 45 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5857 e-17  0.000 000 000 0047 e-17  s
+atomic unit of velocity                                     2.187 691 263 64 e6      0.000 000 000 33 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0783 e-24      0.000 000 0028 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 8060 e-5       0.000 000 0017 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 493 61 e10     0.000 000 000 42 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 783           0.000 000 014            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 815 63         0.000 000 000 20         K T^-1
+Bohr radius                                                 5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 668          0.000 000 057            ohm
+classical electron radius                                   2.817 940 3262 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 238 67 e-12    0.000 000 000 73 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Cu x unit                                                   1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 551 e-4       0.000 000 012 e-4
+deuteron-electron mass ratio                                3670.482 967 88          0.000 000 13
+deuteron g factor                                           0.857 438 2338           0.000 000 0022
+deuteron mag. mom.                                          4.330 735 094 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 570 e-4        0.000 000 012 e-4
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2338           0.000 000 0022
+deuteron mass                                               3.343 583 7724 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 231 02 e-10    0.000 000 000 91 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 942 57          0.000 000 57             MeV
+deuteron mass in u                                          2.013 553 212 745        0.000 000 000 040        u
+deuteron molar mass                                         2.013 553 212 05 e-3     0.000 000 000 61 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 53            0.000 000 11
+deuteron-proton mag. mom. ratio                             0.307 012 209 39         0.000 000 000 79
+deuteron-proton mass ratio                                  1.999 007 501 39         0.000 000 000 11
+deuteron relative atomic mass                               2.013 553 212 745        0.000 000 000 040
+deuteron rms charge radius                                  2.127 99 e-15            0.000 74 e-15            m
+electron charge to mass quotient                            -1.758 820 010 76 e11    0.000 000 000 53 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4915           0.000 0056
+electron-deuteron mass ratio                                2.724 437 107 462 e-4    0.000 000 000 096 e-4
+electron g factor                                           -2.002 319 304 362 56    0.000 000 000 000 35
+electron gyromag. ratio                                     1.760 859 630 23 e11     0.000 000 000 53 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 4242          0.000 0085               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 573 e-4    0.000 000 000 079 e-4
+electron mag. mom.                                          -9.284 764 7043 e-24     0.000 000 0028 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 181 28 e-3     0.000 000 000 18 e-3
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 181 28    0.000 000 000 000 18
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 88         0.000 000 11
+electron mass                                               9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7769 e-14      0.000 000 0025 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 00         0.000 000 000 15         MeV
+electron mass in u                                          5.485 799 090 65 e-4     0.000 000 000 16 e-4     u
+electron molar mass                                         5.485 799 0888 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9883             0.000 0046
+electron-muon mass ratio                                    4.836 331 69 e-3         0.000 000 11 e-3
+electron-neutron mag. mom. ratio                            960.920 50               0.000 23
+electron-neutron mass ratio                                 5.438 673 4424 e-4       0.000 000 0026 e-4
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 20
+electron-proton mass ratio                                  5.446 170 214 87 e-4     0.000 000 000 33 e-4
+electron relative atomic mass                               5.485 799 090 65 e-4     0.000 000 000 16 e-4
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4
+electron to alpha particle mass ratio                       1.370 933 554 787 e-4    0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio                 864.058 257              0.000 010
+electron to shielded proton mag. mom. ratio                 -658.227 5971            0.000 0072
+electron-triton mass ratio                                  1.819 200 062 251 e-4    0.000 000 000 090 e-4
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 102 33 e-9     0.000 000 000 32 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5655 e-2   0.000 000 000 0071 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5693 e-3       0.000 000 0011 e-3
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 322 05 e-8     0.000 000 000 88 e-8     u
+hartree-electron volt relationship                          27.211 386 245 988       0.000 000 000 053        eV
+Hartree energy                                              4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+Hartree energy in eV                                        27.211 386 245 988       0.000 000 000 053        eV
+hartree-hertz relationship                                  6.579 683 920 502 e15    0.000 000 000 013 e15    Hz
+hartree-inverse meter relationship                          2.194 746 313 6320 e7    0.000 000 000 0043 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0407 e5    0.000 000 000 0061 e5    K
+hartree-kilogram relationship                               4.850 870 209 5432 e-35  0.000 000 000 0094 e-35  kg
+helion-electron mass ratio                                  5495.885 280 07          0.000 000 24
+helion g factor                                             -4.255 250 615           0.000 000 050
+helion mag. mom.                                            -1.074 617 532 e-26      0.000 000 013 e-26       J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 958 e-3       0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 307           0.000 000 025
+helion mass                                                 5.006 412 7796 e-27      0.000 000 0015 e-27      kg
+helion mass energy equivalent                               4.499 539 4125 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 607 43          0.000 000 85             MeV
+helion mass in u                                            3.014 932 247 175        0.000 000 000 097        u
+helion molar mass                                           3.014 932 246 13 e-3     0.000 000 000 91 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 67         0.000 000 000 13
+helion relative atomic mass                                 3.014 932 247 175        0.000 000 000 097
+helion shielding shift                                      5.996 743 e-5            0.000 010 e-5
+hertz-atomic mass unit relationship                         4.439 821 6652 e-24      0.000 000 0013 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0570 e-16  0.000 000 000 0029 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 084          0.000 000 021
+inverse meter-atomic mass unit relationship                 1.331 025 050 10 e-15    0.000 000 000 40 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9120 e-8   0.000 000 000 0088 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2565 e9        0.000 000 0020 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3963 e17   0.000 000 000 0045 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 3014 e-14      0.000 000 0028 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4556 e-6   0.000 000 000 0061 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7621 e26       0.000 000 0018 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7409 e34   0.000 000 000 0040 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         0.999 999 999 65 e-3     0.000 000 000 30 e-3     kg mol^-1
+molar mass of carbon-12                                     11.999 999 9958 e-3      0.000 000 0036 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Mo x unit                                                   1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2830             0.000 0046
+muon g factor                                               -2.002 331 8418          0.000 000 0013
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 89 e-3         0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 47 e-3        0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 03            0.000 000 20
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9259           0.000 000 0025           u
+muon molar mass                                             1.134 289 259 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5170           0.000 000 0025
+muon-proton mag. mom. ratio                                 -3.183 345 142           0.000 000 071
+muon-proton mass ratio                                      0.112 609 5264           0.000 000 0025
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7769 e-14      0.000 000 0025 e-14      J
+natural unit of energy in MeV                               0.510 998 950 00         0.000 000 000 15         MeV
+natural unit of length                                      3.861 592 6796 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 530 75 e-22    0.000 000 000 82 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 00         0.000 000 000 15         MeV/c
+natural unit of time                                        1.288 088 668 19 e-21    0.000 000 000 39 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 905 81 e-15    0.000 000 000 75 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 82 e-3         0.000 000 25 e-3
+neutron-electron mass ratio                                 1838.683 661 73          0.000 000 89
+neutron g factor                                            -3.826 085 45            0.000 000 90
+neutron gyromag. ratio                                      1.832 471 71 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6931              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3651 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 63 e-3        0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 73            0.000 000 45
+neutron mass                                                1.674 927 498 04 e-27    0.000 000 000 95 e-27    kg
+neutron mass energy equivalent                              1.505 349 762 87 e-10    0.000 000 000 86 e-10    J
+neutron mass energy equivalent in MeV                       939.565 420 52           0.000 000 54             MeV
+neutron mass in u                                           1.008 664 915 95         0.000 000 000 49         u
+neutron molar mass                                          1.008 664 915 60 e-3     0.000 000 000 57 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 06             0.000 000 20
+neutron-proton mag. mom. ratio                              -0.684 979 34            0.000 000 16
+neutron-proton mass difference                              2.305 574 35 e-30        0.000 000 82 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 146 89 e-13        0.000 000 74 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 36             0.000 000 46             MeV
+neutron-proton mass difference in u                         1.388 449 33 e-3         0.000 000 49 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 31         0.000 000 000 49
+neutron relative atomic mass                                1.008 664 915 95         0.000 000 000 49
+neutron-tau mass ratio                                      0.528 779                0.000 036
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7461 e-27      0.000 000 0015 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 258 44 e-8     0.000 000 000 96 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 413 53 e-2     0.000 000 000 78 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7756 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2291           0.000 000 0023           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1560 e7        0.000 000 0029 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 855 39 e-15    0.000 000 000 40 e-15    m
+proton-electron mass ratio                                  1836.152 673 43          0.000 000 11
+proton g factor                                             5.585 694 6893           0.000 000 0016
+proton gyromag. ratio                                       2.675 221 8744 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 518           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 797 36 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 46 e-3
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82
+proton mag. shielding correction                            2.5689 e-5               0.0011 e-5
+proton mass                                                 1.672 621 923 69 e-27    0.000 000 000 51 e-27    kg
+proton mass energy equivalent                               1.503 277 615 98 e-10    0.000 000 000 46 e-10    J
+proton mass energy equivalent in MeV                        938.272 088 16           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 621        0.000 000 000 053        u
+proton molar mass                                           1.007 276 466 27 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 37             0.000 000 20
+proton-neutron mag. mom. ratio                              -1.459 898 05            0.000 000 34
+proton-neutron mass ratio                                   0.998 623 478 12         0.000 000 000 49
+proton relative atomic mass                                 1.007 276 466 621        0.000 000 000 053
+proton rms charge radius                                    8.414 e-16               0.019 e-16               m
+proton-tau mass ratio                                       0.528 051                0.000 036
+quantum of circulation                                      3.636 947 5516 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 1032 e-4       0.000 000 0022 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6796 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1552 e-16      0.000 000 0012 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 103 36 e-16    0.000 000 000 64 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 160       0.000 021                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2508 e15   0.000 000 000 0064 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 994       0.000 000 000 026        eV
+Rydberg constant times hc in J                              2.179 872 361 1035 e-18  0.000 000 000 0042 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 537 06        0.000 000 000 45
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 523 58        0.000 000 000 45
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 569 e8         0.000 000 024 e8         s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 099 42            0.000 000 38             MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 090 e-26      0.000 000 013 e-26       J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 471 e-3       0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 719           0.000 000 025
+shielded helion to proton mag. mom. ratio                   -0.761 766 5618          0.000 000 0089
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1313          0.000 000 0033
+shielded proton gyromag. ratio                              2.675 153 151 e8         0.000 000 029 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 384 74            0.000 000 46             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 560 e-26       0.000 000 015 e-26       J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 128 e-3        0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 599            0.000 000 030
+shielding difference of d and p in HD                       2.0200 e-8               0.0020 e-8
+shielding difference of t and p in HT                       2.4140 e-8               0.0020 e-8
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011
+tau-neutron mass ratio                                      1.891 15                 0.000 13
+tau-proton mass ratio                                       1.893 76                 0.000 13
+Thomson cross section                                       6.652 458 7321 e-29      0.000 000 0060 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 73          0.000 000 27
+triton g factor                                             5.957 924 931            0.000 000 012
+triton mag. mom.                                            1.504 609 5202 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6651 e-3       0.000 000 0032 e-3
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4656           0.000 000 0059
+triton mass                                                 5.007 356 7446 e-27      0.000 000 0015 e-27      kg
+triton mass energy equivalent                               4.500 387 8060 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 132 98          0.000 000 85             MeV
+triton mass in u                                            3.015 500 716 21         0.000 000 000 12         u
+triton molar mass                                           3.015 500 715 17 e-3     0.000 000 000 92 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 14         0.000 000 000 15
+triton relative atomic mass                                 3.015 500 716 21         0.000 000 000 12
+triton to proton mag. mom. ratio                            1.066 639 9191           0.000 000 0021
+unified atomic mass unit                                    1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+vacuum electric permittivity                                8.854 187 8128 e-12      0.000 000 0013 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 062 12 e-6     0.000 000 000 19 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.222 90                 0.000 30
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 53                 0.000 17                   """
+
+
+def exact2018(exact):
+    # SI base constants
+    c = exact['speed of light in vacuum']
+    h = exact['Planck constant']
+    e = exact['elementary charge']
+    k = exact['Boltzmann constant']
+    N_A = exact['Avogadro constant']
+
+    # Other useful constants
+    R = N_A * k
+    hbar = h / (2*math.pi)
+    G_0 = 2 * e**2 / h
+
+    # Wien law numerical constants: https://en.wikipedia.org/wiki/Wien%27s_displacement_law
+    # (alpha - 3)*exp(alpha) + 3 = 0
+    # (x - 5)*exp(x) + 5 = 0
+    alpha_W = 2.821439372122078893403  # 3 + lambertw(-3 * exp(-3))
+    x_W = 4.965114231744276303699  # 5 + lambertw(-5 * exp(-5))
+
+    # Conventional electrical unit
+    # See https://en.wikipedia.org/wiki/Conventional_electrical_unit
+    K_J90 = exact['conventional value of Josephson constant']
+    K_J = 2 * e / h
+    R_K90 = exact['conventional value of von Klitzing constant']
+    R_K = h / e**2
+    V_90 = K_J90 / K_J
+    ohm_90 = R_K / R_K90
+    A_90 = V_90 / ohm_90
+
+    replace = {
+        'atomic unit of action': hbar,
+        'Boltzmann constant in eV/K': k / e,
+        'Boltzmann constant in Hz/K': k / h,
+        'Boltzmann constant in inverse meter per kelvin': k / (h * c),
+        'conductance quantum': G_0,
+        'conventional value of ampere-90': A_90,
+        'conventional value of coulomb-90': A_90,
+        'conventional value of farad-90': 1 / ohm_90,
+        'conventional value of henry-90': ohm_90,
+        'conventional value of ohm-90': ohm_90,
+        'conventional value of volt-90': V_90,
+        'conventional value of watt-90': V_90**2 / ohm_90,
+        'electron volt-hertz relationship': e / h,
+        'electron volt-inverse meter relationship': e / (h * c),
+        'electron volt-kelvin relationship': e / k,
+        'electron volt-kilogram relationship': e / c**2,
+        'elementary charge over h-bar': e / hbar,
+        'Faraday constant': e * N_A,
+        'first radiation constant': 2 * math.pi * h * c**2,
+        'first radiation constant for spectral radiance': 2 * h * c**2,
+        'hertz-electron volt relationship': h / e,
+        'hertz-inverse meter relationship': 1 / c,
+        'hertz-kelvin relationship': h / k,
+        'hertz-kilogram relationship': h / c**2,
+        'inverse meter-electron volt relationship': (h * c) / e,
+        'inverse meter-joule relationship': h * c,
+        'inverse meter-kelvin relationship': h * c / k,
+        'inverse meter-kilogram relationship': h / c,
+        'inverse of conductance quantum': 1 / G_0,
+        'Josephson constant': K_J,
+        'joule-electron volt relationship': 1 / e,
+        'joule-hertz relationship': 1 / h,
+        'joule-inverse meter relationship': 1 / (h * c),
+        'joule-kelvin relationship': 1 / k,
+        'joule-kilogram relationship': 1 / c**2,
+        'kelvin-electron volt relationship': k / e,
+        'kelvin-hertz relationship': k / h,
+        'kelvin-inverse meter relationship': k / (h * c),
+        'kelvin-kilogram relationship': k / c**2,
+        'kilogram-electron volt relationship': c**2 / e,
+        'kilogram-hertz relationship': c**2 / h,
+        'kilogram-inverse meter relationship': c / h,
+        'kilogram-joule relationship': c**2,
+        'kilogram-kelvin relationship': c**2 / k,
+        'Loschmidt constant (273.15 K, 100 kPa)': 100e3 / 273.15 / k,
+        'Loschmidt constant (273.15 K, 101.325 kPa)': 101.325e3 / 273.15 / k,
+        'mag. flux quantum': h / (2 * e),
+        'molar gas constant': R,
+        'molar Planck constant': h * N_A,
+        'molar volume of ideal gas (273.15 K, 100 kPa)': R * 273.15 / 100e3,
+        'molar volume of ideal gas (273.15 K, 101.325 kPa)': R * 273.15 / 101.325e3,
+        'natural unit of action': hbar,
+        'natural unit of action in eV s': hbar / e,
+        'Planck constant in eV/Hz': h / e,
+        'reduced Planck constant': hbar,
+        'reduced Planck constant in eV s': hbar / e,
+        'reduced Planck constant times c in MeV fm': hbar * c / (e * 1e6 * 1e-15),
+        'second radiation constant': h * c / k,
+        'Stefan-Boltzmann constant': 2 * math.pi**5 * k**4 / (15 * h**3 * c**2),
+        'von Klitzing constant': R_K,
+        'Wien frequency displacement law constant': alpha_W * k / h,
+        'Wien wavelength displacement law constant': h * c / (x_W * k),
+    }
+    return replace
+
+
+txt2022 = """\
+alpha particle-electron mass ratio                          7294.299 541 71          0.000 000 17             
+alpha particle mass                                         6.644 657 3450 e-27      0.000 000 0021 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1997 e-10      0.000 000 0019 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4118            0.000 0012               MeV
+alpha particle mass in u                                    4.001 506 179 129        0.000 000 000 062        u
+alpha particle molar mass                                   4.001 506 1833 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 252        0.000 000 000 070        
+alpha particle relative atomic mass                         4.001 506 179 129        0.000 000 000 062        
+alpha particle rms charge radius                            1.6785 e-15              0.0021 e-15              m
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 103 72           0.000 000 29             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0372 e8        0.000 000 0029 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6922 e7        0.000 000 0011 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 721 85 e23     0.000 000 000 70 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6209 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 020 67 e13     0.000 000 000 34 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 2996 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9735 e-65      0.000 000 0039 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 386 77 e12     0.000 000 000 51 e12     C m^-3
+atomic unit of current                                      6.623 618 237 5082 e-3   0.000 000 000 0072 e-3   A
+atomic unit of electric dipole mom.                         8.478 353 6198 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 751 12 e11     0.000 000 000 80 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4424 e21       0.000 000 0030 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 272 12 e-41    0.000 000 000 51 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 981       0.000 000 000 030        V
+atomic unit of electric quadrupole mom.                     4.486 551 5185 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+atomic unit of force                                        8.238 723 5038 e-8       0.000 000 0013 e-8       N
+atomic unit of length                                       5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 013 15 e-23    0.000 000 000 58 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 570 77 e5      0.000 000 000 73 e5      T
+atomic unit of magnetizability                              7.891 036 5794 e-29      0.000 000 0049 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 915 45 e-24    0.000 000 000 31 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 056 20 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5864 e-17  0.000 000 000 0026 e-17  s
+atomic unit of velocity                                     2.187 691 262 16 e6      0.000 000 000 34 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0657 e-24      0.000 000 0029 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 7982 e-5       0.000 000 0018 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 491 71 e10     0.000 000 000 44 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 719           0.000 000 015            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 814 72         0.000 000 000 21         K T^-1
+Bohr radius                                                 5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 412          0.000 000 059            ohm
+classical electron radius                                   2.817 940 3205 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 235 38 e-12    0.000 000 000 76 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Copper x unit                                               1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 550 e-4       0.000 000 012 e-4        
+deuteron-electron mass ratio                                3670.482 967 655         0.000 000 063            
+deuteron g factor                                           0.857 438 2335           0.000 000 0022           
+deuteron mag. mom.                                          4.330 735 087 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 568 e-4        0.000 000 012 e-4        
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2335           0.000 000 0022           
+deuteron mass                                               3.343 583 7768 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 234 91 e-10    0.000 000 000 94 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 945 00          0.000 000 58             MeV
+deuteron mass in u                                          2.013 553 212 544        0.000 000 000 015        u
+deuteron molar mass                                         2.013 553 214 66 e-3     0.000 000 000 63 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 52            0.000 000 11             
+deuteron-proton mag. mom. ratio                             0.307 012 209 30         0.000 000 000 79         
+deuteron-proton mass ratio                                  1.999 007 501 2699       0.000 000 000 0084       
+deuteron relative atomic mass                               2.013 553 212 544        0.000 000 000 015        
+deuteron rms charge radius                                  2.127 78 e-15            0.000 27 e-15            m
+electron charge to mass quotient                            -1.758 820 008 38 e11    0.000 000 000 55 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4921           0.000 0056               
+electron-deuteron mass ratio                                2.724 437 107 629 e-4    0.000 000 000 047 e-4    
+electron g factor                                           -2.002 319 304 360 92    0.000 000 000 000 36     
+electron gyromag. ratio                                     1.760 859 627 84 e11     0.000 000 000 55 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 3861          0.000 0087               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 649 e-4    0.000 000 000 053 e-4    
+electron mag. mom.                                          -9.284 764 6917 e-24     0.000 000 0029 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 180 46 e-3     0.000 000 000 18 e-3     
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 180 46    0.000 000 000 000 18     
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 877        0.000 000 032            
+electron mass                                               9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7880 e-14      0.000 000 0026 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 69         0.000 000 000 16         MeV
+electron mass in u                                          5.485 799 090 441 e-4    0.000 000 000 097 e-4    u
+electron molar mass                                         5.485 799 0962 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9881             0.000 0046               
+electron-muon mass ratio                                    4.836 331 70 e-3         0.000 000 11 e-3         
+electron-neutron mag. mom. ratio                            960.920 48               0.000 23                 
+electron-neutron mass ratio                                 5.438 673 4416 e-4       0.000 000 0022 e-4       
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 19             
+electron-proton mass ratio                                  5.446 170 214 889 e-4    0.000 000 000 094 e-4    
+electron relative atomic mass                               5.485 799 090 441 e-4    0.000 000 000 097 e-4    
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4             
+electron to alpha particle mass ratio                       1.370 933 554 733 e-4    0.000 000 000 032 e-4    
+electron to shielded helion mag. mom. ratio                 864.058 239 86           0.000 000 70             
+electron to shielded proton mag. mom. ratio                 -658.227 5856            0.000 0027               
+electron-triton mass ratio                                  1.819 200 062 327 e-4    0.000 000 000 068 e-4    
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 100 83 e-9     0.000 000 000 33 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5665 e-2   0.000 000 000 0040 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5643 e-3       0.000 000 0011 e-3       
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 317 97 e-8     0.000 000 000 91 e-8     u
+hartree-electron volt relationship                          27.211 386 245 981       0.000 000 000 030        eV
+Hartree energy                                              4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+Hartree energy in eV                                        27.211 386 245 981       0.000 000 000 030        eV
+hartree-hertz relationship                                  6.579 683 920 4999 e15   0.000 000 000 0072 e15   Hz
+hartree-inverse meter relationship                          2.194 746 313 6314 e7    0.000 000 000 0024 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0398 e5    0.000 000 000 0034 e5    K
+hartree-kilogram relationship                               4.850 870 209 5419 e-35  0.000 000 000 0053 e-35  kg
+helion-electron mass ratio                                  5495.885 279 84          0.000 000 16             
+helion g factor                                             -4.255 250 6995          0.000 000 0034           
+helion mag. mom.                                            -1.074 617 551 98 e-26   0.000 000 000 93 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 980 83 e-3    0.000 000 000 94 e-3     
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 3498          0.000 000 0017           
+helion mass                                                 5.006 412 7862 e-27      0.000 000 0016 e-27      kg
+helion mass energy equivalent                               4.499 539 4185 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 611 12          0.000 000 88             MeV
+helion mass in u                                            3.014 932 246 932        0.000 000 000 074        u
+helion molar mass                                           3.014 932 250 10 e-3     0.000 000 000 94 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 552        0.000 000 000 070        
+helion relative atomic mass                                 3.014 932 246 932        0.000 000 000 074        
+helion shielding shift                                      5.996 7029 e-5           0.000 0023 e-5           
+hertz-atomic mass unit relationship                         4.439 821 6590 e-24      0.000 000 0014 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0574 e-16  0.000 000 000 0017 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 177          0.000 000 021            
+inverse meter-atomic mass unit relationship                 1.331 025 048 24 e-15    0.000 000 000 41 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9132 e-8   0.000 000 000 0050 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2471 e9        0.000 000 0021 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3969 e17   0.000 000 000 0025 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 2884 e-14      0.000 000 0029 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4564 e-6   0.000 000 000 0035 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7537 e26       0.000 000 0019 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7415 e34   0.000 000 000 0022 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         1.000 000 001 05 e-3     0.000 000 000 31 e-3     kg mol^-1
+molar mass of carbon-12                                     12.000 000 0126 e-3      0.000 000 0037 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Molybdenum x unit                                           1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2827             0.000 0046               
+muon g factor                                               -2.002 331 841 23        0.000 000 000 82         
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 62 e-3         0.000 000 41 e-3         
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 48 e-3        0.000 000 11 e-3         
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 04            0.000 000 20             
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9257           0.000 000 0025           u
+muon molar mass                                             1.134 289 258 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5168           0.000 000 0025           
+muon-proton mag. mom. ratio                                 -3.183 345 146           0.000 000 071            
+muon-proton mass ratio                                      0.112 609 5262           0.000 000 0025           
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2             
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7880 e-14      0.000 000 0026 e-14      J
+natural unit of energy in MeV                               0.510 998 950 69         0.000 000 000 16         MeV
+natural unit of length                                      3.861 592 6744 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 534 46 e-22    0.000 000 000 85 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 69         0.000 000 000 16         MeV/c
+natural unit of time                                        1.288 088 666 44 e-21    0.000 000 000 40 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 903 82 e-15    0.000 000 000 67 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 84 e-3         0.000 000 24 e-3         
+neutron-electron mass ratio                                 1838.683 662 00          0.000 000 74             
+neutron g factor                                            -3.826 085 52            0.000 000 90             
+neutron gyromag. ratio                                      1.832 471 74 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6935              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3653 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 65 e-3        0.000 000 25 e-3         
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 76            0.000 000 45             
+neutron mass                                                1.674 927 500 56 e-27    0.000 000 000 85 e-27    kg
+neutron mass energy equivalent                              1.505 349 765 14 e-10    0.000 000 000 76 e-10    J
+neutron mass energy equivalent in MeV                       939.565 421 94           0.000 000 48             MeV
+neutron mass in u                                           1.008 664 916 06         0.000 000 000 40         u
+neutron molar mass                                          1.008 664 917 12 e-3     0.000 000 000 51 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 08             0.000 000 20             
+neutron-proton mag. mom. ratio                              -0.684 979 35            0.000 000 16             
+neutron-proton mass difference                              2.305 574 61 e-30        0.000 000 67 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 147 12 e-13        0.000 000 60 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 51             0.000 000 38             MeV
+neutron-proton mass difference in u                         1.388 449 48 e-3         0.000 000 40 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 46         0.000 000 000 40         
+neutron relative atomic mass                                1.008 664 916 06         0.000 000 000 40         
+neutron-tau mass ratio                                      0.528 779                0.000 036                
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16             
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7393 e-27      0.000 000 0016 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 254 17 e-8     0.000 000 000 98 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 410 09 e-2     0.000 000 000 79 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7706 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2188           0.000 000 0024           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1430 e7        0.000 000 0030 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 853 60 e-15    0.000 000 000 41 e-15    m
+proton-electron mass ratio                                  1836.152 673 426         0.000 000 032            
+proton g factor                                             5.585 694 6893           0.000 000 0016           
+proton gyromag. ratio                                       2.675 221 8708 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 461           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 795 45 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 45 e-3     
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82         
+proton mag. shielding correction                            2.567 15 e-5             0.000 41 e-5             
+proton mass                                                 1.672 621 925 95 e-27    0.000 000 000 52 e-27    kg
+proton mass energy equivalent                               1.503 277 618 02 e-10    0.000 000 000 47 e-10    J
+proton mass energy equivalent in MeV                        938.272 089 43           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 5789       0.000 000 000 0083       u
+proton molar mass                                           1.007 276 467 64 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 38             0.000 000 20             
+proton-neutron mag. mom. ratio                              -1.459 898 02            0.000 000 34             
+proton-neutron mass ratio                                   0.998 623 477 97         0.000 000 000 40         
+proton relative atomic mass                                 1.007 276 466 5789       0.000 000 000 0083       
+proton rms charge radius                                    8.4075 e-16              0.0064 e-16              m
+proton-tau mass ratio                                       0.528 051                0.000 036                
+quantum of circulation                                      3.636 947 5467 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 0934 e-4       0.000 000 0023 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6744 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1520 e-16      0.000 000 0011 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 100 51 e-16    0.000 000 000 66 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 157       0.000 012                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2500 e15   0.000 000 000 0036 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 990       0.000 000 000 015        eV
+Rydberg constant times hc in J                              2.179 872 361 1030 e-18  0.000 000 000 0024 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 534 96        0.000 000 000 47         
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 521 49        0.000 000 000 47         
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 6078 e8        0.000 000 0018 e8        s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 100 033           0.000 000 028            MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 110 35 e-26   0.000 000 000 93 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 494 57 e-3    0.000 000 000 94 e-3     
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 7624          0.000 000 0017           
+shielded helion to proton mag. mom. ratio                   -0.761 766 577 21        0.000 000 000 66         
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1334          0.000 000 0031           
+shielded proton gyromag. ratio                              2.675 153 194 e8         0.000 000 011 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 385 43            0.000 000 17             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 5830 e-26      0.000 000 0058 e-26      J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 1551 e-3       0.000 000 0062 e-3       
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 648            0.000 000 011            
+shielding difference of d and p in HD                       1.987 70 e-8             0.000 10 e-8             
+shielding difference of t and p in HT                       2.394 50 e-8             0.000 20 e-8             
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23                     
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011                   
+tau-neutron mass ratio                                      1.891 15                 0.000 13                 
+tau-proton mass ratio                                       1.893 76                 0.000 13                 
+Thomson cross section                                       6.652 458 7051 e-29      0.000 000 0062 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 51          0.000 000 21             
+triton g factor                                             5.957 924 930            0.000 000 012            
+triton mag. mom.                                            1.504 609 5178 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6648 e-3       0.000 000 0032 e-3       
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4650           0.000 000 0059           
+triton mass                                                 5.007 356 7512 e-27      0.000 000 0016 e-27      kg
+triton mass energy equivalent                               4.500 387 8119 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 136 68          0.000 000 88             MeV
+triton mass in u                                            3.015 500 715 97         0.000 000 000 10         u
+triton molar mass                                           3.015 500 719 13 e-3     0.000 000 000 94 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 03         0.000 000 000 10         
+triton relative atomic mass                                 3.015 500 715 97         0.000 000 000 10         
+triton to proton mag. mom. ratio                            1.066 639 9189           0.000 000 0021           
+unified atomic mass unit                                    1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+vacuum electric permittivity                                8.854 187 8188 e-12      0.000 000 0014 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 061 27 e-6     0.000 000 000 20 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.223 05                 0.000 23                 
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 45                 0.000 13                    """
+
+
+exact2022 = exact2018
+
+
+# -----------------------------------------------------------------------------
+
+
+def parse_constants_2002to2014(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:55].rstrip()
+        val = float(line[55:77].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[55:77]
+        is_exact = '(exact)' in line[77:99]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[77:99].replace(' ', '').replace('(exact)', '0'))
+        units = line[99:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def parse_constants_2018toXXXX(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:60].rstrip()
+        val = float(line[60:85].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[60:85]
+        is_exact = '(exact)' in line[85:110]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[85:110].replace(' ', '').replace('(exact)', '0'))
+        units = line[110:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def replace_exact(d, to_replace, exact):
+    for name in to_replace:
+        assert name in exact, f'Missing exact value: {name}'
+        assert abs(exact[name]/d[name][0] - 1) <= 1e-9, \
+            f'Bad exact value: {name}: { exact[name]}, {d[name][0]}'
+        d[name] = (exact[name],) + d[name][1:]
+    assert set(exact.keys()) == set(to_replace)
+
+
+_physical_constants_2002 = parse_constants_2002to2014(txt2002, exact2002)
+_physical_constants_2006 = parse_constants_2002to2014(txt2006, exact2006)
+_physical_constants_2010 = parse_constants_2002to2014(txt2010, exact2010)
+_physical_constants_2014 = parse_constants_2002to2014(txt2014, exact2014)
+_physical_constants_2018 = parse_constants_2018toXXXX(txt2018, exact2018)
+_physical_constants_2022 = parse_constants_2018toXXXX(txt2022, exact2022)
+
+physical_constants: dict[str, tuple[float, str, float]] = {}
+physical_constants.update(_physical_constants_2002)
+physical_constants.update(_physical_constants_2006)
+physical_constants.update(_physical_constants_2010)
+physical_constants.update(_physical_constants_2014)
+physical_constants.update(_physical_constants_2018)
+physical_constants.update(_physical_constants_2022)
+_current_constants = _physical_constants_2022
+_current_codata = "CODATA 2022"
+
+# check obsolete values
+_obsolete_constants = {}
+for k in physical_constants:
+    if k not in _current_constants:
+        _obsolete_constants[k] = True
+
+# generate some additional aliases
+_aliases = {}
+for k in _physical_constants_2002:
+    if 'magn.' in k:
+        _aliases[k] = k.replace('magn.', 'mag.')
+for k in _physical_constants_2006:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2018:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2022:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')        
+
+# CODATA 2018 and 2022: renamed and no longer exact; use as aliases
+_aliases['mag. constant'] = 'vacuum mag. permeability'
+_aliases['electric constant'] = 'vacuum electric permittivity'
+
+
+_extra_alias_keys = ['natural unit of velocity',
+                     'natural unit of action',
+                     'natural unit of action in eV s',
+                     'natural unit of mass',
+                     'natural unit of energy',
+                     'natural unit of energy in MeV',
+                     'natural unit of mom.um',
+                     'natural unit of mom.um in MeV/c',
+                     'natural unit of length',
+                     'natural unit of time']
+
+# finally, insert aliases for values
+for k, v in list(_aliases.items()):
+    if v in _current_constants or v in _extra_alias_keys:
+        physical_constants[k] = physical_constants[v]
+    else:
+        del _aliases[k]
+
+
+class ConstantWarning(DeprecationWarning):
+    """Accessing a constant no longer in current CODATA data set"""
+    pass
+
+
+def _check_obsolete(key: str) -> None:
+    if key in _obsolete_constants and key not in _aliases:
+        warnings.warn(f"Constant '{key}' is not in current {_current_codata} data set",
+                      ConstantWarning, stacklevel=3)
+
+
+def value(key: str) -> float:
+    """
+    Value in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    value : float
+        Value in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.value('elementary charge')
+    1.602176634e-19
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][0]
+
+
+def unit(key: str) -> str:
+    """
+    Unit in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    unit : Python string
+        Unit in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.unit('proton mass')
+    'kg'
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][1]
+
+
+def precision(key: str) -> float:
+    """
+    Relative precision in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    prec : float
+        Relative precision in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.precision('proton mass')
+    5.1e-37
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][2] / physical_constants[key][0]
+
+
+def find(sub: str | None = None, disp: bool = False) -> Any:
+    """
+    Return list of physical_constant keys containing a given string.
+
+    Parameters
+    ----------
+    sub : str
+        Sub-string to search keys for. By default, return all keys.
+    disp : bool
+        If True, print the keys that are found and return None.
+        Otherwise, return the list of keys without printing anything.
+
+    Returns
+    -------
+    keys : list or None
+        If `disp` is False, the list of keys is returned.
+        Otherwise, None is returned.
+
+    Examples
+    --------
+    >>> from scipy.constants import find, physical_constants
+
+    Which keys in the ``physical_constants`` dictionary contain 'boltzmann'?
+
+    >>> find('boltzmann')
+    ['Boltzmann constant',
+     'Boltzmann constant in Hz/K',
+     'Boltzmann constant in eV/K',
+     'Boltzmann constant in inverse meter per kelvin',
+     'Stefan-Boltzmann constant']
+
+    Get the constant called 'Boltzmann constant in Hz/K':
+
+    >>> physical_constants['Boltzmann constant in Hz/K']
+    (20836619120.0, 'Hz K^-1', 0.0)
+
+    Find constants with 'radius' in the key:
+
+    >>> find('radius')
+    ['Bohr radius',
+     'alpha particle rms charge radius',
+     'classical electron radius',
+     'deuteron rms charge radius',
+     'proton rms charge radius']
+    >>> physical_constants['classical electron radius']
+    (2.8179403262e-15, 'm', 1.3e-24)
+
+    """
+    if sub is None:
+        result = list(_current_constants.keys())
+    else:
+        result = [key for key in _current_constants
+                  if sub.lower() in key.lower()]
+
+    result.sort()
+    if disp:
+        for key in result:
+            print(key)
+        return
+    else:
+        return result
+
+# This is not used here, but it must be defined to pass
+# scipy/_lib/tests/test_public_api.py::test_private_but_present_deprecation
+c = value('speed of light in vacuum')
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/_constants.py b/venv/lib/python3.10/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3a098d5469bb7195202a638022b1120ec0969bd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/_constants.py
@@ -0,0 +1,366 @@
+"""
+Collection of physical constants and conversion factors.
+
+Most constants are in SI units, so you can do
+print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
+
+The list is not meant to be comprehensive, but just convenient for everyday use.
+"""
+
+import math as _math
+from typing import TYPE_CHECKING, Any
+
+from ._codata import value as _cd
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+from scipy._lib._array_api import array_namespace, _asarray
+
+
+"""
+BasSw 2006
+physical constants: imported from CODATA
+unit conversion: see e.g., NIST special publication 811
+Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
+Some constants exist in a few variants, which are marked with suffixes.
+The ones without any suffix should be the most common ones.
+"""
+
+__all__ = [
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
+    'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+# mathematical constants
+pi = _math.pi
+golden = golden_ratio = (1 + _math.sqrt(5)) / 2
+
+# SI prefixes
+quetta = 1e30
+ronna = 1e27
+yotta = 1e24
+zetta = 1e21
+exa = 1e18
+peta = 1e15
+tera = 1e12
+giga = 1e9
+mega = 1e6
+kilo = 1e3
+hecto = 1e2
+deka = 1e1
+deci = 1e-1
+centi = 1e-2
+milli = 1e-3
+micro = 1e-6
+nano = 1e-9
+pico = 1e-12
+femto = 1e-15
+atto = 1e-18
+zepto = 1e-21
+yocto = 1e-24
+ronto = 1e-27
+quecto = 1e-30
+
+# binary prefixes
+kibi = 2**10
+mebi = 2**20
+gibi = 2**30
+tebi = 2**40
+pebi = 2**50
+exbi = 2**60
+zebi = 2**70
+yobi = 2**80
+
+# physical constants
+c = speed_of_light = _cd('speed of light in vacuum')
+mu_0 = _cd('vacuum mag. permeability')
+epsilon_0 = _cd('vacuum electric permittivity')
+h = Planck = _cd('Planck constant')
+hbar = _cd('reduced Planck constant')
+G = gravitational_constant = _cd('Newtonian constant of gravitation')
+g = _cd('standard acceleration of gravity')
+e = elementary_charge = _cd('elementary charge')
+R = gas_constant = _cd('molar gas constant')
+alpha = fine_structure = _cd('fine-structure constant')
+N_A = Avogadro = _cd('Avogadro constant')
+k = Boltzmann = _cd('Boltzmann constant')
+sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
+Wien = _cd('Wien wavelength displacement law constant')
+Rydberg = _cd('Rydberg constant')
+
+# mass in kg
+gram = 1e-3
+metric_ton = 1e3
+grain = 64.79891e-6
+lb = pound = 7000 * grain  # avoirdupois
+blob = slinch = pound * g / 0.0254  # lbf*s**2/in (added in 1.0.0)
+slug = blob / 12  # lbf*s**2/foot (added in 1.0.0)
+oz = ounce = pound / 16
+stone = 14 * pound
+long_ton = 2240 * pound
+short_ton = 2000 * pound
+
+troy_ounce = 480 * grain  # only for metals / gems
+troy_pound = 12 * troy_ounce
+carat = 200e-6
+
+m_e = electron_mass = _cd('electron mass')
+m_p = proton_mass = _cd('proton mass')
+m_n = neutron_mass = _cd('neutron mass')
+m_u = u = atomic_mass = _cd('atomic mass constant')
+
+# angle in rad
+degree = pi / 180
+arcmin = arcminute = degree / 60
+arcsec = arcsecond = arcmin / 60
+
+# time in second
+minute = 60.0
+hour = 60 * minute
+day = 24 * hour
+week = 7 * day
+year = 365 * day
+Julian_year = 365.25 * day
+
+# length in meter
+inch = 0.0254
+foot = 12 * inch
+yard = 3 * foot
+mile = 1760 * yard
+mil = inch / 1000
+pt = point = inch / 72  # typography
+survey_foot = 1200.0 / 3937
+survey_mile = 5280 * survey_foot
+nautical_mile = 1852.0
+fermi = 1e-15
+angstrom = 1e-10
+micron = 1e-6
+au = astronomical_unit = 149597870700.0
+light_year = Julian_year * c
+parsec = au / arcsec
+
+# pressure in pascal
+atm = atmosphere = _cd('standard atmosphere')
+bar = 1e5
+torr = mmHg = atm / 760
+psi = pound * g / (inch * inch)
+
+# area in meter**2
+hectare = 1e4
+acre = 43560 * foot**2
+
+# volume in meter**3
+litre = liter = 1e-3
+gallon = gallon_US = 231 * inch**3  # US
+# pint = gallon_US / 8
+fluid_ounce = fluid_ounce_US = gallon_US / 128
+bbl = barrel = 42 * gallon_US  # for oil
+
+gallon_imp = 4.54609e-3  # UK
+fluid_ounce_imp = gallon_imp / 160
+
+# speed in meter per second
+kmh = 1e3 / hour
+mph = mile / hour
+# approx value of mach at 15 degrees in 1 atm. Is this a common value?
+mach = speed_of_sound = 340.5
+knot = nautical_mile / hour
+
+# temperature in kelvin
+zero_Celsius = 273.15
+degree_Fahrenheit = 1/1.8  # only for differences
+
+# energy in joule
+eV = electron_volt = elementary_charge  # * 1 Volt
+calorie = calorie_th = 4.184
+calorie_IT = 4.1868
+erg = 1e-7
+Btu_th = pound * degree_Fahrenheit * calorie_th / gram
+Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
+ton_TNT = 1e9 * calorie_th
+# Wh = watt_hour
+
+# power in watt
+hp = horsepower = 550 * foot * pound * g
+
+# force in newton
+dyn = dyne = 1e-5
+lbf = pound_force = pound * g
+kgf = kilogram_force = g  # * 1 kg
+
+# functions for conversions that are not linear
+
+
+def convert_temperature(
+    val: "npt.ArrayLike",
+    old_scale: str,
+    new_scale: str,
+) -> Any:
+    """
+    Convert from a temperature scale to another one among Celsius, Kelvin,
+    Fahrenheit, and Rankine scales.
+
+    Parameters
+    ----------
+    val : array_like
+        Value(s) of the temperature(s) to be converted expressed in the
+        original scale.
+    old_scale : str
+        Specifies as a string the original scale from which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+    new_scale : str
+        Specifies as a string the new scale to which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+
+    Returns
+    -------
+    res : float or array of floats
+        Value(s) of the converted temperature(s) expressed in the new scale.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    >>> from scipy.constants import convert_temperature
+    >>> import numpy as np
+    >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
+    array([ 233.15,  313.15])
+
+    """
+    xp = array_namespace(val)
+    _val = _asarray(val, xp=xp, subok=True)
+    # Convert from `old_scale` to Kelvin
+    if old_scale.lower() in ['celsius', 'c']:
+        tempo = _val + zero_Celsius
+    elif old_scale.lower() in ['kelvin', 'k']:
+        tempo = _val
+    elif old_scale.lower() in ['fahrenheit', 'f']:
+        tempo = (_val - 32) * 5 / 9 + zero_Celsius
+    elif old_scale.lower() in ['rankine', 'r']:
+        tempo = _val * 5 / 9
+    else:
+        raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
+                                   "are Celsius, Kelvin, Fahrenheit, and "
+                                   "Rankine")
+    # and from Kelvin to `new_scale`.
+    if new_scale.lower() in ['celsius', 'c']:
+        res = tempo - zero_Celsius
+    elif new_scale.lower() in ['kelvin', 'k']:
+        res = tempo
+    elif new_scale.lower() in ['fahrenheit', 'f']:
+        res = (tempo - zero_Celsius) * 9 / 5 + 32
+    elif new_scale.lower() in ['rankine', 'r']:
+        res = tempo * 9 / 5
+    else:
+        raise NotImplementedError(f"{new_scale=} is unsupported: supported "
+                                   "scales are 'Celsius', 'Kelvin', "
+                                   "'Fahrenheit', and 'Rankine'")
+
+    return res
+
+
+# optics
+
+
+def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
+    """
+    Convert wavelength to optical frequency
+
+    Parameters
+    ----------
+    lambda_ : array_like
+        Wavelength(s) to be converted.
+
+    Returns
+    -------
+    nu : float or array of floats
+        Equivalent optical frequency.
+
+    Notes
+    -----
+    Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import lambda2nu, speed_of_light
+    >>> import numpy as np
+    >>> lambda2nu(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(lambda_)
+    return c / _asarray(lambda_, xp=xp, subok=True)
+
+
+def nu2lambda(nu: "npt.ArrayLike") -> Any:
+    """
+    Convert optical frequency to wavelength.
+
+    Parameters
+    ----------
+    nu : array_like
+        Optical frequency to be converted.
+
+    Returns
+    -------
+    lambda : float or array of floats
+        Equivalent wavelength(s).
+
+    Notes
+    -----
+    Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import nu2lambda, speed_of_light
+    >>> import numpy as np
+    >>> nu2lambda(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(nu)
+    return c / _asarray(nu, xp=xp, subok=True)
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/codata.py b/venv/lib/python3.10/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..912e0bbf7c4f14d23ced4546b6704f7789996d97
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/codata.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.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'physical_constants', 'value', 'unit', 'precision', 'find',
+    'ConstantWarning', 'k', 'c',
+
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="codata",
+                                   private_modules=["_codata"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/constants.py b/venv/lib/python3.10/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..855901ba802881090b99b7e8972de741331c7ab9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/constants.py
@@ -0,0 +1,53 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'short_ton',
+    'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="constants",
+                                   private_modules=["_constants"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/constants/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ba5d9729330023e148f3e0867c9a231192c0d7d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18d8cf51b128f1be44a707bdacad1f4bbf640ca0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b40cbd290764a325de66a6b18e77b82a90e2314
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py b/venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..51b77c491344963c648fef90cdeaa5adac5d9a6f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py
@@ -0,0 +1,78 @@
+from scipy.constants import find, value, c, speed_of_light, precision
+from numpy.testing import assert_equal, assert_, assert_almost_equal
+import scipy.constants._codata as _cd
+from scipy import constants
+
+
+def test_find():
+    keys = find('weak mixing', disp=False)
+    assert_equal(keys, ['weak mixing angle'])
+
+    keys = find('qwertyuiop', disp=False)
+    assert_equal(keys, [])
+
+    keys = find('natural unit', disp=False)
+    assert_equal(keys, sorted(['natural unit of velocity',
+                                'natural unit of action',
+                                'natural unit of action in eV s',
+                                'natural unit of mass',
+                                'natural unit of energy',
+                                'natural unit of energy in MeV',
+                                'natural unit of momentum',
+                                'natural unit of momentum in MeV/c',
+                                'natural unit of length',
+                                'natural unit of time']))
+
+
+def test_basic_table_parse():
+    c_s = 'speed of light in vacuum'
+    assert_equal(value(c_s), c)
+    assert_equal(value(c_s), speed_of_light)
+
+
+def test_basic_lookup():
+    assert_equal('%d %s' % (_cd.value('speed of light in vacuum'),
+                            _cd.unit('speed of light in vacuum')),
+                 '299792458 m s^-1')
+
+
+def test_find_all():
+    assert_(len(find(disp=False)) > 300)
+
+
+def test_find_single():
+    assert_equal(find('Wien freq', disp=False)[0],
+                 'Wien frequency displacement law constant')
+
+
+def test_2002_vs_2006():
+    assert_almost_equal(value('magn. flux quantum'),
+                        value('mag. flux quantum'))
+
+
+def test_exact_values():
+    # Check that updating stored values with exact ones worked.
+    exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items())
+    replace = _cd.exact2018(exact)
+    for key, val in replace.items():
+        assert_equal(val, value(key))
+        assert precision(key) == 0
+
+
+def test_gh11341():
+    # gh-11341 noted that these three constants should exist (for backward
+    # compatibility) and should always have the same value:
+    a = constants.epsilon_0
+    b = constants.physical_constants['electric constant'][0]
+    c = constants.physical_constants['vacuum electric permittivity'][0]
+    assert a == b == c
+
+
+def test_gh14467():
+    # gh-14467 noted that some physical constants in CODATA are rounded
+    # to only ten significant figures even though they are supposed to be
+    # exact. Check that (at least) the case mentioned in the issue is resolved.
+    res = constants.physical_constants['Boltzmann constant in eV/K'][0]
+    ref = (constants.physical_constants['Boltzmann constant'][0]
+           / constants.physical_constants['elementary charge'][0])
+    assert res == ref
diff --git a/venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py b/venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b9dcd3b5355063cffb3b7a144937a95aab77955
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
@@ -0,0 +1,90 @@
+import pytest
+
+import scipy.constants as sc
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from numpy.testing import assert_allclose
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestConvertTemperature:
+    def test_convert_temperature(self, xp):
+        xp_assert_equal(sc.convert_temperature(xp.asarray(32.), 'f', 'Celsius'),
+                        xp.asarray(0.0))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]),
+                                               'celsius', 'Kelvin'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'kelvin', 'c'),
+                        xp.asarray([-273.15, -273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([32., 32.]), 'f', 'k'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([273.15, 273.15]),
+                                               'kelvin', 'F'),
+                        xp.asarray([32., 32.]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'C', 'fahrenheit'),
+                        xp.asarray([32., 32.]))
+        xp_assert_close(sc.convert_temperature(xp.asarray([0., 0.], dtype=xp.float64),
+                                               'c', 'r'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'Rankine', 'C'),
+                        xp.asarray([0., 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'r', 'F'),
+                        xp.asarray([32., 32.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([32., 32.], dtype=xp.float64),
+                                               'fahrenheit', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([273.15, 273.15],
+                                                        dtype=xp.float64),
+                                               'K', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 0.],
+                                                          dtype=xp.float64),
+                                               'rankine', 'kelvin'),
+                        xp.asarray([273.15, 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_convert_temperature_array_like(self):
+        assert_allclose(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
+                        [273.15, 0.], rtol=0., atol=1e-13)
+
+
+    @skip_xp_backends(np_only=True, reason='Python int input uses NumPy backend')
+    def test_convert_temperature_errors(self, xp):
+        with pytest.raises(NotImplementedError, match="old_scale="):
+            sc.convert_temperature(1, old_scale="cheddar", new_scale="kelvin")
+        with pytest.raises(NotImplementedError, match="new_scale="):
+            sc.convert_temperature(1, old_scale="kelvin", new_scale="brie")
+
+
+class TestLambdaToNu:
+    def test_lambda_to_nu(self, xp):
+        xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_lambda_to_nu_array_like(self, xp):
+        assert_allclose(sc.lambda2nu([sc.speed_of_light, 1]),
+                        [1, sc.speed_of_light])
+
+
+class TestNuToLambda:
+    def test_nu_to_lambda(self, xp):
+        xp_assert_equal(sc.nu2lambda(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_nu_to_lambda_array_like(self, xp):
+        assert_allclose(sc.nu2lambda([sc.speed_of_light, 1]),
+                        [1, sc.speed_of_light])
+
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/__init__.py b/venv/lib/python3.10/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdd4ffebec4c57f6d399a0f76df2b66056f0b225
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/datasets/__init__.py
@@ -0,0 +1,90 @@
+"""
+================================
+Datasets (:mod:`scipy.datasets`)
+================================
+
+.. currentmodule:: scipy.datasets
+
+Dataset Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   ascent
+   face
+   electrocardiogram
+
+Utility Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   download_all    -- Download all the dataset files to specified path.
+   clear_cache     -- Clear cached dataset directory.
+
+
+Usage of Datasets
+=================
+
+SciPy dataset methods can be simply called as follows: ``'()'``
+This downloads the dataset files over the network once, and saves the cache,
+before returning a `numpy.ndarray` object representing the dataset.
+
+Note that the return data structure and data type might be different for
+different dataset methods. For a more detailed example on usage, please look
+into the particular dataset method documentation above.
+
+
+How dataset retrieval and storage works
+=======================================
+
+SciPy dataset files are stored within individual GitHub repositories under the
+SciPy GitHub organization, following a naming convention as
+``'dataset-'``, for example `scipy.datasets.face` files live at
+https://github.com/scipy/dataset-face.  The `scipy.datasets` submodule utilizes
+and depends on `Pooch `_, a Python
+package built to simplify fetching data files. Pooch uses these repos to
+retrieve the respective dataset files when calling the dataset function.
+
+A registry of all the datasets, essentially a mapping of filenames with their
+SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
+the downloads on function call. After downloading the dataset once, the files
+are saved in the system cache directory under ``'scipy-data'``.
+
+Dataset cache locations may vary on different platforms.
+
+For macOS::
+
+    '~/Library/Caches/scipy-data'
+
+For Linux and other Unix-like platforms::
+
+    '~/.cache/scipy-data'  # or the value of the XDG_CACHE_HOME env var, if defined
+
+For Windows::
+
+    'C:\\Users\\\\AppData\\Local\\\\scipy-data\\Cache'
+
+
+In environments with constrained network connectivity for various security
+reasons or on systems without continuous internet connections, one may manually
+load the cache of the datasets by placing the contents of the dataset repo in
+the above mentioned cache directory to avoid fetching dataset errors without
+the internet connectivity.
+
+"""
+
+
+from ._fetchers import face, ascent, electrocardiogram
+from ._download_all import download_all
+from ._utils import clear_cache
+
+__all__ = ['ascent', 'electrocardiogram', 'face',
+           'download_all', 'clear_cache']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c4905f9a021646dd3b6c5409015e3bc35ed8d0b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_download_all.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_download_all.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7c2675c500e9fbdd26680abdd144c5427ada7bb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_download_all.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..688de48db25fbe7e54a9a56a23c3ae523da5e392
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_registry.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_registry.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f69bc1735a79123d09c9a5e08f644c85526dae5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_registry.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb939b5769130d85a6c65838a01b9deb689a6d9c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py b/venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..255fdcaf22950848f458a7ed9ada183e0a2e630e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py
@@ -0,0 +1,57 @@
+"""
+Platform independent script to download all the
+`scipy.datasets` module data files.
+This doesn't require a full scipy build.
+
+Run: python _download_all.py 
+"""
+
+import argparse
+try:
+    import pooch
+except ImportError:
+    pooch = None
+
+
+if __package__ is None or __package__ == '':
+    # Running as python script, use absolute import
+    import _registry  # type: ignore
+else:
+    # Running as python module, use relative import
+    from . import _registry
+
+
+def download_all(path=None):
+    """
+    Utility method to download all the dataset files
+    for `scipy.datasets` module.
+
+    Parameters
+    ----------
+    path : str, optional
+        Directory path to download all the dataset files.
+        If None, default to the system cache_dir detected by pooch.
+    """
+    if pooch is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    if path is None:
+        path = pooch.os_cache('scipy-data')
+    for dataset_name, dataset_hash in _registry.registry.items():
+        pooch.retrieve(url=_registry.registry_urls[dataset_name],
+                       known_hash=dataset_hash,
+                       fname=dataset_name, path=path)
+
+
+def main():
+    parser = argparse.ArgumentParser(description='Download SciPy data files.')
+    parser.add_argument("path", nargs='?', type=str,
+                        default=pooch.os_cache('scipy-data'),
+                        help="Directory path to download all the data files.")
+    args = parser.parse_args()
+    download_all(args.path)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py b/venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..57bb2fa6a12e753eb07a1f359ac04a29bd5c77e5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py
@@ -0,0 +1,219 @@
+from numpy import array, frombuffer, load
+from ._registry import registry, registry_urls
+
+try:
+    import pooch
+except ImportError:
+    pooch = None
+    data_fetcher = None
+else:
+    data_fetcher = pooch.create(
+        # Use the default cache folder for the operating system
+        # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
+        # select an appropriate directory for the cache on each platform.
+        path=pooch.os_cache("scipy-data"),
+
+        # The remote data is on Github
+        # base_url is a required param, even though we override this
+        # using individual urls in the registry.
+        base_url="https://github.com/scipy/",
+        registry=registry,
+        urls=registry_urls
+    )
+
+
+def fetch_data(dataset_name, data_fetcher=data_fetcher):
+    if data_fetcher is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    # The "fetch" method returns the full path to the downloaded data file.
+    return data_fetcher.fetch(dataset_name)
+
+
+def ascent():
+    """
+    Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
+    use in demos.
+
+    The image is derived from
+    https://pixnio.com/people/accent-to-the-top
+
+    Parameters
+    ----------
+    None
+
+    Returns
+    -------
+    ascent : ndarray
+       convenient image to use for testing and demonstration
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> ascent = scipy.datasets.ascent()
+    >>> ascent.shape
+    (512, 512)
+    >>> ascent.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(ascent)
+    >>> plt.show()
+
+    """
+    import pickle
+
+    # The file will be downloaded automatically the first time this is run,
+    # returning the path to the downloaded file. Afterwards, Pooch finds
+    # it in the local cache and doesn't repeat the download.
+    fname = fetch_data("ascent.dat")
+    # Now we just need to load it with our standard Python tools.
+    with open(fname, 'rb') as f:
+        ascent = array(pickle.load(f))
+    return ascent
+
+
+def electrocardiogram():
+    """
+    Load an electrocardiogram as an example for a 1-D signal.
+
+    The returned signal is a 5 minute long electrocardiogram (ECG), a medical
+    recording of the heart's electrical activity, sampled at 360 Hz.
+
+    Returns
+    -------
+    ecg : ndarray
+        The electrocardiogram in millivolt (mV) sampled at 360 Hz.
+
+    Notes
+    -----
+    The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
+    (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
+    PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
+    heartbeats as well as pathological changes.
+
+    .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
+           IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
+           (PMID: 11446209); :doi:`10.13026/C2F305`
+    .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
+           Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
+           PhysioToolkit, and PhysioNet: Components of a New Research Resource
+           for Complex Physiologic Signals. Circulation 101(23):e215-e220;
+           :doi:`10.1161/01.CIR.101.23.e215`
+
+    Examples
+    --------
+    >>> from scipy.datasets import electrocardiogram
+    >>> ecg = electrocardiogram()
+    >>> ecg
+    array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
+    >>> ecg.shape, ecg.mean(), ecg.std()
+    ((108000,), -0.16510875, 0.5992473991177294)
+
+    As stated the signal features several areas with a different morphology.
+    E.g., the first few seconds show the electrical activity of a heart in
+    normal sinus rhythm as seen below.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fs = 360
+    >>> time = np.arange(ecg.size) / fs
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(9, 10.2)
+    >>> plt.ylim(-1, 1.5)
+    >>> plt.show()
+
+    After second 16, however, the first premature ventricular contractions,
+    also called extrasystoles, appear. These have a different morphology
+    compared to typical heartbeats. The difference can easily be observed
+    in the following plot.
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(46.5, 50)
+    >>> plt.ylim(-2, 1.5)
+    >>> plt.show()
+
+    At several points large artifacts disturb the recording, e.g.:
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(207, 215)
+    >>> plt.ylim(-2, 3.5)
+    >>> plt.show()
+
+    Finally, examining the power spectrum reveals that most of the biosignal is
+    made up of lower frequencies. At 60 Hz the noise induced by the mains
+    electricity can be clearly observed.
+
+    >>> from scipy.signal import welch
+    >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
+    >>> plt.semilogy(f, Pxx)
+    >>> plt.xlabel("Frequency in Hz")
+    >>> plt.ylabel("Power spectrum of the ECG in mV**2")
+    >>> plt.xlim(f[[0, -1]])
+    >>> plt.show()
+    """
+    fname = fetch_data("ecg.dat")
+    with load(fname) as file:
+        ecg = file["ecg"].astype(int)  # np.uint16 -> int
+    # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
+    ecg = (ecg - 1024) / 200.0
+    return ecg
+
+
+def face(gray=False):
+    """
+    Get a 1024 x 768, color image of a raccoon face.
+
+    The image is derived from
+    https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
+
+    Parameters
+    ----------
+    gray : bool, optional
+        If True return 8-bit grey-scale image, otherwise return a color image
+
+    Returns
+    -------
+    face : ndarray
+        image of a raccoon face
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> face = scipy.datasets.face()
+    >>> face.shape
+    (768, 1024, 3)
+    >>> face.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(face)
+    >>> plt.show()
+
+    """
+    import bz2
+    fname = fetch_data("face.dat")
+    with open(fname, 'rb') as f:
+        rawdata = f.read()
+    face_data = bz2.decompress(rawdata)
+    face = frombuffer(face_data, dtype='uint8')
+    face.shape = (768, 1024, 3)
+    if gray is True:
+        face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
+                0.07 * face[:, :, 2]).astype('uint8')
+    return face
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/_registry.py b/venv/lib/python3.10/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..969384ad9843159e766100bfa9755aed8102dd09
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/datasets/_registry.py
@@ -0,0 +1,26 @@
+##########################################################################
+# This file serves as the dataset registry for SciPy Datasets SubModule.
+##########################################################################
+
+
+# To generate the SHA256 hash, use the command
+# openssl sha256 
+registry = {
+    "ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
+    "ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
+    "face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
+}
+
+registry_urls = {
+    "ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
+    "ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
+    "face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
+}
+
+# dataset method mapping with their associated filenames
+#  : ["filename1", "filename2", ...]
+method_files_map = {
+    "ascent": ["ascent.dat"],
+    "electrocardiogram": ["ecg.dat"],
+    "face": ["face.dat"]
+}
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/_utils.py b/venv/lib/python3.10/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f644f8797d6e3256a16ec2c509eec725c726300
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/datasets/_utils.py
@@ -0,0 +1,81 @@
+import os
+import shutil
+from ._registry import method_files_map
+
+try:
+    import platformdirs
+except ImportError:
+    platformdirs = None  # type: ignore[assignment]
+
+
+def _clear_cache(datasets, cache_dir=None, method_map=None):
+    if method_map is None:
+        # Use SciPy Datasets method map
+        method_map = method_files_map
+    if cache_dir is None:
+        # Use default cache_dir path
+        if platformdirs is None:
+            # platformdirs is pooch dependency
+            raise ImportError("Missing optional dependency 'pooch' required "
+                              "for scipy.datasets module. Please use pip or "
+                              "conda to install 'pooch'.")
+        cache_dir = platformdirs.user_cache_dir("scipy-data")
+
+    if not os.path.exists(cache_dir):
+        print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
+        return
+
+    if datasets is None:
+        print(f"Cleaning the cache directory {cache_dir}!")
+        shutil.rmtree(cache_dir)
+    else:
+        if not isinstance(datasets, (list, tuple)):
+            # single dataset method passed should be converted to list
+            datasets = [datasets, ]
+        for dataset in datasets:
+            assert callable(dataset)
+            dataset_name = dataset.__name__  # Name of the dataset method
+            if dataset_name not in method_map:
+                raise ValueError(f"Dataset method {dataset_name} doesn't "
+                                 "exist. Please check if the passed dataset "
+                                 "is a subset of the following dataset "
+                                 f"methods: {list(method_map.keys())}")
+
+            data_files = method_map[dataset_name]
+            data_filepaths = [os.path.join(cache_dir, file)
+                              for file in data_files]
+            for data_filepath in data_filepaths:
+                if os.path.exists(data_filepath):
+                    print("Cleaning the file "
+                          f"{os.path.split(data_filepath)[1]} "
+                          f"for dataset {dataset_name}")
+                    os.remove(data_filepath)
+                else:
+                    print(f"Path {data_filepath} doesn't exist. "
+                          "Nothing to clear.")
+
+
+def clear_cache(datasets=None):
+    """
+    Cleans the scipy datasets cache directory.
+
+    If a scipy.datasets method or a list/tuple of the same is
+    provided, then clear_cache removes all the data files
+    associated to the passed dataset method callable(s).
+
+    By default, it removes all the cached data files.
+
+    Parameters
+    ----------
+    datasets : callable or list/tuple of callable or None
+
+    Examples
+    --------
+    >>> from scipy import datasets
+    >>> ascent_array = datasets.ascent()
+    >>> ascent_array.shape
+    (512, 512)
+    >>> datasets.clear_cache([datasets.ascent])
+    Cleaning the file ascent.dat for dataset ascent
+    """
+    _clear_cache(datasets)
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2060b3d7518565870af2d4d15c79b1fb0925d039
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..104651bea5bc9b89e7216e5c2dd47a7a2fb7cc96
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py b/venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..243176bd89b7b6f16406d66293d1872ac2712252
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py
@@ -0,0 +1,128 @@
+from scipy.datasets._registry import registry
+from scipy.datasets._fetchers import data_fetcher
+from scipy.datasets._utils import _clear_cache
+from scipy.datasets import ascent, face, electrocardiogram, download_all
+from numpy.testing import assert_equal, assert_almost_equal
+import os
+from threading import get_ident
+import pytest
+
+try:
+    import pooch
+except ImportError:
+    raise ImportError("Missing optional dependency 'pooch' required "
+                      "for scipy.datasets module. Please use pip or "
+                      "conda to install 'pooch'.")
+
+
+data_dir = data_fetcher.path  # type: ignore
+
+
+def _has_hash(path, expected_hash):
+    """Check if the provided path has the expected hash."""
+    if not os.path.exists(path):
+        return False
+    return pooch.file_hash(path) == expected_hash
+
+
+class TestDatasets:
+
+    @pytest.fixture(scope='module', autouse=True)
+    def test_download_all(self):
+        # This fixture requires INTERNET CONNECTION
+
+        # test_setup phase
+        download_all()
+
+        yield
+
+    @pytest.mark.fail_slow(10)
+    def test_existence_all(self):
+        assert len(os.listdir(data_dir)) >= len(registry)
+
+    def test_ascent(self):
+        assert_equal(ascent().shape, (512, 512))
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "ascent.dat"),
+                         registry["ascent.dat"])
+
+    def test_face(self):
+        assert_equal(face().shape, (768, 1024, 3))
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "face.dat"),
+                         registry["face.dat"])
+
+    def test_electrocardiogram(self):
+        # Test shape, dtype and stats of signal
+        ecg = electrocardiogram()
+        assert_equal(ecg.dtype, float)
+        assert_equal(ecg.shape, (108000,))
+        assert_almost_equal(ecg.mean(), -0.16510875)
+        assert_almost_equal(ecg.std(), 0.5992473991177294)
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "ecg.dat"),
+                         registry["ecg.dat"])
+
+
+def test_clear_cache(tmp_path):
+    # Note: `tmp_path` is a pytest fixture, it handles cleanup
+    thread_basepath = tmp_path / str(get_ident())
+    thread_basepath.mkdir()
+
+    dummy_basepath = thread_basepath / "dummy_cache_dir"
+    dummy_basepath.mkdir()
+
+    # Create three dummy dataset files for dummy dataset methods
+    dummy_method_map = {}
+    for i in range(4):
+        dummy_method_map[f"data{i}"] = [f"data{i}.dat"]
+        data_filepath = dummy_basepath / f"data{i}.dat"
+        data_filepath.write_text("")
+
+    # clear files associated to single dataset method data0
+    # also test callable argument instead of list of callables
+    def data0():
+        pass
+    _clear_cache(datasets=data0, cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data0.dat")
+
+    # clear files associated to multiple dataset methods "data3" and "data4"
+    def data1():
+        pass
+
+    def data2():
+        pass
+    _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data1.dat")
+    assert not os.path.exists(dummy_basepath/"data2.dat")
+
+    # clear multiple dataset files "data3_0.dat" and "data3_1.dat"
+    # associated with dataset method "data3"
+    def data4():
+        pass
+    # create files
+    (dummy_basepath / "data4_0.dat").write_text("")
+    (dummy_basepath / "data4_1.dat").write_text("")
+
+    dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"]
+    _clear_cache(datasets=[data4], cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data4_0.dat")
+    assert not os.path.exists(dummy_basepath/"data4_1.dat")
+
+    # wrong dataset method should raise ValueError since it
+    # doesn't exist in the dummy_method_map
+    def data5():
+        pass
+    with pytest.raises(ValueError):
+        _clear_cache(datasets=[data5], cache_dir=dummy_basepath,
+                     method_map=dummy_method_map)
+
+    # remove all dataset cache
+    _clear_cache(datasets=None, cache_dir=dummy_basepath)
+    assert not os.path.exists(dummy_basepath)
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py b/venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3a7ccc4b33f27dbae7958641a89106cf9580326
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py
@@ -0,0 +1,27 @@
+"""
+==============================================================
+Finite Difference Differentiation (:mod:`scipy.differentiate`)
+==============================================================
+
+.. currentmodule:: scipy.differentiate
+
+SciPy ``differentiate`` provides functions for performing finite difference
+numerical differentiation of black-box functions.
+
+.. autosummary::
+   :toctree: generated/
+
+   derivative
+   jacobian
+   hessian
+
+"""
+
+
+from ._differentiate import *
+
+__all__ = ['derivative', 'jacobian', 'hessian']
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/differentiate/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3946495947e8fb34dbebfa2030f026458d8ec8dc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/differentiate/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/__pycache__/_differentiate.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/differentiate/__pycache__/_differentiate.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..861c3ded2ee0f80b80caf6893b49c1ab656eaed0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/differentiate/__pycache__/_differentiate.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py b/venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e104a071055161b69f62cec317e8a07b4466653
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py
@@ -0,0 +1,1129 @@
+# mypy: disable-error-code="attr-defined"
+import warnings
+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_sign, xp_copy, xp_take_along_axis
+
+_EERRORINCREASE = -1  # used in derivative
+
+def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
+                   step_factor, step_direction, preserve_shape, callback):
+    # Input validation for `derivative`
+    xp = array_namespace(x)
+
+    if not callable(f):
+        raise ValueError('`f` must be callable.')
+
+    if not np.iterable(args):
+        args = (args,)
+
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    # tolerances are floats, not arrays; OK to use NumPy
+    message = 'Tolerances and step parameters must be non-negative scalars.'
+    tols = np.asarray([atol if atol is not None else 1,
+                       rtol if rtol is not None else 1,
+                       step_factor])
+    if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
+            or np.any(np.isnan(tols)) or tols.shape != (3,)):
+        raise ValueError(message)
+    step_factor = float(tols[2])
+
+    maxiter_int = int(maxiter)
+    if maxiter != maxiter_int or maxiter <= 0:
+        raise ValueError('`maxiter` must be a positive integer.')
+
+    order_int = int(order)
+    if order_int != order or order <= 0:
+        raise ValueError('`order` must be a positive integer.')
+
+    step_direction = xp.asarray(step_direction)
+    initial_step = xp.asarray(initial_step)
+    temp = xp.broadcast_arrays(x, step_direction, initial_step)
+    x, step_direction, initial_step = temp
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step,
+            step_factor, step_direction, preserve_shape, callback)
+
+
+def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
+               order=8, initial_step=0.5, step_factor=2.0,
+               step_direction=0, preserve_shape=False, callback=None):
+    """Evaluate the derivative of a elementwise, real scalar function numerically.
+
+    For each element of the output of `f`, `derivative` approximates the first
+    derivative of `f` at the corresponding element of `x` using finite difference
+    differentiation.
+
+    This function works elementwise when `x`, `step_direction`, and `args` contain
+    (broadcastable) arrays.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose derivative is desired. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable with
+        ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
+        must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
+        ``xi`` or the arrays in ``argsi``.
+    x : float array_like
+        Abscissae at which to evaluate the derivative. Must be broadcastable with
+        `args` and `step_direction`.
+    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``.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    step_direction : integer array_like
+        An array representing the direction of the finite difference steps (for
+        use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and all `args`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `x` and all elements of `args` (which is conceptually
+        distinct from ``xi` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+    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 `derivative` (but containing the current
+        iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `derivative` 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 error estimate increased, so iteration was terminated.
+            - ``-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).
+
+        df : float array
+            The derivative of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the derivative and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+        x : float array
+            The value at which the derivative of `f` was evaluated
+            (after broadcasting with `args` and `step_direction`).
+
+    See Also
+    --------
+    jacobian, hessian
+
+    Notes
+    -----
+    The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
+    DERIVEST [3]_, but the implementation follows the theory of Taylor series
+    more straightforwardly (and arguably naively so).
+    In the first iteration, the derivative is estimated using a finite
+    difference formula of order `order` with maximum step size `initial_step`.
+    Each subsequent iteration, the maximum step size is reduced by
+    `step_factor`, and the derivative is estimated again until a termination
+    condition is reached. The error estimate is the magnitude of the difference
+    between the current derivative approximation and that of the previous
+    iteration.
+
+    The stencils of the finite difference formulae are designed such that
+    abscissae are "nested": after `f` is evaluated at ``order + 1``
+    points in the first iteration, `f` is evaluated at only two new points
+    in each subsequent iteration; ``order - 1`` previously evaluated function
+    values required by the finite difference formula are reused, and two
+    function values (evaluations at the points furthest from `x`) are unused.
+
+    Step sizes are absolute. When the step size is small relative to the
+    magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
+    default initial step size of ``0.5`` cannot be resolved. Accordingly,
+    consider using larger initial step sizes for large magnitudes of `x`.
+
+    The default tolerances are challenging to satisfy at points where the
+    true derivative is exactly zero. If the derivative may be exactly zero,
+    consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
+    improve convergence.
+
+    References
+    ----------
+    .. [1] Hans Dembinski (@HDembinski). jacobi.
+           https://github.com/HDembinski/jacobi
+    .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
+           https://numdifftools.readthedocs.io/en/latest/
+    .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
+           https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
+    .. [4] Numerical Differentition. Wikipedia.
+           https://en.wikipedia.org/wiki/Numerical_differentiation
+
+    Examples
+    --------
+    Evaluate the derivative of ``np.exp`` at several points ``x``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import derivative
+    >>> f = np.exp
+    >>> df = np.exp  # true derivative
+    >>> x = np.linspace(1, 2, 5)
+    >>> res = derivative(f, x)
+    >>> res.df  # approximation of the derivative
+    array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
+    >>> res.error  # estimate of the error
+    array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
+           1.94262384e-11])
+    >>> abs(res.df - df(x))  # true error
+    array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
+           6.92779167e-14])
+
+    Show the convergence of the approximation as the step size is reduced.
+    Each iteration, the step size is reduced by `step_factor`, so for
+    sufficiently small initial step, each iteration reduces the error by a
+    factor of ``1/step_factor**order`` until finite precision arithmetic
+    inhibits further improvement.
+
+    >>> import matplotlib.pyplot as plt
+    >>> iter = list(range(1, 12))  # maximum iterations
+    >>> hfac = 2  # step size reduction per iteration
+    >>> hdir = [-1, 0, 1]  # compare left-, central-, and right- steps
+    >>> order = 4  # order of differentiation formula
+    >>> x = 1
+    >>> ref = df(x)
+    >>> errors = []  # true error
+    >>> for i in iter:
+    ...     res = derivative(f, x, maxiter=i, step_factor=hfac,
+    ...                      step_direction=hdir, order=order,
+    ...                      # prevent early termination
+    ...                      tolerances=dict(atol=0, rtol=0))
+    ...     errors.append(abs(res.df - ref))
+    >>> errors = np.array(errors)
+    >>> plt.semilogy(iter, errors[:, 0], label='left differences')
+    >>> plt.semilogy(iter, errors[:, 1], label='central differences')
+    >>> plt.semilogy(iter, errors[:, 2], label='right differences')
+    >>> plt.xlabel('iteration')
+    >>> plt.ylabel('error')
+    >>> plt.legend()
+    >>> plt.show()
+    >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
+    (0.06215223140159822, 0.0625)
+
+    The implementation is vectorized over `x`, `step_direction`, and `args`.
+    The function is evaluated once before the first iteration to perform input
+    validation and standardization, and once per iteration thereafter.
+
+    >>> def f(x, p):
+    ...     f.nit += 1
+    ...     return x**p
+    >>> f.nit = 0
+    >>> def df(x, p):
+    ...     return p*x**(p-1)
+    >>> x = np.arange(1, 5)
+    >>> p = np.arange(1, 6).reshape((-1, 1))
+    >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
+    >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
+    >>> np.allclose(res.df, df(x, p))
+    True
+    >>> res.df.shape
+    (3, 5, 4)
+    >>> f.nit
+    2
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 5, 10, 20]
+    >>> res = derivative(f, 0, args=(c,))
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `derivative` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the function's derivative change
+    faster, so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([11, 13, 15, 17], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    function at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    function at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function evaluate the function at two more
+    abscissae, increasing the effective order of the approximation by two.
+    However, in later function evaluations, the function is evaluated at
+    fewer frequencies because the corresponding derivative has already
+    converged to the required tolerance. This saves function evaluations to
+    improve performance, but it requires the function to accept arguments of
+    any shape.
+
+    "Vector-valued" functions are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
+
+    This integrand is not compatible with `derivative` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
+    >>>
+    >>> x = np.zeros(4)
+    >>> res = derivative(f, x, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
+
+    Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
+    function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
+    and this is what we observe.
+
+    """
+    # TODO (followup):
+    #  - investigate behavior at saddle points
+    #  - multivariate functions?
+    #  - relative steps?
+    #  - show example of `np.vectorize`
+
+    res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
+                            step_factor, step_direction, preserve_shape, callback)
+    (func, x, args, atol, rtol, maxiter, order,
+     h0, fac, hdir, preserve_shape, callback) = res
+
+    # Initialization
+    # Since f(x) (no step) is not needed for central differences, it may be
+    # possible to eliminate this function evaluation. However, it's useful for
+    # input validation and standardization, and everything else is designed to
+    # reduce function calls, so let's keep it simple.
+    temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape)
+    func, xs, fs, args, shape, dtype, xp = temp
+
+    finfo = xp.finfo(dtype)
+    atol = finfo.smallest_normal if atol is None else atol
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `hessian`
+
+    x, f = xs[0], fs[0]
+    df = xp.full_like(f, xp.nan)
+
+    # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
+    # it's simpler to do it here than to generalize `_elementwise_algo_init` further.
+    # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
+    # that `hdir` can be broadcasted to the final shape. Same with `h0`.
+    hdir = xp.broadcast_to(hdir, shape)
+    hdir = xp.reshape(hdir, (-1,))
+    hdir = xp.astype(xp_sign(hdir), dtype)
+    h0 = xp.broadcast_to(h0, shape)
+    h0 = xp.reshape(h0, (-1,))
+    h0 = xp.astype(h0, dtype)
+    h0[h0 <= 0] = xp.asarray(xp.nan, dtype=dtype)
+
+    status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32)  # in progress
+    nit, nfev = 0, 1  # one function evaluations performed above
+    # Boolean indices of left, central, right, and (all) one-sided steps
+    il = hdir < 0
+    ic = hdir == 0
+    ir = hdir > 0
+    io = il | ir
+
+    # Most of these attributes are reasonably obvious, but:
+    # - `fs` holds all the function values of all active `x`. The zeroth
+    #   axis corresponds with active points `x`, the first axis corresponds
+    #   with the different steps (in the order described in
+    #   `_derivative_weights`).
+    # - `terms` (which could probably use a better name) is half the `order`,
+    #   which is always even.
+    work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
+                       df_last=xp.nan, error_last=xp.nan, fac=fac,
+                       atol=atol, rtol=rtol, nit=nit, nfev=nfev,
+                       status=status, dtype=dtype, terms=(order+1)//2,
+                       hdir=hdir, il=il, ic=ic, ir=ir, io=io,
+                       # Store the weights in an object so they can't get compressed
+                       # Using RichResult to allow dot notation, but a dict would work
+                       diff_state=_RichResult(central=[], right=[], fac=None))
+
+    # This is the correspondence between terms in the `work` object and the
+    # final result. In this case, the mapping is trivial. Note that `success`
+    # is prepended automatically.
+    res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
+                      ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
+
+    def pre_func_eval(work):
+        """Determine the abscissae at which the function needs to be evaluated.
+
+        See `_derivative_weights` for a description of the stencil (pattern
+        of the abscissae).
+
+        In the first iteration, there is only one stored function value in
+        `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
+        subsequent iterations, we evaluate at two new points. Note that
+        `work.x` is always flattened into a 1D array after broadcasting with
+        all `args`, so we add a new axis at the end and evaluate all point
+        in one call to the function.
+
+        For improvement:
+        - Consider measuring the step size actually taken, since ``(x + h) - x``
+          is not identically equal to `h` with floating point arithmetic.
+        - Adjust the step size automatically if `x` is too big to resolve the
+          step.
+        - We could probably save some work if there are no central difference
+          steps or no one-sided steps.
+        """
+        n = work.terms  # half the order
+        h = work.h[:, xp.newaxis]  # step size
+        c = work.fac  # step reduction factor
+        d = c**0.5  # square root of step reduction factor (one-sided stencil)
+        # Note - no need to be careful about dtypes until we allocate `x_eval`
+
+        if work.nit == 0:
+            hc = h / c**xp.arange(n, dtype=work.dtype)
+            hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
+        else:
+            hc = xp.concat((-h, h), axis=-1) / c**(n-1)
+
+        if work.nit == 0:
+            hr = h / d**xp.arange(2*n, dtype=work.dtype)
+        else:
+            hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
+
+        n_new = 2*n if work.nit == 0 else 2  # number of new abscissae
+        x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
+        il, ic, ir = work.il, work.ic, work.ir
+        x_eval[ir] = work.x[ir][:, xp.newaxis] + hr[ir]
+        x_eval[ic] = work.x[ic][:, xp.newaxis] + hc[ic]
+        x_eval[il] = work.x[il][:, xp.newaxis] - hr[il]
+        return x_eval
+
+    def post_func_eval(x, f, work):
+        """ Estimate the derivative and error from the function evaluations
+
+        As in `pre_func_eval`: in the first iteration, there is only one stored
+        function value in `work.fs`, `f(x)`, so we need to add the `order` new
+        points. In subsequent iterations, we add two new points. The tricky
+        part is getting the order to match that of the weights, which is
+        described in `_derivative_weights`.
+
+        For improvement:
+        - Change the order of the weights (and steps in `pre_func_eval`) to
+          simplify `work_fc` concatenation and eliminate `fc` concatenation.
+        - It would be simple to do one-step Richardson extrapolation with `df`
+          and `df_last` to increase the order of the estimate and/or improve
+          the error estimate.
+        - Process the function evaluations in a more numerically favorable
+          way. For instance, combining the pairs of central difference evals
+          into a second-order approximation and using Richardson extrapolation
+          to produce a higher order approximation seemed to retain accuracy up
+          to very high order.
+        - Alternatively, we could use `polyfit` like Jacobi. An advantage of
+          fitting polynomial to more points than necessary is improved noise
+          tolerance.
+        """
+        n = work.terms
+        n_new = n if work.nit == 0 else 1
+        il, ic, io = work.il, work.ic, work.io
+
+        # Central difference
+        # `work_fc` is *all* the points at which the function has been evaluated
+        # `fc` is the points we're using *this iteration* to produce the estimate
+        work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
+        work_fc = xp.concat(work_fc, axis=-1)
+        if work.nit == 0:
+            fc = work_fc
+        else:
+            fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
+            fc = xp.concat(fc, axis=-1)
+
+        # One-sided difference
+        work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
+        if work.nit == 0:
+            fo = work_fo
+        else:
+            fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
+
+        work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
+        work.fs[ic] = work_fc
+        work.fs[io] = work_fo
+
+        wc, wo = _derivative_weights(work, n, xp)
+        work.df_last = xp.asarray(work.df, copy=True)
+        work.df[ic] = fc @ wc / work.h[ic]
+        work.df[io] = fo @ wo / work.h[io]
+        work.df[il] *= -1
+
+        work.h /= work.fac
+        work.error_last = work.error
+        # Simple error estimate - the difference in derivative estimates between
+        # this iteration and the last. This is typically conservative because if
+        # convergence has begin, the true error is much closer to the difference
+        # between the current estimate and the *next* error estimate. However,
+        # we could use Richarson extrapolation to produce an error estimate that
+        # is one order higher, and take the difference between that and
+        # `work.df` (which would just be constant factor that depends on `fac`.)
+        work.error = xp.abs(work.df - work.df_last)
+
+    def check_termination(work):
+        """Terminate due to convergence, non-finite values, or error increase"""
+        stop = xp.astype(xp.zeros_like(work.df), xp.bool)
+
+        i = work.error < work.atol + work.rtol*abs(work.df)
+        work.status[i] = eim._ECONVERGED
+        stop[i] = True
+
+        if work.nit > 0:
+            i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
+            work.df[i], work.status[i] = xp.nan, eim._EVALUEERR
+            stop[i] = True
+
+        # With infinite precision, there is a step size below which
+        # all smaller step sizes will reduce the error. But in floating point
+        # arithmetic, catastrophic cancellation will begin to cause the error
+        # to increase again. This heuristic tries to avoid step sizes that are
+        # too small. There may be more theoretically sound approaches for
+        # detecting a step size that minimizes the total error, but this
+        # heuristic seems simple and effective.
+        i = (work.error > work.error_last*10) & ~stop
+        work.status[i] = _EERRORINCREASE
+        stop[i] = True
+
+        return stop
+
+    def post_termination_check(work):
+        return
+
+    def customize_result(res, shape):
+        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, preserve_shape)
+
+
+def _derivative_weights(work, n, xp):
+    # This produces the weights of the finite difference formula for a given
+    # stencil. In experiments, use of a second-order central difference formula
+    # with Richardson extrapolation was more accurate numerically, but it was
+    # more complicated, and it would have become even more complicated when
+    # adding support for one-sided differences. However, now that all the
+    # function evaluation values are stored, they can be processed in whatever
+    # way is desired to produce the derivative estimate. We leave alternative
+    # approaches to future work. To be more self-contained, here is the theory
+    # for deriving the weights below.
+    #
+    # Recall that the Taylor expansion of a univariate, scalar-values function
+    # about a point `x` may be expressed as:
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # Suppose we evaluate f(x), f(x+h), and f(x-h).  We have:
+    #      f(x)      =     f(x)
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    #      f(x - h)  =     f(x) - f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # We can solve for weights `wi` such that:
+    #   w1*f(x)      = w1*(f(x))
+    # + w2*f(x + h)  = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    # + w3*f(x - h)  = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    #                =     0    + f'(x)*h + 0               + O(h**3)
+    # Then
+    #     f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
+    # is a finite difference derivative approximation with error O(h**2),
+    # and so it is said to be a "second-order" approximation. Under certain
+    # conditions (e.g. well-behaved function, `h` sufficiently small), the
+    # error in the approximation will decrease with h**2; that is, if `h` is
+    # reduced by a factor of 2, the error is reduced by a factor of 4.
+    #
+    # By default, we use eighth-order formulae. Our central-difference formula
+    # uses abscissae:
+    #   x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
+    # where `c` is the step factor. (Typically, the step factor is greater than
+    # one, so the outermost points - as written above - are actually closest to
+    # `x`.) This "stencil" is chosen so that each iteration, the step can be
+    # reduced by the factor `c`, and most of the function evaluations can be
+    # reused with the new step size. For example, in the next iteration, we
+    # will have:
+    #   x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
+    # We do not reuse `x-h` and `x+h` for the new derivative estimate.
+    # While this would increase the order of the formula and thus the
+    # theoretical convergence rate, it is also less stable numerically.
+    # (As noted above, there are other ways of processing the values that are
+    # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
+    # to simplify future development of this sort of improvement.)
+    #
+    # The (right) one-sided formula is produced similarly using abscissae
+    #   x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
+    # where `d` is the square root of `c`. (The left one-sided formula simply
+    # uses -h.) When the step size is reduced by factor `c = d**2`, we have
+    # abscissae:
+    #   x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
+    # `d` is chosen as the square root of `c` so that the rate of the step-size
+    # reduction is the same per iteration as in the central difference case.
+    # Note that because the central difference formulas are inherently of even
+    # order, for simplicity, we use only even-order formulas for one-sided
+    # differences, too.
+
+    # It's possible for the user to specify `fac` in, say, double precision but
+    # `x` and `args` in single precision. `fac` gets converted to single
+    # precision, but we should always use double precision for the intermediate
+    # calculations here to avoid additional error in the weights.
+    fac = float(work.fac)
+
+    # Note that if the user switches back to floating point precision with
+    # `x` and `args`, then `fac` will not necessarily equal the (lower
+    # precision) cached `_derivative_weights.fac`, and the weights will
+    # need to be recalculated. This could be fixed, but it's late, and of
+    # low consequence.
+
+    diff_state = work.diff_state
+    if fac != diff_state.fac:
+        diff_state.central = []
+        diff_state.right = []
+        diff_state.fac = fac
+
+    if len(diff_state.central) != 2*n + 1:
+        # Central difference weights. Consider refactoring this; it could
+        # probably be more compact.
+        # Note: Using NumPy here is OK; we convert to xp-type at the end
+        i = np.arange(-n, n + 1)
+        p = np.abs(i) - 1.  # center point has power `p` -1, but sign `s` is 0
+        s = np.sign(i)
+
+        h = s / fac ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2*n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        # Enforce identities to improve accuracy
+        weights[n] = 0
+        for i in range(n):
+            weights[-i-1] = -weights[i]
+
+        # Cache the weights. We only need to calculate them once unless
+        # the step factor changes.
+        diff_state.central = weights
+
+        # One-sided difference weights. The left one-sided weights (with
+        # negative steps) are simply the negative of the right one-sided
+        # weights, so no need to compute them separately.
+        i = np.arange(2*n + 1)
+        p = i - 1.
+        s = np.sign(i)
+
+        h = s / np.sqrt(fac) ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2 * n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        diff_state.right = weights
+
+    return (xp.asarray(diff_state.central, dtype=work.dtype),
+            xp.asarray(diff_state.right, dtype=work.dtype))
+
+
+def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
+             step_factor=2.0, step_direction=0):
+    r"""Evaluate the Jacobian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Jacobian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `jacobian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Jacobian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation. Must be broadcastable with `x` and `step_direction`.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    step_direction : integer array_like
+        An array representing the direction of the finite difference steps (e.g.
+        for use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and `initial_step`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+
+    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 error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        df : float array
+            The Jacobian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Jacobian and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `df`. For instance, element ``i`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``i`` of `df`.
+
+    See Also
+    --------
+    derivative, hessian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Jacobian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
+    ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
+    respectively, and let ``...`` represent an arbitrary tuple of integers.
+    If we wish to evaluate the Jacobian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
+      The first axis represents the :math:`m` inputs of :math:`f`; the remainder
+      are for evaluating the function at multiple points in a single call.
+    - argument `f` must return an array of shape ``(n, ...)``. The first
+      axis represents the :math:`n` outputs of :math:`f`; the remainder
+      are for the result of evaluating the function at multiple points.
+    - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
+      the Jacobian.
+
+    This function is also vectorized in the sense that the Jacobian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
+    attribute of the result would have shape ``(n, m, k)``.
+
+    Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
+    only accept an array of shape ``(m,)``. A simple solution to satisfy the required
+    interface is to wrap ``f_not_vectorized`` as follows::
+
+        def f(x):
+            return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
+
+    Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
+    only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
+    consider::
+
+        def f(x):
+            m, batch = x.shape[0], x.shape[1:]  # x.shape is (m, ...)
+            x = np.reshape(x, (m, -1))  # `-1` is short for q = prod(batch)
+            res = f_vec_q(x)  # pass shape (m, q) to function
+            n = res.shape[0]
+            return np.reshape(res, (n,) + batch)  # return shape (n, ...)
+
+    Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
+
+    References
+    ----------
+    .. [1] Jacobian matrix and determinant, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
+    to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
+    at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import jacobian
+    >>> from scipy.optimize import rosen, rosen_der
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = jacobian(rosen, x)
+    >>> ref = rosen_der(x)  # reference value of the gradient
+    >>> res.df, ref
+    (array([-51.,  -1.,  50.]), array([-51.,  -1.,  50.]))
+
+    As an example of a function with multiple outputs, consider Example 4
+    from [1]_.
+
+    >>> def f(x):
+    ...     x1, x2, x3 = x
+    ...     return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
+
+    The true Jacobian is given by:
+
+    >>> def df(x):
+    ...         x1, x2, x3 = x
+    ...         one = np.ones_like(x1)
+    ...         return [[one, 0*one, 0*one],
+    ...                 [0*one, 0*one, 5*one],
+    ...                 [0*one, 8*x2, -2*one],
+    ...                 [x3*np.cos(x1), 0*one, np.sin(x1)]]
+
+    Evaluate the Jacobian at an arbitrary point.
+
+    >>> rng = np.random.default_rng(389252938452)
+    >>> x = rng.random(size=3)
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    Evaluate the Jacobian at 10 arbitrary points in a single call.
+
+    >>> x = rng.random(size=(3, 10))
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3, 10)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    """
+    xp = array_namespace(x)
+    x = xp.asarray(x)
+    int_dtype = xp.isdtype(x.dtype, 'integral')
+    x0 = xp.asarray(x, dtype=xp.asarray(1.0).dtype) if int_dtype else x
+
+    if x0.ndim < 1:
+        message = "Argument `x` must be at least 1-D."
+        raise ValueError(message)
+
+    m = x0.shape[0]
+    i = xp.arange(m)
+
+    def wrapped(x):
+        p = () if x.ndim == x0.ndim else (x.shape[-1],)  # number of abscissae
+
+        new_shape = (m, m) + x0.shape[1:] + p
+        xph = xp.expand_dims(x0, axis=1)
+        if x.ndim != x0.ndim:
+            xph = xp.expand_dims(xph, axis=-1)
+        xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
+        xph[i, i] = x
+        return f(xph)
+
+    res = derivative(wrapped, x, tolerances=tolerances,
+                     maxiter=maxiter, order=order, initial_step=initial_step,
+                     step_factor=step_factor, preserve_shape=True,
+                     step_direction=step_direction)
+
+    del res.x  # the user knows `x`, and the way it gets broadcasted is meaningless here
+    return res
+
+
+def hessian(f, x, *, tolerances=None, maxiter=10,
+            order=8, initial_step=0.5, step_factor=2.0):
+    r"""Evaluate the Hessian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Hessian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `hessian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Hessian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+
+    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 error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        ddf : float array
+            The Hessian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Hessian and the estimate in the
+            previous iteration.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``[i, j]`` of `ddf`.
+
+    See Also
+    --------
+    derivative, jacobian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Hessian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
+    ``m`` the positive integer value of :math:`m`. If we wish to evaluate
+    the Hessian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape
+      ``(m, ...)``. The first axis represents the :math:`m` inputs of
+      :math:`f`; the remaining axes indicated by ellipses are for evaluating
+      the function at several abscissae in a single call.
+    - argument `f` must return an array of shape ``(...)``.
+    - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
+      the Hessian.
+
+    This function is also vectorized in the sense that the Hessian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
+    attribute of the result would have shape ``(m, m, k)``. Note that the
+    axis associated with the ``k`` points is included within the axes
+    denoted by ``(...)``.
+
+    Currently, `hessian` is implemented by nesting calls to `jacobian`.
+    All options passed to `hessian` are used for both the inner and outer
+    calls with one exception: the `rtol` used in the inner `jacobian` call
+    is tightened by a factor of 100 with the expectation that the inner
+    error can be ignored. A consequence is that `rtol` should not be set
+    less than 100 times the precision of the dtype of `x`; a warning is
+    emitted otherwise.
+
+    References
+    ----------
+    .. [1] Hessian matrix, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Hessian_matrix
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
+    wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import hessian
+    >>> from scipy.optimize import rosen, rosen_hess
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = hessian(rosen, x)
+    >>> ref = rosen_hess(x)  # reference value of the Hessian
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    `hessian` is vectorized to evaluate the Hessian at multiple points
+    in a single call.
+
+    >>> rng = np.random.default_rng(4589245925010)
+    >>> x = rng.random((m, 10))
+    >>> res = hessian(rosen, x)
+    >>> ref = [rosen_hess(xi) for xi in x.T]
+    >>> ref = np.moveaxis(ref, 0, -1)
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    """
+    # todo:
+    # - add ability to vectorize over additional parameters (*args?)
+    # - error estimate stack with inner jacobian (or use legit 2D stencil)
+
+    kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
+                  step_factor=step_factor)
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    xp = array_namespace(x)
+    x = xp.asarray(x)
+    dtype = x.dtype if not xp.isdtype(x.dtype, 'integral') else xp.asarray(1.).dtype
+    finfo = xp.finfo(dtype)
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `derivative`
+
+    # tighten the inner tolerance to make the inner error negligible
+    rtol_min = finfo.eps * 100
+    message = (f"The specified `{rtol=}`, but error estimates are likely to be "
+               f"unreliable when `rtol < {rtol_min}`.")
+    if 0 < rtol < rtol_min:  # rtol <= 0 is an error
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+        rtol = rtol_min
+
+    def df(x):
+        tolerances = dict(rtol=rtol/100, atol=atol)
+        temp = jacobian(f, x, tolerances=tolerances, **kwargs)
+        nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
+        return temp.df
+
+    nfev = []  # track inner function evaluations
+    res = jacobian(df, x, tolerances=tolerances, **kwargs)  # jacobian of jacobian
+
+    nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
+    res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64)  # appease torch
+    res.nfev = xp_take_along_axis(nfev, res_nit, axis=0)[0]
+    res.ddf = res.df
+    del res.df  # this is renamed to ddf
+    del res.nit  # this is only the outer-jacobian nit
+
+    return res
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a7e274b860ee3926e47ee6dc04e10f85e849a9f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__pycache__/test_differentiate.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__pycache__/test_differentiate.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..262bae9ff3738c648a10a86d5974312be8d56d43
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/__pycache__/test_differentiate.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..64bc8193cc237465e9427300bedfac8712963e4c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py
@@ -0,0 +1,695 @@
+import math
+import pytest
+
+import numpy as np
+
+from scipy.conftest import array_api_compatible
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal, xp_assert_less
+from scipy._lib._array_api import is_numpy, is_torch, array_namespace
+
+from scipy import stats, optimize, special
+from scipy.differentiate import derivative, jacobian, hessian
+from scipy.differentiate._differentiate import _EERRORINCREASE
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+
+array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+jax_skip_reason = 'JAX arrays do not support item assignment.'
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestDerivative:
+
+    def f(self, x):
+        return special.ndtr(x)
+
+    @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)])
+    def test_basic(self, x, xp):
+        # Invert distribution CDF and compare against distribution `ppf`
+        default_dtype = xp.asarray(1.).dtype
+        res = derivative(self.f, xp.asarray(x, dtype=default_dtype))
+        ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype)
+        xp_assert_close(res.df, ref)
+        # This would be nice, but doesn't always work out. `error` is an
+        # estimate, not a bound.
+        if not is_torch(xp):
+            xp_assert_less(xp.abs(res.df - ref), res.error)
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.parametrize('case', stats._distr_params.distcont)
+    def test_accuracy(self, case):
+        distname, params = case
+        dist = getattr(stats, distname)(*params)
+        x = dist.median() + 0.1
+        res = derivative(dist.cdf, x)
+        ref = dist.pdf(x)
+        xp_assert_close(res.df, ref, atol=1e-10)
+
+    @pytest.mark.parametrize('order', [1, 6])
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, order, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+        n = np.size(x)
+        state = {}
+
+        @np.vectorize
+        def _derivative_single(x):
+            return derivative(self.f, x, order=order)
+
+        def f(x, *args, **kwargs):
+            state['nit'] += 1
+            state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1]
+            return self.f(x, *args, **kwargs)
+
+        state['nit'] = -1
+        state['feval'] = 0
+
+        res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order)
+        refs = _derivative_single(x).ravel()
+
+        ref_x = [ref.x for ref in refs]
+        xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x))
+
+        ref_df = [ref.df for ref in refs]
+        xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df))
+
+        ref_error = [ref.error for ref in refs]
+        xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error),
+                        atol=1e-12)
+
+        ref_success = [bool(ref.success) for ref in refs]
+        xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success))
+
+        ref_flag = [np.int32(ref.status) for ref in refs]
+        xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag))
+
+        ref_nfev = [np.int32(ref.nfev) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nfev) == state['feval']
+
+        ref_nit = [np.int32(ref.nit) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nit) == state['nit']
+
+    def test_flags(self, xp):
+        # Test cases that should produce different status flags; show that all
+        # can be produced simultaneously.
+        rng = np.random.default_rng(5651219684984213)
+        def f(xs, js):
+            f.nit += 1
+            funcs = [lambda x: x - 2.5,  # converges
+                     lambda x: xp.exp(x)*rng.random(),  # error increases
+                     lambda x: xp.exp(x),  # reaches maxiter due to order=2
+                     lambda x: xp.full_like(x, xp.nan)]  # stops due to NaN
+            res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))]
+            return xp.stack(res)
+        f.nit = 0
+
+        args = (xp.arange(4, dtype=xp.int64),)
+        res = derivative(f, xp.ones(4, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, args=args)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_flags_preserve_shape(self, xp):
+        # Same test as above but using `preserve_shape` option to simplify.
+        rng = np.random.default_rng(5651219684984213)
+        def f(x):
+            out = [x - 2.5,  # converges
+                   xp.exp(x)*rng.random(),  # error increases
+                   xp.exp(x),  # reaches maxiter due to order=2
+                   xp.full_like(x, xp.nan)]  # stops due to NaN
+            return xp.stack(out)
+
+        res = derivative(f, xp.asarray(1, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, preserve_shape=True)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_preserve_shape(self, xp):
+        # Test `preserve_shape` option
+        def f(x):
+            out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2]
+            return xp.stack(out)
+
+        x = xp.asarray(0.)
+        ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x),
+                          20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)])
+        res = derivative(f, x, preserve_shape=True)
+        xp_assert_close(res.df, ref)
+
+    def test_convergence(self, xp):
+        # Test that the convergence tolerances behave as expected
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+        tolerances0 = dict(atol=0, rtol=0)
+
+        tolerances = tolerances0.copy()
+        tolerances['atol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3
+        tolerances['atol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        tolerances = tolerances0.copy()
+        tolerances['rtol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3 * ref
+        tolerances['rtol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6 * ref
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+    def test_step_parameters(self, xp):
+        # Test that step factors have the expected effect on accuracy
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+
+        res1 = derivative(f, x, initial_step=0.5, maxiter=1)
+        res2 = derivative(f, x, initial_step=0.05, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        res1 = derivative(f, x, step_factor=2, maxiter=1)
+        res2 = derivative(f, x, step_factor=20, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        # `step_factor` can be less than 1: `initial_step` is the minimum step
+        kwargs = dict(order=4, maxiter=1, step_direction=0)
+        res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs)
+        ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        # This is a similar test for one-sided difference
+        kwargs = dict(order=2, maxiter=1, step_direction=1)
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        kwargs['step_direction'] = -1
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+    def test_step_direction(self, xp):
+        # test that `step_direction` works as expected
+        def f(x):
+            y = xp.exp(x)
+            y[(x < 0) + (x > 2)] = xp.nan
+            return y
+
+        x = xp.linspace(0, 2, 10)
+        step_direction = xp.zeros_like(x)
+        step_direction[x < 0.6], step_direction[x > 1.4] = 1, -1
+        res = derivative(f, x, step_direction=step_direction)
+        xp_assert_close(res.df, xp.exp(x))
+        assert xp.all(res.success)
+
+    def test_vectorized_step_direction_args(self, xp):
+        # test that `step_direction` and `args` are vectorized properly
+        def f(x, p):
+            return x ** p
+
+        def df(x, p):
+            return p * x ** (p - 1)
+
+        x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1))
+        hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1))
+        p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1))
+        res = derivative(f, x, step_direction=hdir, args=(p,))
+        ref = xp.broadcast_to(df(x, p), res.df.shape)
+        ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype)
+        xp_assert_close(res.df, ref)
+
+    def test_initial_step(self, xp):
+        # Test that `initial_step` works as expected and is vectorized
+        def f(x):
+            return xp.exp(x)
+
+        x = xp.asarray(0., dtype=xp.float64)
+        step_direction = xp.asarray([-1, 0, 1])
+        h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1))
+        res = derivative(f, x, initial_step=h0, order=2, maxiter=1,
+                         step_direction=step_direction)
+        err = xp.abs(res.df - f(x))
+
+        # error should be smaller for smaller step sizes
+        assert xp.all(err[:-1, ...] < err[1:, ...])
+
+        # results of vectorized call should match results with
+        # initial_step taken one at a time
+        for i in range(h0.shape[0]):
+            ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1,
+                             step_direction=step_direction)
+            xp_assert_close(res.df[i, :], ref.df, rtol=1e-14)
+
+    def test_maxiter_callback(self, xp):
+        # Test behavior of `maxiter` parameter and `callback` interface
+        x = xp.asarray(0.612814, dtype=xp.float64)
+        maxiter = 3
+
+        def f(x):
+            res = special.ndtr(x)
+            return res
+
+        default_order = 8
+        res = derivative(f, x, maxiter=maxiter, tolerances=dict(rtol=1e-15))
+        assert not xp.any(res.success)
+        assert xp.all(res.nfev == default_order + 1 + (maxiter - 1)*2)
+        assert xp.all(res.nit == maxiter)
+
+        def callback(res):
+            callback.iter += 1
+            callback.res = res
+            assert hasattr(res, 'x')
+            assert float(res.df) not in callback.dfs
+            callback.dfs.add(float(res.df))
+            assert res.status == eim._EINPROGRESS
+            if callback.iter == maxiter:
+                raise StopIteration
+        callback.iter = -1  # callback called once before first iteration
+        callback.res = None
+        callback.dfs = set()
+
+        res2 = derivative(f, x, callback=callback, tolerances=dict(rtol=1e-15))
+        # 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 res2[key] == eim._ECALLBACK
+            else:
+                assert res2[key] == callback.res[key] == res[key]
+
+    @pytest.mark.parametrize("hdir", (-1, 0, 1))
+    @pytest.mark.parametrize("x", (0.65, [0.65, 0.7]))
+    @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+    def test_dtype(self, hdir, x, dtype, xp):
+        if dtype == 'float16' and not is_numpy(xp):
+            pytest.skip('float16 not tested for alternative backends')
+
+        # Test that dtypes are preserved
+        dtype = getattr(xp, dtype)
+        x = xp.asarray(x, dtype=dtype)
+
+        def f(x):
+            assert x.dtype == dtype
+            return xp.exp(x)
+
+        def callback(res):
+            assert res.x.dtype == dtype
+            assert res.df.dtype == dtype
+            assert res.error.dtype == dtype
+
+        res = derivative(f, x, order=4, step_direction=hdir, callback=callback)
+        assert res.x.dtype == dtype
+        assert res.df.dtype == dtype
+        assert res.error.dtype == dtype
+        eps = xp.finfo(dtype).eps
+        # not sure why torch is less accurate here; might be worth investigating
+        rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5
+        xp_assert_close(res.df, xp.exp(res.x), rtol=rtol)
+
+    def test_input_validation(self, xp):
+        # Test input validation for appropriate error messages
+        one = xp.asarray(1)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(None, one)
+
+        message = 'Abscissae and function output must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, xp.asarray(-4+1j))
+
+        message = "When `preserve_shape=False`, the shape of the array..."
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3]))
+
+        message = 'Tolerances and step parameters must be non-negative...'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(rtol='ekki'))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, step_factor=object())
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=0)
+
+        message = '`order` must be a positive integer'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=0)
+
+        message = '`preserve_shape` must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, preserve_shape='herring')
+
+        message = '`callback` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, callback='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):
+            xp_test = array_namespace(x)  # needs `isdtype`
+            assert xp_test.isdtype(x.dtype, 'real floating')
+            return x ** 99 - 1
+
+        if not is_torch(xp):  # torch defaults to float32
+            res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10))
+            assert res.success
+            xp_assert_close(res.df, xp.asarray(99*7.**98))
+
+        # Test invalid step size and direction
+        res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        res = derivative(xp.exp, xp.asarray(1), initial_step=0)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        # Test that if success is achieved in the correct number
+        # of iterations if function is a polynomial. Ideally, all polynomials
+        # of order 0-2 would get exact result with 0 refinement iterations,
+        # all polynomials of order 3-4 would be differentiated exactly after
+        # 1 iteration, etc. However, it seems that `derivative` needs an
+        # extra iteration to detect convergence based on the error estimate.
+
+        for n in range(6):
+            x = xp.asarray(1.5, dtype=xp.float64)
+            def f(x):
+                return 2*x**n
+
+            ref = 2*n*x**(n-1)
+
+            res = derivative(f, x, maxiter=1, order=max(1, n))
+            xp_assert_close(res.df, ref, rtol=1e-15)
+            xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64))
+
+            res = derivative(f, x, order=max(1, n))
+            assert res.success
+            assert res.nit == 2
+            xp_assert_close(res.df, ref, rtol=1e-15)
+
+        # Test scalar `args` (not in tuple)
+        def f(x, c):
+            return c*x - 1
+
+        res = derivative(f, xp.asarray(2), args=xp.asarray(3))
+        xp_assert_close(res.df, xp.asarray(3.))
+
+    # no need to run a test on multiple backends if it's xfailed
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.xfail
+    @pytest.mark.parametrize("case", (  # function, evaluation point
+        (lambda x: (x - 1) ** 3, 1),
+        (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1)
+    ))
+    def test_saddle_gh18811(self, case):
+        # With default settings, `derivative` will not always converge when
+        # the true derivative is exactly zero. This tests that specifying a
+        # (tight) `atol` alleviates the problem. See discussion in gh-18811.
+        atol = 1e-16
+        res = derivative(*case, step_direction=[-1, 0, 1], atol=atol)
+        assert np.all(res.success)
+        xp_assert_close(res.df, 0, atol=atol)
+
+
+class JacobianHessianTest:
+    def test_iv(self, xp):
+        jh_func = self.jh_func.__func__
+
+        # Test input validation
+        message = "Argument `x` must be at least 1-D."
+        with pytest.raises(ValueError, match=message):
+            jh_func(xp.sin, 1, tolerances=dict(atol=-1))
+
+        # Confirm that other parameters are being passed to `derivative`,
+        # which raises an appropriate error message.
+        x = xp.ones(3)
+        func = optimize.rosen
+        message = 'Tolerances and step parameters must be non-negative scalars.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(rtol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, step_factor=-1)
+
+        message = '`order` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, order=-1)
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, maxiter=-1)
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestJacobian(JacobianHessianTest):
+    jh_func = jacobian
+
+    # Example functions and Jacobians from Wikipedia:
+    # https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Examples
+
+    def f1(z, xp):
+        x, y = z
+        return xp.stack([x ** 2 * y, 5 * x + xp.sin(y)])
+
+    def df1(z):
+        x, y = z
+        return [[2 * x * y, x ** 2], [np.full_like(x, 5), np.cos(y)]]
+
+    f1.mn = 2, 2  # type: ignore[attr-defined]
+    f1.ref = df1  # type: ignore[attr-defined]
+
+    def f2(z, xp):
+        r, phi = z
+        return xp.stack([r * xp.cos(phi), r * xp.sin(phi)])
+
+    def df2(z):
+        r, phi = z
+        return [[np.cos(phi), -r * np.sin(phi)],
+                [np.sin(phi), r * np.cos(phi)]]
+
+    f2.mn = 2, 2  # type: ignore[attr-defined]
+    f2.ref = df2  # type: ignore[attr-defined]
+
+    def f3(z, xp):
+        r, phi, th = z
+        return xp.stack([r * xp.sin(phi) * xp.cos(th), r * xp.sin(phi) * xp.sin(th),
+                         r * xp.cos(phi)])
+
+    def df3(z):
+        r, phi, th = z
+        return [[np.sin(phi) * np.cos(th), r * np.cos(phi) * np.cos(th),
+                 -r * np.sin(phi) * np.sin(th)],
+                [np.sin(phi) * np.sin(th), r * np.cos(phi) * np.sin(th),
+                 r * np.sin(phi) * np.cos(th)],
+                [np.cos(phi), -r * np.sin(phi), np.zeros_like(r)]]
+
+    f3.mn = 3, 3  # type: ignore[attr-defined]
+    f3.ref = df3  # type: ignore[attr-defined]
+
+    def f4(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([x1, 5 * x3, 4 * x2 ** 2 - 2 * x3, x3 * xp.sin(x1)])
+
+    def df4(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[one, 0 * one, 0 * one],
+                [0 * one, 0 * one, 5 * one],
+                [0 * one, 8 * x2, -2 * one],
+                [x3 * np.cos(x1), 0 * one, np.sin(x1)]]
+
+    f4.mn = 3, 4  # type: ignore[attr-defined]
+    f4.ref = df4  # type: ignore[attr-defined]
+
+    def f5(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([5 * x2, 4 * x1 ** 2 - 2 * xp.sin(x2 * x3), x2 * x3])
+
+    def df5(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[0 * one, 5 * one, 0 * one],
+                [8 * x1, -2 * x3 * np.cos(x2 * x3), -2 * x2 * np.cos(x2 * x3)],
+                [0 * one, x3, x2]]
+
+    f5.mn = 3, 3  # type: ignore[attr-defined]
+    f5.ref = df5  # type: ignore[attr-defined]
+
+    def rosen(x, _): return optimize.rosen(x)
+    rosen.mn = 5, 1  # type: ignore[attr-defined]
+    rosen.ref = optimize.rosen_der  # type: ignore[attr-defined]
+
+    @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+    @pytest.mark.parametrize('size', [(), (6,), (2, 3)])
+    @pytest.mark.parametrize('func', [f1, f2, f3, f4, f5, rosen])
+    def test_examples(self, dtype, size, func, xp):
+        atol = 1e-10 if dtype == 'float64' else 1.99e-3
+        dtype = getattr(xp, dtype)
+        rng = np.random.default_rng(458912319542)
+        m, n = func.mn
+        x = rng.random(size=(m,) + size)
+        res = jacobian(lambda x: func(x , xp), xp.asarray(x, dtype=dtype))
+        # convert list of arrays to single array before converting to xp array
+        ref = xp.asarray(np.asarray(func.ref(x)), dtype=dtype)
+        xp_assert_close(res.df, ref, atol=atol)
+
+    def test_attrs(self, xp):
+        # Test attributes of result object
+        z = xp.asarray([0.5, 0.25])
+
+        # case in which some elements of the Jacobian are harder
+        # to calculate than others
+        def df1(z):
+            x, y = z
+            return xp.stack([xp.cos(0.5*x) * xp.cos(y), xp.sin(2*x) * y**2])
+
+        def df1_0xy(x, y):
+            return xp.cos(0.5*x) * xp.cos(y)
+
+        def df1_1xy(x, y):
+            return xp.sin(2*x) * y**2
+
+        res = jacobian(df1, z, initial_step=10)
+        if is_numpy(xp):
+            assert len(np.unique(res.nit)) == 4
+            assert len(np.unique(res.nfev)) == 4
+
+        res00 = jacobian(lambda x: df1_0xy(x, z[1]), z[0:1], initial_step=10)
+        res01 = jacobian(lambda y: df1_0xy(z[0], y), z[1:2], initial_step=10)
+        res10 = jacobian(lambda x: df1_1xy(x, z[1]), z[0:1], initial_step=10)
+        res11 = jacobian(lambda y: df1_1xy(z[0], y), z[1:2], initial_step=10)
+        ref = optimize.OptimizeResult()
+        for attr in ['success', 'status', 'df', 'nit', 'nfev']:
+            ref_attr = xp.asarray([[getattr(res00, attr), getattr(res01, attr)],
+                                   [getattr(res10, attr), getattr(res11, attr)]])
+            ref[attr] = xp.squeeze(ref_attr)
+            rtol = 1.5e-5 if res[attr].dtype == xp.float32 else 1.5e-14
+            xp_assert_close(res[attr], ref[attr], rtol=rtol)
+
+    def test_step_direction_size(self, xp):
+        # Check that `step_direction` and `initial_step` can be used to ensure that
+        # the usable domain of a function is respected.
+        rng = np.random.default_rng(23892589425245)
+        b = rng.random(3)
+        eps = 1e-7  # torch needs wiggle room?
+
+        def f(x):
+            x[0, x[0] < b[0]] = xp.nan
+            x[0, x[0] > b[0] + 0.25] = xp.nan
+            x[1, x[1] > b[1]] = xp.nan
+            x[1, x[1] < b[1] - 0.1-eps] = xp.nan
+            return TestJacobian.f5(x, xp)
+
+        dir = [1, -1, 0]
+        h0 = [0.25, 0.1, 0.5]
+        atol = {'atol': 1e-8}
+        res = jacobian(f, xp.asarray(b, dtype=xp.float64), initial_step=h0,
+                       step_direction=dir, tolerances=atol)
+        ref = xp.asarray(TestJacobian.df5(b), dtype=xp.float64)
+        xp_assert_close(res.df, ref, atol=1e-8)
+        assert xp.all(xp.isfinite(ref))
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestHessian(JacobianHessianTest):
+    jh_func = hessian
+
+    @pytest.mark.parametrize('shape', [(), (4,), (2, 4)])
+    def test_example(self, shape, xp):
+        rng = np.random.default_rng(458912319542)
+        m = 3
+        x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64)
+        res = hessian(optimize.rosen, x)
+        if shape:
+            x = xp.reshape(x, (m, -1))
+            ref = xp.stack([optimize.rosen_hess(xi) for xi in x.T])
+            ref = xp.moveaxis(ref, 0, -1)
+            ref = xp.reshape(ref, (m, m,) + shape)
+        else:
+            ref = optimize.rosen_hess(x)
+        xp_assert_close(res.ddf, ref, atol=1e-8)
+
+        # # Removed symmetry enforcement; consider adding back in as a feature
+        # # check symmetry
+        # for key in ['ddf', 'error', 'nfev', 'success', 'status']:
+        #     assert_equal(res[key], np.swapaxes(res[key], 0, 1))
+
+    def test_float32(self, xp):
+        rng = np.random.default_rng(458912319542)
+        x = xp.asarray(rng.random(3), dtype=xp.float32)
+        res = hessian(optimize.rosen, x)
+        ref = optimize.rosen_hess(x)
+        mask = (ref != 0)
+        xp_assert_close(res.ddf[mask], ref[mask])
+        atol = 1e-2 * xp.abs(xp.min(ref[mask]))
+        xp_assert_close(res.ddf[~mask], ref[~mask], atol=atol)
+
+    def test_nfev(self, xp):
+        z = xp.asarray([0.5, 0.25])
+        xp_test = array_namespace(z)
+
+        def f1(z):
+            x, y = xp_test.broadcast_arrays(*z)
+            f1.nfev = f1.nfev + (math.prod(x.shape[2:]) if x.ndim > 2 else 1)
+            return xp.sin(x) * y ** 3
+        f1.nfev = 0
+
+
+        res = hessian(f1, z, initial_step=10)
+        f1.nfev = 0
+        res00 = hessian(lambda x: f1([x[0], z[1]]), z[0:1], initial_step=10)
+        assert res.nfev[0, 0] == f1.nfev == res00.nfev[0, 0]
+
+        f1.nfev = 0
+        res11 = hessian(lambda y: f1([z[0], y[0]]), z[1:2], initial_step=10)
+        assert res.nfev[1, 1] == f1.nfev == res11.nfev[0, 0]
+
+        # Removed symmetry enforcement; consider adding back in as a feature
+        # assert_equal(res.nfev, res.nfev.T)  # check symmetry
+        # assert np.unique(res.nfev).size == 3
+
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason='Python list input uses NumPy backend')
+    def test_small_rtol_warning(self, xp):
+        message = 'The specified `rtol=1e-15`, but...'
+        with pytest.warns(RuntimeWarning, match=message):
+            hessian(xp.sin, [1.], tolerances=dict(rtol=1e-15))
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__init__.py b/venv/lib/python3.10/site-packages/scipy/fftpack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10f4b39e48e2d6c0b042582ca65f572bde6ba575
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/__init__.py
@@ -0,0 +1,103 @@
+"""
+=========================================================
+Legacy discrete Fourier transforms (:mod:`scipy.fftpack`)
+=========================================================
+
+.. legacy::
+
+   New code should use :mod:`scipy.fft`.
+
+Fast Fourier Transforms (FFTs)
+==============================
+
+.. autosummary::
+   :toctree: generated/
+
+   fft - Fast (discrete) Fourier Transform (FFT)
+   ifft - Inverse FFT
+   fft2 - 2-D FFT
+   ifft2 - 2-D inverse FFT
+   fftn - N-D FFT
+   ifftn - N-D inverse FFT
+   rfft - FFT of strictly real-valued sequence
+   irfft - Inverse of rfft
+   dct - Discrete cosine transform
+   idct - Inverse discrete cosine transform
+   dctn - N-D Discrete cosine transform
+   idctn - N-D Inverse discrete cosine transform
+   dst - Discrete sine transform
+   idst - Inverse discrete sine transform
+   dstn - N-D Discrete sine transform
+   idstn - N-D Inverse discrete sine transform
+
+Differential and pseudo-differential operators
+==============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   diff - Differentiation and integration of periodic sequences
+   tilbert - Tilbert transform:         cs_diff(x,h,h)
+   itilbert - Inverse Tilbert transform: sc_diff(x,h,h)
+   hilbert - Hilbert transform:         cs_diff(x,inf,inf)
+   ihilbert - Inverse Hilbert transform: sc_diff(x,inf,inf)
+   cs_diff - cosh/sinh pseudo-derivative of periodic sequences
+   sc_diff - sinh/cosh pseudo-derivative of periodic sequences
+   ss_diff - sinh/sinh pseudo-derivative of periodic sequences
+   cc_diff - cosh/cosh pseudo-derivative of periodic sequences
+   shift - Shift periodic sequences
+
+Helper functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   fftshift - Shift the zero-frequency component to the center of the spectrum
+   ifftshift - The inverse of `fftshift`
+   fftfreq - Return the Discrete Fourier Transform sample frequencies
+   rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+
+Note that ``fftshift``, ``ifftshift`` and ``fftfreq`` are numpy functions
+exposed by ``fftpack``; importing them from ``numpy`` should be preferred.
+
+Convolutions (:mod:`scipy.fftpack.convolve`)
+============================================
+
+.. module:: scipy.fftpack.convolve
+
+.. autosummary::
+   :toctree: generated/
+
+   convolve
+   convolve_z
+   init_convolution_kernel
+   destroy_convolve_cache
+
+"""
+
+
+__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
+           'fft2','ifft2',
+           'diff',
+           'tilbert','itilbert','hilbert','ihilbert',
+           'sc_diff','cs_diff','cc_diff','ss_diff',
+           'shift',
+           'fftfreq', 'rfftfreq',
+           'fftshift', 'ifftshift',
+           'next_fast_len',
+           'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
+           ]
+
+from ._basic import *
+from ._pseudo_diffs import *
+from ._helper import *
+from ._realtransforms import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import basic, helper, pseudo_diffs, realtransforms
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f726fe4d73582709c63618dcbca3f38c247381b4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ad8cfc3c3c768b523616a13cb1b1abeace749ad
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_helper.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa0dadf4a7c41e6c8911875bda178c9d539ef88b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_helper.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c238d7ce289bb8153322fce82d4647f9141a648
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd55719894a7d3cb9c4a48244ff0d16228f2cce4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86df0f312c43d95144b065a13141de0c353e5a03
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/helper.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50dea02e289335af03e1724c2e0d40c3d6d93aae
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/helper.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f7eaa35efc38e232375598b89cab6a10463a0c3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8934b73c49696b1477f3a37bf5059374533f5ae4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/_basic.py b/venv/lib/python3.10/site-packages/scipy/fftpack/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..59c85ae4b364464a66489ef221f7f7ac45624694
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/_basic.py
@@ -0,0 +1,428 @@
+"""
+Discrete Fourier Transforms - _basic.py
+"""
+# Created by Pearu Peterson, August,September 2002
+__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
+           'fft2','ifft2']
+
+from scipy.fft import _pocketfft
+from ._helper import _good_shape
+
+
+def fft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return discrete Fourier transform of real or complex sequence.
+
+    The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
+
+    ``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to Fourier transform.
+    n : int, optional
+        Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
+        truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the fft's are computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    z : complex ndarray
+        with the elements::
+
+            [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)]        if n is even
+            [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)]  if n is odd
+
+        where::
+
+            y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
+
+    See Also
+    --------
+    ifft : Inverse FFT
+    rfft : FFT of a real sequence
+
+    Notes
+    -----
+    The packing of the result is "standard": If ``A = fft(a, n)``, then
+    ``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
+    positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
+    terms, in order of decreasingly negative frequency. So ,for an 8-point
+    transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
+    To rearrange the fft output so that the zero-frequency component is
+    centered, like [-4, -3, -2, -1,  0,  1,  2,  3], use `fftshift`.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    This function is most efficient when `n` is a power of two, and least
+    efficient when `n` is prime.
+
+    Note that if ``x`` is real-valued, then ``A[j] == A[n-j].conjugate()``.
+    If ``x`` is real-valued and ``n`` is even, then ``A[n/2]`` is real.
+
+    If the data type of `x` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data is both real and
+    symmetrical, the `dct` can again double the efficiency by generating
+    half of the spectrum from half of the signal.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft, ifft
+    >>> x = np.arange(5)
+    >>> np.allclose(fft(ifft(x)), x, atol=1e-15)  # within numerical accuracy.
+    True
+
+    """
+    return _pocketfft.fft(x, n, axis, None, overwrite_x)
+
+
+def ifft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return discrete inverse Fourier transform of real or complex sequence.
+
+    The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
+
+    ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
+
+    Parameters
+    ----------
+    x : array_like
+        Transformed data to invert.
+    n : int, optional
+        Length of the inverse Fourier transform.  If ``n < x.shape[axis]``,
+        `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
+        The default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the ifft's are computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    ifft : ndarray of floats
+        The inverse discrete Fourier transform.
+
+    See Also
+    --------
+    fft : Forward FFT
+
+    Notes
+    -----
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    This function is most efficient when `n` is a power of two, and least
+    efficient when `n` is prime.
+
+    If the data type of `x` is real, a "real IFFT" algorithm is automatically
+    used, which roughly halves the computation time.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fft, ifft
+    >>> import numpy as np
+    >>> x = np.arange(5)
+    >>> np.allclose(ifft(fft(x)), x, atol=1e-15)  # within numerical accuracy.
+    True
+
+    """
+    return _pocketfft.ifft(x, n, axis, None, overwrite_x)
+
+
+def rfft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Discrete Fourier transform of a real sequence.
+
+    Parameters
+    ----------
+    x : array_like, real-valued
+        The data to transform.
+    n : int, optional
+        Defines the length of the Fourier transform. If `n` is not specified
+        (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``,
+        `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded.
+    axis : int, optional
+        The axis along which the transform is applied. The default is the
+        last axis.
+    overwrite_x : bool, optional
+        If set to true, the contents of `x` can be overwritten. Default is
+        False.
+
+    Returns
+    -------
+    z : real ndarray
+        The returned real array contains::
+
+          [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))]              if n is even
+          [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))]   if n is odd
+
+        where::
+
+          y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n)
+          j = 0..n-1
+
+    See Also
+    --------
+    fft, irfft, scipy.fft.rfft
+
+    Notes
+    -----
+    Within numerical accuracy, ``y == rfft(irfft(y))``.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    To get an output with a complex datatype, consider using the newer
+    function `scipy.fft.rfft`.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fft, rfft
+    >>> a = [9, -9, 1, 3]
+    >>> fft(a)
+    array([  4. +0.j,   8.+12.j,  16. +0.j,   8.-12.j])
+    >>> rfft(a)
+    array([  4.,   8.,  12.,  16.])
+
+    """
+    return _pocketfft.rfft_fftpack(x, n, axis, None, overwrite_x)
+
+
+def irfft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return inverse discrete Fourier transform of real sequence x.
+
+    The contents of `x` are interpreted as the output of the `rfft`
+    function.
+
+    Parameters
+    ----------
+    x : array_like
+        Transformed data to invert.
+    n : int, optional
+        Length of the inverse Fourier transform.
+        If n < x.shape[axis], x is truncated.
+        If n > x.shape[axis], x is zero-padded.
+        The default results in n = x.shape[axis].
+    axis : int, optional
+        Axis along which the ifft's are computed; the default is over
+        the last axis (i.e., axis=-1).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    irfft : ndarray of floats
+        The inverse discrete Fourier transform.
+
+    See Also
+    --------
+    rfft, ifft, scipy.fft.irfft
+
+    Notes
+    -----
+    The returned real array contains::
+
+        [y(0),y(1),...,y(n-1)]
+
+    where for n is even::
+
+        y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
+                                     * exp(sqrt(-1)*j*k* 2*pi/n)
+                    + c.c. + x[0] + (-1)**(j) x[n-1])
+
+    and for n is odd::
+
+        y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
+                                     * exp(sqrt(-1)*j*k* 2*pi/n)
+                    + c.c. + x[0])
+
+    c.c. denotes complex conjugate of preceding expression.
+
+    For details on input parameters, see `rfft`.
+
+    To process (conjugate-symmetric) frequency-domain data with a complex
+    datatype, consider using the newer function `scipy.fft.irfft`.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import rfft, irfft
+    >>> a = [1.0, 2.0, 3.0, 4.0, 5.0]
+    >>> irfft(a)
+    array([ 2.6       , -3.16405192,  1.24398433, -1.14955713,  1.46962473])
+    >>> irfft(rfft(a))
+    array([1., 2., 3., 4., 5.])
+
+    """
+    return _pocketfft.irfft_fftpack(x, n, axis, None, overwrite_x)
+
+
+def fftn(x, shape=None, axes=None, overwrite_x=False):
+    """
+    Return multidimensional discrete Fourier transform.
+
+    The returned array contains::
+
+      y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
+         x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)
+
+    where d = len(x.shape) and n = x.shape.
+
+    Parameters
+    ----------
+    x : array_like
+        The (N-D) array to transform.
+    shape : int or array_like of ints or None, optional
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        The axes of `x` (`y` if `shape` is not None) along which the
+        transform is applied.
+        The default is over all axes.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed. Default is False.
+
+    Returns
+    -------
+    y : complex-valued N-D NumPy array
+        The (N-D) DFT of the input array.
+
+    See Also
+    --------
+    ifftn
+
+    Notes
+    -----
+    If ``x`` is real-valued, then
+    ``y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate()``.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fftn, ifftn
+    >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
+    >>> np.allclose(y, fftn(ifftn(y)))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.fftn(x, shape, axes, None, overwrite_x)
+
+
+def ifftn(x, shape=None, axes=None, overwrite_x=False):
+    """
+    Return inverse multidimensional discrete Fourier transform.
+
+    The sequence can be of an arbitrary type.
+
+    The returned array contains::
+
+      y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
+         x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)
+
+    where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.
+
+    For description of parameters see `fftn`.
+
+    See Also
+    --------
+    fftn : for detailed information.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fftn, ifftn
+    >>> import numpy as np
+    >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
+    >>> np.allclose(y, ifftn(fftn(y)))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.ifftn(x, shape, axes, None, overwrite_x)
+
+
+def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
+    """
+    2-D discrete Fourier transform.
+
+    Return the 2-D discrete Fourier transform of the 2-D argument
+    `x`.
+
+    See Also
+    --------
+    fftn : for detailed information.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft2, ifft2
+    >>> y = np.mgrid[:5, :5][0]
+    >>> y
+    array([[0, 0, 0, 0, 0],
+           [1, 1, 1, 1, 1],
+           [2, 2, 2, 2, 2],
+           [3, 3, 3, 3, 3],
+           [4, 4, 4, 4, 4]])
+    >>> np.allclose(y, ifft2(fft2(y)))
+    True
+    """
+    return fftn(x,shape,axes,overwrite_x)
+
+
+def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
+    """
+    2-D discrete inverse Fourier transform of real or complex sequence.
+
+    Return inverse 2-D discrete Fourier transform of
+    arbitrary type sequence x.
+
+    See `ifft` for more information.
+
+    See Also
+    --------
+    fft2, ifft
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft2, ifft2
+    >>> y = np.mgrid[:5, :5][0]
+    >>> y
+    array([[0, 0, 0, 0, 0],
+           [1, 1, 1, 1, 1],
+           [2, 2, 2, 2, 2],
+           [3, 3, 3, 3, 3],
+           [4, 4, 4, 4, 4]])
+    >>> np.allclose(y, fft2(ifft2(y)))
+    True
+
+    """
+    return ifftn(x,shape,axes,overwrite_x)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/_helper.py b/venv/lib/python3.10/site-packages/scipy/fftpack/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..7892543732906dcd86b4c1aa9c1f249af701c137
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/_helper.py
@@ -0,0 +1,115 @@
+import operator
+
+import numpy as np
+from numpy.fft import fftshift, ifftshift, fftfreq
+
+import scipy.fft._pocketfft.helper as _helper
+
+__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len']
+
+
+def rfftfreq(n, d=1.0):
+    """DFT sample frequencies (for usage with rfft, irfft).
+
+    The returned float array contains the frequency bins in
+    cycles/unit (with zero at the start) given a window length `n` and a
+    sample spacing `d`::
+
+      f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2]/(d*n)   if n is even
+      f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2,n/2]/(d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing. Default is 1.
+
+    Returns
+    -------
+    out : ndarray
+        The array of length `n`, containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import fftpack
+    >>> sig = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> sig_fft = fftpack.rfft(sig)
+    >>> n = sig_fft.size
+    >>> timestep = 0.1
+    >>> freq = fftpack.rfftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  1.25,  2.5 ,  2.5 ,  3.75,  3.75,  5.  ])
+
+    """
+    n = operator.index(n)
+    if n < 0:
+        raise ValueError(f"n = {n} is not valid. "
+                         "n must be a nonnegative integer.")
+
+    return (np.arange(1, n + 1, dtype=int) // 2) / float(n * d)
+
+
+def next_fast_len(target):
+    """
+    Find the next fast size of input data to `fft`, for zero-padding, etc.
+
+    SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
+    returns the next composite of the prime factors 2, 3, and 5 which is
+    greater than or equal to `target`. (These are also known as 5-smooth
+    numbers, regular numbers, or Hamming numbers.)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+
+    Returns
+    -------
+    out : int
+        The first 5-smooth number greater than or equal to `target`.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 133 ms:
+
+    >>> from scipy import fftpack
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 10007  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fftpack.fft(a)
+
+    Zero-padding to the next 5-smooth length reduces computation time to
+    211 us, a speedup of 630 times:
+
+    >>> fftpack.next_fast_len(min_len)
+    10125
+    >>> b = fftpack.fft(a, 10125)
+
+    Rounding up to the next power of 2 is not optimal, taking 367 us to
+    compute, 1.7 times as long as the 5-smooth size:
+
+    >>> b = fftpack.fft(a, 16384)
+
+    """
+    # Real transforms use regular sizes so this is backwards compatible
+    return _helper.good_size(target, True)
+
+
+def _good_shape(x, shape, axes):
+    """Ensure that shape argument is valid for scipy.fftpack
+
+    scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
+    """
+    if shape is not None and axes is None:
+        shape = _helper._iterable_of_int(shape, 'shape')
+        if len(shape) != np.ndim(x):
+            raise ValueError("when given, axes and shape arguments"
+                             " have to be of the same length")
+    return shape
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py b/venv/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dbcc8d3979b35c1497266fea34cf565cd3d11d7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py
@@ -0,0 +1,554 @@
+"""
+Differential and pseudo-differential operators.
+"""
+# Created by Pearu Peterson, September 2002
+
+__all__ = ['diff',
+           'tilbert','itilbert','hilbert','ihilbert',
+           'cs_diff','cc_diff','sc_diff','ss_diff',
+           'shift']
+
+import threading
+
+from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj
+from . import convolve
+
+from scipy.fft._pocketfft.helper import _datacopied
+
+
+_cache = threading.local()
+
+
+def diff(x,order=1,period=None, _cache=_cache):
+    """
+    Return kth derivative (or integral) of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j
+      y_0 = 0 if order is not 0.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    order : int, optional
+        The order of differentiation. Default order is 1. If order is
+        negative, then integration is carried out under the assumption
+        that ``x_0 == 0``.
+    period : float, optional
+        The assumed period of the sequence. Default is ``2*pi``.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within
+    numerical accuracy).
+
+    For odd order and even ``len(x)``, the Nyquist mode is taken zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'diff_cache'):
+            _cache.diff_cache = {}
+        _cache = _cache.diff_cache
+
+    tmp = asarray(x)
+    if order == 0:
+        return tmp
+    if iscomplexobj(tmp):
+        return diff(tmp.real, order, period, _cache)+1j*diff(
+            tmp.imag, order, period, _cache)
+    if period is not None:
+        c = 2*pi/period
+    else:
+        c = 1.0
+    n = len(x)
+    omega = _cache.get((n,order,c))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,order=order,c=c):
+            if k:
+                return pow(c*k,order)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=order,
+                                                 zero_nyquist=1)
+        _cache[(n,order,c)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=order % 2,
+                             overwrite_x=overwrite_x)
+
+
+def tilbert(x, h, period=None, _cache=_cache):
+    """
+    Return h-Tilbert transform of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+        y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j
+        y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The input array to transform.
+    h : float
+        Defines the parameter of the Tilbert transform.
+    period : float, optional
+        The assumed period of the sequence. Default period is ``2*pi``.
+
+    Returns
+    -------
+    tilbert : ndarray
+        The result of the transform.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then
+    ``tilbert(itilbert(x)) == x``.
+
+    If ``2 * pi * h / period`` is approximately 10 or larger, then
+    numerically ``tilbert == hilbert``
+    (theoretically oo-Tilbert == Hilbert).
+
+    For even ``len(x)``, the Nyquist mode of ``x`` is taken zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'tilbert_cache'):
+            _cache.tilbert_cache = {}
+        _cache = _cache.tilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return tilbert(tmp.real, h, period, _cache) + \
+               1j * tilbert(tmp.imag, h, period, _cache)
+
+    if period is not None:
+        h = h * 2 * pi / period
+
+    n = len(x)
+    omega = _cache.get((n, h))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k, h=h):
+            if k:
+                return 1.0/tanh(h*k)
+
+            return 0
+
+        omega = convolve.init_convolution_kernel(n, kernel, d=1)
+        _cache[(n,h)] = omega
+
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def itilbert(x,h,period=None, _cache=_cache):
+    """
+    Return inverse h-Tilbert transform of a periodic sequence x.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j
+      y_0 = 0
+
+    For more details, see `tilbert`.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'itilbert_cache'):
+            _cache.itilbert_cache = {}
+        _cache = _cache.itilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return itilbert(tmp.real, h, period, _cache) + \
+               1j*itilbert(tmp.imag, h, period, _cache)
+    if period is not None:
+        h = h*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,h))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,h=h):
+            if k:
+                return -tanh(h*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,h)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def hilbert(x, _cache=_cache):
+    """
+    Return Hilbert transform of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sqrt(-1)*sign(j) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The input array, should be periodic.
+    _cache : dict, optional
+        Dictionary that contains the kernel used to do a convolution with.
+
+    Returns
+    -------
+    y : ndarray
+        The transformed input.
+
+    See Also
+    --------
+    scipy.signal.hilbert : Compute the analytic signal, using the Hilbert
+                           transform.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.
+
+    For even len(x), the Nyquist mode of x is taken zero.
+
+    The sign of the returned transform does not have a factor -1 that is more
+    often than not found in the definition of the Hilbert transform. Note also
+    that `scipy.signal.hilbert` does have an extra -1 factor compared to this
+    function.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'hilbert_cache'):
+            _cache.hilbert_cache = {}
+        _cache = _cache.hilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return hilbert(tmp.real, _cache) + 1j * hilbert(tmp.imag, _cache)
+    n = len(x)
+    omega = _cache.get(n)
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k):
+            if k > 0:
+                return 1.0
+            elif k < 0:
+                return -1.0
+            return 0.0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[n] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def ihilbert(x, _cache=_cache):
+    """
+    Return inverse Hilbert transform of a periodic sequence x.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*sign(j) * x_j
+      y_0 = 0
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'ihilbert_cache'):
+            _cache.ihilbert_cache = {}
+        _cache = _cache.ihilbert_cache
+    return -hilbert(x, _cache)
+
+
+def cs_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a, b : float
+        Defines the parameters of the cosh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence. Default period is ``2*pi``.
+
+    Returns
+    -------
+    cs_diff : ndarray
+        Pseudo-derivative of periodic sequence `x`.
+
+    Notes
+    -----
+    For even len(`x`), the Nyquist mode of `x` is taken as zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'cs_diff_cache'):
+            _cache.cs_diff_cache = {}
+        _cache = _cache.cs_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return cs_diff(tmp.real, a, b, period, _cache) + \
+               1j*cs_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return -cosh(a*k)/sinh(b*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def sc_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    a,b : float
+        Defines the parameters of the sinh/cosh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is 2*pi.
+
+    Notes
+    -----
+    ``sc_diff(cs_diff(x,a,b),b,a) == x``
+    For even ``len(x)``, the Nyquist mode of x is taken as zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'sc_diff_cache'):
+            _cache.sc_diff_cache = {}
+        _cache = _cache.sc_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return sc_diff(tmp.real, a, b, period, _cache) + \
+               1j * sc_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return sinh(a*k)/cosh(b*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def ss_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
+      y_0 = a/b * x_0
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a,b
+        Defines the parameters of the sinh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is ``2*pi``.
+
+    Notes
+    -----
+    ``ss_diff(ss_diff(x,a,b),b,a) == x``
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'ss_diff_cache'):
+            _cache.ss_diff_cache = {}
+        _cache = _cache.ss_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return ss_diff(tmp.real, a, b, period, _cache) + \
+               1j*ss_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return sinh(a*k)/sinh(b*k)
+            return float(a)/b
+        omega = convolve.init_convolution_kernel(n,kernel)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
+
+
+def cc_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a,b : float
+        Defines the parameters of the sinh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is ``2*pi``.
+
+    Returns
+    -------
+    cc_diff : ndarray
+        Pseudo-derivative of periodic sequence `x`.
+
+    Notes
+    -----
+    ``cc_diff(cc_diff(x,a,b),b,a) == x``
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'cc_diff_cache'):
+            _cache.cc_diff_cache = {}
+        _cache = _cache.cc_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return cc_diff(tmp.real, a, b, period, _cache) + \
+               1j * cc_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            return cosh(a*k)/cosh(b*k)
+        omega = convolve.init_convolution_kernel(n,kernel)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
+
+
+def shift(x, a, period=None, _cache=_cache):
+    """
+    Shift periodic sequence x by a: y(u) = x(u+a).
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+          y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a : float
+        Defines the parameters of the sinh/sinh pseudo-differential
+    period : float, optional
+        The period of the sequences x and y. Default period is ``2*pi``.
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'shift_cache'):
+            _cache.shift_cache = {}
+        _cache = _cache.shift_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return shift(tmp.real, a, period, _cache) + 1j * shift(
+            tmp.imag, a, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel_real(k,a=a):
+            return cos(a*k)
+
+        def kernel_imag(k,a=a):
+            return sin(a*k)
+        omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0,
+                                                      zero_nyquist=0)
+        omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1,
+                                                      zero_nyquist=0)
+        _cache[(n,a)] = omega_real,omega_imag
+    else:
+        omega_real,omega_imag = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve_z(tmp,omega_real,omega_imag,
+                               overwrite_x=overwrite_x)
+
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py b/venv/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad71d517b0ac829ab71850bf67f7dc38636161f2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py
@@ -0,0 +1,598 @@
+"""
+Real spectrum transforms (DCT, DST, MDCT)
+"""
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+from scipy.fft import _pocketfft
+from ._helper import _good_shape
+
+_inverse_typemap = {1: 1, 2: 3, 3: 2, 4: 4}
+
+
+def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the DCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idctn : Inverse multidimensional DCT
+
+    Notes
+    -----
+    For full details of the DCT types and normalization modes, as well as
+    references, see `dct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
+
+
+def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the IDCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dctn : multidimensional DCT
+
+    Notes
+    -----
+    For full details of the IDCT types and normalization modes, as well as
+    references, see `idct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    type = _inverse_typemap[type]
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
+
+
+def dstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the DCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idstn : Inverse multidimensional DST
+
+    Notes
+    -----
+    For full details of the DST types and normalization modes, as well as
+    references, see `dst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
+
+
+def idstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the IDST is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dstn : multidimensional DST
+
+    Notes
+    -----
+    For full details of the IDST types and normalization modes, as well as
+    references, see `idst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    type = _inverse_typemap[type]
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    r"""
+    Return the Discrete Cosine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idct : Inverse DCT
+
+    Notes
+    -----
+    For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
+    MATLAB ``dct(x)``.
+
+    There are, theoretically, 8 types of the DCT, only the first 4 types are
+    implemented in scipy. 'The' DCT generally refers to DCT type 2, and 'the'
+    Inverse DCT generally refers to DCT type 3.
+
+    **Type I**
+
+    There are several definitions of the DCT-I; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
+       \frac{\pi k n}{N-1} \right)
+
+    If ``norm='ortho'``, ``x[0]`` and ``x[N-1]`` are multiplied by a scaling
+    factor of :math:`\sqrt{2}`, and ``y[k]`` is multiplied by a scaling factor
+    ``f``
+
+    .. math::
+
+        f = \begin{cases}
+         \frac{1}{2}\sqrt{\frac{1}{N-1}} & \text{if }k=0\text{ or }N-1, \\
+         \frac{1}{2}\sqrt{\frac{2}{N-1}} & \text{otherwise} \end{cases}
+
+    .. versionadded:: 1.2.0
+       Orthonormalization in DCT-I.
+
+    .. note::
+       The DCT-I is only supported for input size > 1.
+
+    **Type II**
+
+    There are several definitions of the DCT-II; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+       f = \begin{cases}
+       \sqrt{\frac{1}{4N}} & \text{if }k=0, \\
+       \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
+
+    which makes the corresponding matrix of coefficients orthonormal
+    (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions, we use the following (for ``norm=None``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    or, for ``norm='ortho'``
+
+    .. math::
+
+       y_k = \frac{x_0}{\sqrt{N}} + \sqrt{\frac{2}{N}} \sum_{n=1}^{N-1} x_n
+       \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
+    to a factor ``2N``. The orthonormalized DCT-III is exactly the inverse of
+    the orthonormalized DCT-II.
+
+    **Type IV**
+
+    There are several definitions of the DCT-IV; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+
+        f = \frac{1}{\sqrt{2N}}
+
+    .. versionadded:: 1.2.0
+       Support for DCT-IV.
+
+    References
+    ----------
+    .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
+           Makhoul, `IEEE Transactions on acoustics, speech and signal
+           processing` vol. 28(1), pp. 27-34,
+           :doi:`10.1109/TASSP.1980.1163351` (1980).
+    .. [2] Wikipedia, "Discrete cosine transform",
+           https://en.wikipedia.org/wiki/Discrete_cosine_transform
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the FFT (though faster) for real,
+    even-symmetrical inputs. The output is also real and even-symmetrical.
+    Half of the FFT input is used to generate half of the FFT output:
+
+    >>> from scipy.fftpack import fft, dct
+    >>> import numpy as np
+    >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
+    array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])
+    >>> dct(np.array([4., 3., 5., 10.]), 1)
+    array([ 30.,  -8.,   6.,  -2.])
+
+    """
+    return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    """
+    Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    idct : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dct : Forward DCT
+
+    Notes
+    -----
+    For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
+    MATLAB ``idct(x)``.
+
+    'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
+
+    IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
+    3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
+    of type 4. For the definition of these types, see `dct`.
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
+    inputs. The output is also real and even-symmetrical. Half of the IFFT
+    input is used to generate half of the IFFT output:
+
+    >>> from scipy.fftpack import ifft, idct
+    >>> import numpy as np
+    >>> ifft(np.array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])).real
+    array([  4.,   3.,   5.,  10.,   5.,   3.])
+    >>> idct(np.array([ 30.,  -8.,   6.,  -2.]), 1) / 6
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    type = _inverse_typemap[type]
+    return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    r"""
+    Return the Discrete Sine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    For a single dimension array ``x``.
+
+    There are, theoretically, 8 types of the DST for different combinations of
+    even/odd boundary conditions and boundary off sets [1]_, only the first
+    4 types are implemented in scipy.
+
+    **Type I**
+
+    There are several definitions of the DST-I; we use the following
+    for ``norm=None``. DST-I assumes the input is odd around `n=-1` and `n=N`.
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
+
+    Note that the DST-I is only supported for input size > 1.
+    The (unnormalized) DST-I is its own inverse, up to a factor ``2(N+1)``.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm=None``. DST-II assumes the input is odd around `n=-1/2` and
+    `n=N-1/2`; the output is odd around :math:`k=-1` and even around `k=N-1`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
+
+    if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+
+        f = \begin{cases}
+        \sqrt{\frac{1}{4N}} & \text{if }k = 0, \\
+        \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm=None``). DST-III assumes the input is odd around `n=-1` and even
+    around `n=N-1`
+
+    .. math::
+
+        y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
+        \frac{\pi(2k+1)(n+1)}{2N}\right)
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor ``2N``. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    .. versionadded:: 0.11.0
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm=None``). DST-IV assumes the input is odd around `n=-0.5` and even
+    around `n=N-0.5`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor ``2N``. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    .. versionadded:: 1.2.0
+       Support for DST-IV.
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    """
+    Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+
+    Notes
+    -----
+    'The' IDST is the IDST of type 2, which is the same as DST of type 3.
+
+    IDST of type 1 is the DST of type 1, IDST of type 2 is the DST of type
+    3, and IDST of type 3 is the DST of type 2. For the definition of these
+    types, see `dst`.
+
+    .. versionadded:: 0.11.0
+
+    """
+    type = _inverse_typemap[type]
+    return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/basic.py b/venv/lib/python3.10/site-packages/scipy/fftpack/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..553f456fe1561c28928ecc4ebe2238459cc60443
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/basic.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'fft','ifft','fftn','ifftn','rfft','irfft',
+    'fft2','ifft2'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="basic",
+                                   private_modules=["_basic"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/helper.py b/venv/lib/python3.10/site-packages/scipy/fftpack/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcc7000c215f8a7605a2a59b5767b27b2fcd969d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/helper.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.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="helper",
+                                   private_modules=["_helper"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py b/venv/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecf71ad3256d48d2131c8058072da724cb001af9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.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.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'diff',
+    'tilbert', 'itilbert', 'hilbert', 'ihilbert',
+    'cs_diff', 'cc_diff', 'sc_diff', 'ss_diff',
+    'shift', 'convolve'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="pseudo_diffs",
+                                   private_modules=["_pseudo_diffs"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py b/venv/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a392198fccf213bc988a79058bd69515e39f510
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/realtransforms.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.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="realtransforms",
+                                   private_modules=["_realtransforms"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebb5398fa9904b4f36481a02a562347f14290fac
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25af493e15347706fd477e9d705f76e7019014b1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a28f25cfc5a710601cd4f052c3bd90a52ea4151a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce016b6dd0dc6a4a280505b34de2f8f4b0951fb2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..077e4dbcd1f1d1457035a051e537433b42335899
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a5e2a5778cc9dbae57587e13ea6176ce4c57c17
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..2951471d2abb5c4a88ae0b44c172d3ecc0862d4d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py
@@ -0,0 +1,879 @@
+# Created by Pearu Peterson, September 2002
+
+from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
+                           assert_array_almost_equal_nulp, assert_array_less)
+import pytest
+from pytest import raises as assert_raises
+from scipy.fftpack import ifft, fft, fftn, ifftn, rfft, irfft, fft2
+
+from numpy import (arange, array, asarray, zeros, dot, exp, pi,
+                   swapaxes, double, cdouble)
+import numpy as np
+import numpy.fft
+from numpy.random import rand
+
+# "large" composite numbers supported by FFTPACK
+LARGE_COMPOSITE_SIZES = [
+    2**13,
+    2**5 * 3**5,
+    2**3 * 3**3 * 5**2,
+]
+SMALL_COMPOSITE_SIZES = [
+    2,
+    2*3*5,
+    2*2*3*3,
+]
+# prime
+LARGE_PRIME_SIZES = [
+    2011
+]
+SMALL_PRIME_SIZES = [
+    29
+]
+
+
+def _assert_close_in_norm(x, y, rtol, size, rdt):
+    # helper function for testing
+    err_msg = f"size: {size}  rdt: {rdt}"
+    assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
+
+
+def random(size):
+    return rand(*size)
+
+
+def direct_dft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = -arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)
+    return y
+
+
+def direct_idft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)/n
+    return y
+
+
+def direct_dftn(x):
+    x = asarray(x)
+    for axis in range(len(x.shape)):
+        x = fft(x, axis=axis)
+    return x
+
+
+def direct_idftn(x):
+    x = asarray(x)
+    for axis in range(len(x.shape)):
+        x = ifft(x, axis=axis)
+    return x
+
+
+def direct_rdft(x):
+    x = asarray(x)
+    n = len(x)
+    w = -arange(n)*(2j*pi/n)
+    r = zeros(n, dtype=double)
+    for i in range(n//2+1):
+        y = dot(exp(i*w), x)
+        if i:
+            r[2*i-1] = y.real
+            if 2*i < n:
+                r[2*i] = y.imag
+        else:
+            r[0] = y.real
+    return r
+
+
+def direct_irdft(x):
+    x = asarray(x)
+    n = len(x)
+    x1 = zeros(n, dtype=cdouble)
+    for i in range(n//2+1):
+        if i:
+            if 2*i < n:
+                x1[i] = x[2*i-1] + 1j*x[2*i]
+                x1[n-i] = x[2*i-1] - 1j*x[2*i]
+            else:
+                x1[i] = x[2*i-1]
+        else:
+            x1[0] = x[0]
+    return direct_idft(x1).real
+
+
+class _TestFFTBase:
+    def setup_method(self):
+        self.cdt = None
+        self.rdt = None
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
+        y = fft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_dft(x)
+        assert_array_almost_equal(y,y1)
+        x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
+        assert_array_almost_equal(fft(x),direct_dft(x))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1,2,3,4], dtype=self.rdt)
+        x2 = np.array([1,2,3,4], dtype=self.rdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def _test_n_argument_complex(self):
+        x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, fft, [])
+        assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
+
+
+class TestDoubleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestSingleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+    reason = ("single-precision FFT implementation is partially disabled, "
+              "until accuracy issues with large prime powers are resolved")
+
+    @pytest.mark.xfail(run=False, reason=reason)
+    def test_notice(self):
+        pass
+
+
+class TestFloat16FFT:
+
+    def test_1_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft(x1, n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (4, ))
+        assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        x2 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft([x1, x2], n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (2, 4))
+        assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
+        assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
+
+
+class _TestIFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
+        y = ifft(x)
+        y1 = direct_idft(x)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4+0j,5], self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_definition_real(self):
+        x = np.array([1,2,3,4,1,2,3,4], self.rdt)
+        y = ifft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_idft(x)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4,5], dtype=self.rdt)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_random_complex(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.cdt)
+            x = random([size]).astype(self.cdt) + 1j*x
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        if self.rdt == np.float32:
+            rtol = 1e-5
+        elif self.rdt == np.float64:
+            rtol = 1e-10
+
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+            x = (x + 1j*np.random.rand(size)).astype(self.cdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, ifft, [])
+        assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
+
+
+class TestDoubleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestSingleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class _TestRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
+            x = np.array(t, dtype=self.rdt)
+            y = rfft(x)
+            y1 = direct_rdft(x)
+            assert_array_almost_equal(y,y1)
+            assert_equal(y.dtype, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, rfft, [])
+        assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
+
+    # See gh-5790
+    class MockSeries:
+        def __init__(self, data):
+            self.data = np.asarray(data)
+
+        def __getattr__(self, item):
+            try:
+                return getattr(self.data, item)
+            except AttributeError as e:
+                raise AttributeError("'MockSeries' object "
+                                      f"has no attribute '{item}'") from e
+
+    def test_non_ndarray_with_dtype(self):
+        x = np.array([1., 2., 3., 4., 5.])
+        xs = _TestRFFTBase.MockSeries(x)
+
+        expected = [1, 2, 3, 4, 5]
+        rfft(xs)
+
+        # Data should not have been overwritten
+        assert_equal(x, expected)
+        assert_equal(xs.data, expected)
+
+    def test_complex_input(self):
+        assert_raises(TypeError, rfft, np.arange(4, dtype=np.complex64))
+
+
+class TestRFFTDouble(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestRFFTSingle(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class _TestIRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x1 = [1,2,3,4,1,2,3,4]
+        x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
+        x2 = [1,2,3,4,1,2,3,4,5]
+        x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
+
+        def _test(x, xr):
+            y = irfft(np.array(x, dtype=self.rdt))
+            y1 = direct_irdft(x)
+            assert_equal(y.dtype, self.rdt)
+            assert_array_almost_equal(y,y1, decimal=self.ndec)
+            assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
+
+        _test(x1, x1_1)
+        _test(x2, x2_1)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = irfft(rfft(x))
+            y2 = rfft(irfft(x))
+            assert_equal(y1.dtype, self.rdt)
+            assert_equal(y2.dtype, self.rdt)
+            assert_array_almost_equal(y1, x, decimal=self.ndec,
+                                       err_msg="size=%d" % size)
+            assert_array_almost_equal(y2, x, decimal=self.ndec,
+                                       err_msg="size=%d" % size)
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        if self.rdt == np.float32:
+            rtol = 1e-5
+        elif self.rdt == np.float64:
+            rtol = 1e-10
+
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = irfft(rfft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = rfft(irfft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, irfft, [])
+        assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
+
+    def test_complex_input(self):
+        assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
+
+
+# self.ndec is bogus; we should have a assert_array_approx_equal for number of
+# significant digits
+
+class TestIRFFTDouble(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.ndec = 14
+
+
+class TestIRFFTSingle(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+        self.ndec = 5
+
+
+class Testfft2:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_regression_244(self):
+        """FFT returns wrong result with axes parameter."""
+        # fftn (and hence fft2) used to break when both axes and shape were
+        # used
+        x = numpy.ones((4, 4, 2))
+        y = fft2(x, shape=(8, 8), axes=(-3, -2))
+        y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
+        assert_array_almost_equal(y, y_r)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, fft2, [[]])
+        assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
+
+
+class TestFftnSingle:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float32))
+        assert_(y.dtype == np.complex64,
+                msg="double precision output with single precision")
+
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_size_accuracy_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j*rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_size_accuracy_large(self, size):
+        rand = np.random.default_rng(1234)
+        x = rand.random((size, 3)) + 1j*rand.random((size, 3))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    def test_definition_float16(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float16))
+        assert_equal(y.dtype, np.complex64)
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_float16_input_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j * rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 5e5)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_float16_input_large(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, 3)) + 1j*rng.random((size, 3))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2e6)
+
+
+class TestFftn:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(x)
+        assert_array_almost_equal(y, direct_dftn(x))
+
+        x = random((20, 26))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+        x = random((5, 4, 3, 20))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+    def test_axes_argument(self):
+        # plane == ji_plane, x== kji_space
+        plane1 = [[1, 2, 3],
+                  [4, 5, 6],
+                  [7, 8, 9]]
+        plane2 = [[10, 11, 12],
+                  [13, 14, 15],
+                  [16, 17, 18]]
+        plane3 = [[19, 20, 21],
+                  [22, 23, 24],
+                  [25, 26, 27]]
+        ki_plane1 = [[1, 2, 3],
+                     [10, 11, 12],
+                     [19, 20, 21]]
+        ki_plane2 = [[4, 5, 6],
+                     [13, 14, 15],
+                     [22, 23, 24]]
+        ki_plane3 = [[7, 8, 9],
+                     [16, 17, 18],
+                     [25, 26, 27]]
+        jk_plane1 = [[1, 10, 19],
+                     [4, 13, 22],
+                     [7, 16, 25]]
+        jk_plane2 = [[2, 11, 20],
+                     [5, 14, 23],
+                     [8, 17, 26]]
+        jk_plane3 = [[3, 12, 21],
+                     [6, 15, 24],
+                     [9, 18, 27]]
+        kj_plane1 = [[1, 4, 7],
+                     [10, 13, 16], [19, 22, 25]]
+        kj_plane2 = [[2, 5, 8],
+                     [11, 14, 17], [20, 23, 26]]
+        kj_plane3 = [[3, 6, 9],
+                     [12, 15, 18], [21, 24, 27]]
+        ij_plane1 = [[1, 4, 7],
+                     [2, 5, 8],
+                     [3, 6, 9]]
+        ij_plane2 = [[10, 13, 16],
+                     [11, 14, 17],
+                     [12, 15, 18]]
+        ij_plane3 = [[19, 22, 25],
+                     [20, 23, 26],
+                     [21, 24, 27]]
+        ik_plane1 = [[1, 10, 19],
+                     [2, 11, 20],
+                     [3, 12, 21]]
+        ik_plane2 = [[4, 13, 22],
+                     [5, 14, 23],
+                     [6, 15, 24]]
+        ik_plane3 = [[7, 16, 25],
+                     [8, 17, 26],
+                     [9, 18, 27]]
+        ijk_space = [jk_plane1, jk_plane2, jk_plane3]
+        ikj_space = [kj_plane1, kj_plane2, kj_plane3]
+        jik_space = [ik_plane1, ik_plane2, ik_plane3]
+        jki_space = [ki_plane1, ki_plane2, ki_plane3]
+        kij_space = [ij_plane1, ij_plane2, ij_plane3]
+        x = array([plane1, plane2, plane3])
+
+        assert_array_almost_equal(fftn(x),
+                                  fftn(x, axes=(-3, -2, -1)))  # kji_space
+        assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
+        assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
+        y = fftn(x, axes=(2, 1, 0))  # ijk_space
+        assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
+        y = fftn(x, axes=(2, 0, 1))  # ikj_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
+                                  fftn(ikj_space))
+        y = fftn(x, axes=(1, 2, 0))  # jik_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
+                                  fftn(jik_space))
+        y = fftn(x, axes=(1, 0, 2))  # jki_space
+        assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
+        y = fftn(x, axes=(0, 2, 1))  # kij_space
+        assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
+
+        y = fftn(x, axes=(-2, -1))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(1, 2))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(-3, -2))  # kj_plane
+        assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
+        assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
+        assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
+
+        y = fftn(x, axes=(-3, -1))  # ki_plane
+        assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
+        assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
+        assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
+
+        y = fftn(x, axes=(-1, -2))  # ij_plane
+        assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
+
+        y = fftn(x, axes=(-1, -3))  # ik_plane
+        assert_array_almost_equal(fftn(ik_plane1),
+                                  swapaxes(y[:, 0, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane2),
+                                  swapaxes(y[:, 1, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane3),
+                                  swapaxes(y[:, 2, :], -1, -2))
+
+        y = fftn(x, axes=(-2, -3))  # jk_plane
+        assert_array_almost_equal(fftn(jk_plane1),
+                                  swapaxes(y[:, :, 0], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane2),
+                                  swapaxes(y[:, :, 1], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane3),
+                                  swapaxes(y[:, :, 2], -1, -2))
+
+        y = fftn(x, axes=(-1,))  # i_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
+        y = fftn(x, axes=(-2,))  # j_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
+        y = fftn(x, axes=(0,))  # k_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
+
+        y = fftn(x, axes=())  # point
+        assert_array_almost_equal(y, x)
+
+    def test_shape_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6]]
+        large_x1 = [[1, 2, 3, 0],
+                    [4, 5, 6, 0],
+                    [0, 0, 0, 0],
+                    [0, 0, 0, 0]]
+
+        y = fftn(small_x, shape=(4, 4))
+        assert_array_almost_equal(y, fftn(large_x1))
+
+        y = fftn(small_x, shape=(3, 4))
+        assert_array_almost_equal(y, fftn(large_x1[:-1]))
+
+    def test_shape_axes_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6],
+                   [7, 8, 9]]
+        large_x1 = array([[1, 2, 3, 0],
+                          [4, 5, 6, 0],
+                          [7, 8, 9, 0],
+                          [0, 0, 0, 0]])
+        y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
+        assert_array_almost_equal(y, fftn(large_x1))
+        y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
+
+        assert_array_almost_equal(y, swapaxes(
+            fftn(swapaxes(large_x1, -1, -2)), -1, -2))
+
+    def test_shape_axes_argument2(self):
+        # Change shape of the last axis
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-1,), shape=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-1, n=8))
+
+        # Change shape of an arbitrary axis which is not the last one
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-2,), shape=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-2, n=8))
+
+        # Change shape of axes: cf #244, where shape and axes were mixed up
+        x = numpy.random.random((4, 4, 2))
+        y = fftn(x, axes=(-3, -2), shape=(8, 8))
+        assert_array_almost_equal(y,
+                                  numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
+
+    def test_shape_argument_more(self):
+        x = zeros((4, 4, 2))
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fftn(x, shape=(8, 8, 2, 1))
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            fftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            fftn([[1, 1], [2, 2]], (4, -3))
+
+
+class TestIfftn:
+    dtype = None
+    cdtype = None
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+                             [(np.float64, np.complex128, 2000),
+                              (np.float32, np.complex64, 3500)])
+    def test_definition(self, dtype, cdtype, maxnlp):
+        rng = np.random.default_rng(1234)
+        x = np.array([[1, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]], dtype=dtype)
+        y = ifftn(x)
+        assert_equal(y.dtype, cdtype)
+        assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
+
+        x = rng.random((20, 26))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+        x = rng.random((5, 4, 3, 20))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+    @pytest.mark.parametrize('maxnlp', [2000, 3500])
+    @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+    def test_random_complex(self, maxnlp, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random([size, size]) + 1j * rng.random([size, size])
+        assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
+        assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            ifftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            ifftn([[1, 1], [2, 2]], (4, -3))
+
+
+class FakeArray:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+class FakeArray2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        return self._data
+
+
+class TestOverwrite:
+    """Check input overwrite behavior of the FFT functions."""
+
+    real_dtypes = (np.float32, np.float64)
+    dtypes = real_dtypes + (np.complex64, np.complex128)
+    fftsizes = [8, 16, 32]
+
+    def _check(self, x, routine, fftsize, axis, overwrite_x):
+        x2 = x.copy()
+        for fake in [lambda x: x, FakeArray, FakeArray2]:
+            routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
+
+            sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+                   f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+            if not overwrite_x:
+                assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
+                  fftsize, overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        self._check(data, routine, fftsize, axis,
+                    overwrite_x=overwrite_x)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = (np.complex128, np.complex64)
+        self._check_1d(fft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(ifft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    @pytest.mark.parametrize('dtype', real_dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = self.real_dtypes
+        self._check_1d(irfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(rfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
+                      overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        def fftshape_iter(shp):
+            if len(shp) <= 0:
+                yield ()
+            else:
+                for j in (shp[0]//2, shp[0], shp[0]*2):
+                    for rest in fftshape_iter(shp[1:]):
+                        yield (j,) + rest
+
+        if axes is None:
+            part_shape = shape
+        else:
+            part_shape = tuple(np.take(shape, axes))
+
+        for fftshape in fftshape_iter(part_shape):
+            self._check(data, routine, fftshape, axes,
+                        overwrite_x=overwrite_x)
+            if data.ndim > 1:
+                self._check(data.T, routine, fftshape, axes,
+                            overwrite_x=overwrite_x)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), None),
+                                            ((16,), (0,)),
+                                            ((16, 2), (0,)),
+                                            ((2, 16), (1,)),
+                                            ((8, 16), None),
+                                            ((8, 16), (0, 1)),
+                                            ((8, 16, 2), (0, 1)),
+                                            ((8, 16, 2), (1, 2)),
+                                            ((8, 16, 2), (0,)),
+                                            ((8, 16, 2), (1,)),
+                                            ((8, 16, 2), (2,)),
+                                            ((8, 16, 2), None),
+                                            ((8, 16, 2), (0, 1, 2))])
+    def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
+        overwritable = (np.complex128, np.complex64)
+        self._check_nd_one(fftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+        self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+
+
+@pytest.mark.parametrize('func', [fftn, ifftn, fft2])
+def test_shape_axes_ndarray(func):
+    # Test fftn and ifftn work with NumPy arrays for shape and axes arguments
+    # Regression test for gh-13342
+    a = np.random.rand(10, 10)
+
+    expect = func(a, shape=(5, 5))
+    actual = func(a, shape=np.array([5, 5]))
+    assert_equal(expect, actual)
+
+    expect = func(a, axes=(-1,))
+    actual = func(a, axes=np.array([-1,]))
+    assert_equal(expect, actual)
+
+    expect = func(a, shape=(4, 7), axes=(1, 0))
+    actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0]))
+    assert_equal(expect, actual)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e7be04f3c0291502b50b101db82d299aadc7772
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py
@@ -0,0 +1,54 @@
+# Created by Pearu Peterson, September 2002
+
+__usage__ = """
+Build fftpack:
+  python setup_fftpack.py build
+Run tests if scipy is installed:
+  python -c 'import scipy;scipy.fftpack.test()'
+Run tests if fftpack is not installed:
+  python tests/test_helper.py []
+"""
+
+from numpy.testing import assert_array_almost_equal
+from scipy.fftpack import fftshift, ifftshift, fftfreq, rfftfreq
+
+from numpy import pi, random
+
+class TestFFTShift:
+
+    def test_definition(self):
+        x = [0,1,2,3,4,-4,-3,-2,-1]
+        y = [-4,-3,-2,-1,0,1,2,3,4]
+        assert_array_almost_equal(fftshift(x),y)
+        assert_array_almost_equal(ifftshift(y),x)
+        x = [0,1,2,3,4,-5,-4,-3,-2,-1]
+        y = [-5,-4,-3,-2,-1,0,1,2,3,4]
+        assert_array_almost_equal(fftshift(x),y)
+        assert_array_almost_equal(ifftshift(y),x)
+
+    def test_inverse(self):
+        for n in [1,4,9,100,211]:
+            x = random.random((n,))
+            assert_array_almost_equal(ifftshift(fftshift(x)),x)
+
+
+class TestFFTFreq:
+
+    def test_definition(self):
+        x = [0,1,2,3,4,-4,-3,-2,-1]
+        assert_array_almost_equal(9*fftfreq(9),x)
+        assert_array_almost_equal(9*pi*fftfreq(9,pi),x)
+        x = [0,1,2,3,4,-5,-4,-3,-2,-1]
+        assert_array_almost_equal(10*fftfreq(10),x)
+        assert_array_almost_equal(10*pi*fftfreq(10,pi),x)
+
+
+class TestRFFTFreq:
+
+    def test_definition(self):
+        x = [0,1,1,2,2,3,3,4,4]
+        assert_array_almost_equal(9*rfftfreq(9),x)
+        assert_array_almost_equal(9*pi*rfftfreq(9,pi),x)
+        x = [0,1,1,2,2,3,3,4,4,5]
+        assert_array_almost_equal(10*rfftfreq(10),x)
+        assert_array_almost_equal(10*pi*rfftfreq(10,pi),x)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..e71aec9bd07cd4ef486b7e74b9589b6f1634d629
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py
@@ -0,0 +1,33 @@
+"""Test possibility of patching fftpack with pyfftw.
+
+No module source outside of scipy.fftpack should contain an import of
+the form `from scipy.fftpack import ...`, so that a simple replacement
+of scipy.fftpack by the corresponding fftw interface completely swaps
+the two FFT implementations.
+
+Because this simply inspects source files, we only need to run the test
+on one version of Python.
+"""
+
+
+from pathlib import Path
+import re
+import tokenize
+import pytest
+from numpy.testing import assert_
+import scipy
+
+class TestFFTPackImport:
+    @pytest.mark.slow
+    def test_fftpack_import(self):
+        base = Path(scipy.__file__).parent
+        regexp = r"\s*from.+\.fftpack import .*\n"
+        for path in base.rglob("*.py"):
+            if base / "fftpack" in path.parents:
+                continue
+            # use tokenize to auto-detect encoding on systems where no
+            # default encoding is defined (e.g., LANG='C')
+            with tokenize.open(str(path)) as file:
+                assert_(all(not re.fullmatch(regexp, line)
+                            for line in file),
+                        f"{path} contains an import from fftpack")
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a92729626a280c12aa3197e99b0d58ce00812d9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
@@ -0,0 +1,388 @@
+# Created by Pearu Peterson, September 2002
+
+__usage__ = """
+Build fftpack:
+  python setup_fftpack.py build
+Run tests if scipy is installed:
+  python -c 'import scipy;scipy.fftpack.test()'
+Run tests if fftpack is not installed:
+  python tests/test_pseudo_diffs.py []
+"""
+
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_array_almost_equal)
+from scipy.fftpack import (diff, fft, ifft, tilbert, itilbert, hilbert,
+                           ihilbert, shift, fftfreq, cs_diff, sc_diff,
+                           ss_diff, cc_diff)
+
+import numpy as np
+from numpy import arange, sin, cos, pi, exp, tanh, sum, sign
+from numpy.random import random
+
+
+def direct_diff(x,k=1,period=None):
+    fx = fft(x)
+    n = len(fx)
+    if period is None:
+        period = 2*pi
+    w = fftfreq(n)*2j*pi/period*n
+    if k < 0:
+        w = 1 / w**k
+        w[0] = 0.0
+    else:
+        w = w**k
+    if n > 2000:
+        w[250:n-250] = 0.0
+    return ifft(w*fx).real
+
+
+def direct_tilbert(x,h=1,period=None):
+    fx = fft(x)
+    n = len(fx)
+    if period is None:
+        period = 2*pi
+    w = fftfreq(n)*h*2*pi/period*n
+    w[0] = 1
+    w = 1j/tanh(w)
+    w[0] = 0j
+    return ifft(w*fx)
+
+
+def direct_itilbert(x,h=1,period=None):
+    fx = fft(x)
+    n = len(fx)
+    if period is None:
+        period = 2*pi
+    w = fftfreq(n)*h*2*pi/period*n
+    w = -1j*tanh(w)
+    return ifft(w*fx)
+
+
+def direct_hilbert(x):
+    fx = fft(x)
+    n = len(fx)
+    w = fftfreq(n)*n
+    w = 1j*sign(w)
+    return ifft(w*fx)
+
+
+def direct_ihilbert(x):
+    return -direct_hilbert(x)
+
+
+def direct_shift(x,a,period=None):
+    n = len(x)
+    if period is None:
+        k = fftfreq(n)*1j*n
+    else:
+        k = fftfreq(n)*2j*pi/period*n
+    return ifft(fft(x)*exp(k*a)).real
+
+
+class TestDiff:
+
+    def test_definition(self):
+        for n in [16,17,64,127,32]:
+            x = arange(n)*2*pi/n
+            assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x)))
+            assert_array_almost_equal(diff(sin(x),2),direct_diff(sin(x),2))
+            assert_array_almost_equal(diff(sin(x),3),direct_diff(sin(x),3))
+            assert_array_almost_equal(diff(sin(x),4),direct_diff(sin(x),4))
+            assert_array_almost_equal(diff(sin(x),5),direct_diff(sin(x),5))
+            assert_array_almost_equal(diff(sin(2*x),3),direct_diff(sin(2*x),3))
+            assert_array_almost_equal(diff(sin(2*x),4),direct_diff(sin(2*x),4))
+            assert_array_almost_equal(diff(cos(x)),direct_diff(cos(x)))
+            assert_array_almost_equal(diff(cos(x),2),direct_diff(cos(x),2))
+            assert_array_almost_equal(diff(cos(x),3),direct_diff(cos(x),3))
+            assert_array_almost_equal(diff(cos(x),4),direct_diff(cos(x),4))
+            assert_array_almost_equal(diff(cos(2*x)),direct_diff(cos(2*x)))
+            assert_array_almost_equal(diff(sin(x*n/8)),direct_diff(sin(x*n/8)))
+            assert_array_almost_equal(diff(cos(x*n/8)),direct_diff(cos(x*n/8)))
+            for k in range(5):
+                assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k))
+                assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k))
+
+    def test_period(self):
+        for n in [17,64]:
+            x = arange(n)/float(n)
+            assert_array_almost_equal(diff(sin(2*pi*x),period=1),
+                                      2*pi*cos(2*pi*x))
+            assert_array_almost_equal(diff(sin(2*pi*x),3,period=1),
+                                      -(2*pi)**3*cos(2*pi*x))
+
+    def test_sin(self):
+        for n in [32,64,77]:
+            x = arange(n)*2*pi/n
+            assert_array_almost_equal(diff(sin(x)),cos(x))
+            assert_array_almost_equal(diff(cos(x)),-sin(x))
+            assert_array_almost_equal(diff(sin(x),2),-sin(x))
+            assert_array_almost_equal(diff(sin(x),4),sin(x))
+            assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x))
+            assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x)))
+
+    def test_expr(self):
+        for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]:
+            x = arange(n)*2*pi/n
+            f = sin(x)*cos(4*x)+exp(sin(3*x))
+            df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
+            ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
+                 - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
+            d1 = diff(f)
+            assert_array_almost_equal(d1,df)
+            assert_array_almost_equal(diff(df),ddf)
+            assert_array_almost_equal(diff(f,2),ddf)
+            assert_array_almost_equal(diff(ddf,-1),df)
+
+    def test_expr_large(self):
+        for n in [2048,4096]:
+            x = arange(n)*2*pi/n
+            f = sin(x)*cos(4*x)+exp(sin(3*x))
+            df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
+            ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
+                 - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
+            assert_array_almost_equal(diff(f),df)
+            assert_array_almost_equal(diff(df),ddf)
+            assert_array_almost_equal(diff(ddf,-1),df)
+            assert_array_almost_equal(diff(f,2),ddf)
+
+    def test_int(self):
+        n = 64
+        x = arange(n)*2*pi/n
+        assert_array_almost_equal(diff(sin(x),-1),-cos(x))
+        assert_array_almost_equal(diff(sin(x),-2),-sin(x))
+        assert_array_almost_equal(diff(sin(x),-4),sin(x))
+        assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x))
+
+    def test_random_even(self):
+        rng = np.random.default_rng(1234)
+        for k in [0,2,4,6]:
+            for n in [60,32,64,56,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                # zeroing Nyquist mode:
+                f = diff(diff(f,1),-1)
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(diff(diff(f,k),-k),f)
+                assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+    def test_random_odd(self):
+        rng = np.random.default_rng(1234)
+        for k in [0,1,2,3,4,5,6]:
+            for n in [33,65,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(diff(diff(f,k),-k),f)
+                assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+    def test_zero_nyquist(self):
+        rng = np.random.default_rng(1234)
+        for k in [0,1,2,3,4,5,6]:
+            for n in [32,33,64,56,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                # zeroing Nyquist mode:
+                f = diff(diff(f,1),-1)
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(diff(diff(f,k),-k),f)
+                assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+
+class TestTilbert:
+
+    def test_definition(self):
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [16,17,64,127]:
+                x = arange(n)*2*pi/n
+                y = tilbert(sin(x),h)
+                y1 = direct_tilbert(sin(x),h)
+                assert_array_almost_equal(y,y1)
+                assert_array_almost_equal(tilbert(sin(x),h),
+                                          direct_tilbert(sin(x),h))
+                assert_array_almost_equal(tilbert(sin(2*x),h),
+                                          direct_tilbert(sin(2*x),h))
+
+    def test_random_even(self):
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [32,64,56]:
+                f = random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f)
+
+    def test_random_odd(self):
+        rng = np.random.default_rng(1234)
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [33,65,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(itilbert(tilbert(f,h),h),f)
+                assert_array_almost_equal(tilbert(itilbert(f,h),h),f)
+
+
+class TestITilbert:
+
+    def test_definition(self):
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [16,17,64,127]:
+                x = arange(n)*2*pi/n
+                y = itilbert(sin(x),h)
+                y1 = direct_itilbert(sin(x),h)
+                assert_array_almost_equal(y,y1)
+                assert_array_almost_equal(itilbert(sin(x),h),
+                                          direct_itilbert(sin(x),h))
+                assert_array_almost_equal(itilbert(sin(2*x),h),
+                                          direct_itilbert(sin(2*x),h))
+
+
+class TestHilbert:
+
+    def test_definition(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            y = hilbert(sin(x))
+            y1 = direct_hilbert(sin(x))
+            assert_array_almost_equal(y,y1)
+            assert_array_almost_equal(hilbert(sin(2*x)),
+                                      direct_hilbert(sin(2*x)))
+
+    def test_tilbert_relation(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            f = sin(x)+cos(2*x)*sin(x)
+            y = hilbert(f)
+            y1 = direct_hilbert(f)
+            assert_array_almost_equal(y,y1)
+            y2 = tilbert(f,h=10)
+            assert_array_almost_equal(y,y2)
+
+    def test_random_odd(self):
+        rng = np.random.default_rng(1234)
+        for n in [33,65,55]:
+            f = rng.random((n,))
+            af = sum(f,axis=0)/n
+            f = f-af
+            assert_almost_equal(sum(f,axis=0),0.0)
+            assert_array_almost_equal(ihilbert(hilbert(f)),f)
+            assert_array_almost_equal(hilbert(ihilbert(f)),f)
+
+    def test_random_even(self):
+        rng = np.random.default_rng(1234)
+        for n in [32,64,56]:
+            f = rng.random((n,))
+            af = sum(f,axis=0)/n
+            f = f-af
+            # zeroing Nyquist mode:
+            f = diff(diff(f,1),-1)
+            assert_almost_equal(sum(f,axis=0),0.0)
+            assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f)
+            assert_array_almost_equal(hilbert(ihilbert(f)),f)
+
+
+class TestIHilbert:
+
+    def test_definition(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            y = ihilbert(sin(x))
+            y1 = direct_ihilbert(sin(x))
+            assert_array_almost_equal(y,y1)
+            assert_array_almost_equal(ihilbert(sin(2*x)),
+                                      direct_ihilbert(sin(2*x)))
+
+    def test_itilbert_relation(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            f = sin(x)+cos(2*x)*sin(x)
+            y = ihilbert(f)
+            y1 = direct_ihilbert(f)
+            assert_array_almost_equal(y,y1)
+            y2 = itilbert(f,h=10)
+            assert_array_almost_equal(y,y2)
+
+
+class TestShift:
+
+    def test_definition(self):
+        for n in [18,17,64,127,32,2048,256]:
+            x = arange(n)*2*pi/n
+            for a in [0.1,3]:
+                assert_array_almost_equal(shift(sin(x),a),direct_shift(sin(x),a))
+                assert_array_almost_equal(shift(sin(x),a),sin(x+a))
+                assert_array_almost_equal(shift(cos(x),a),cos(x+a))
+                assert_array_almost_equal(shift(cos(2*x)+sin(x),a),
+                                          cos(2*(x+a))+sin(x+a))
+                assert_array_almost_equal(shift(exp(sin(x)),a),exp(sin(x+a)))
+            assert_array_almost_equal(shift(sin(x),2*pi),sin(x))
+            assert_array_almost_equal(shift(sin(x),pi),-sin(x))
+            assert_array_almost_equal(shift(sin(x),pi/2),cos(x))
+
+
+class TestOverwrite:
+    """Check input overwrite behavior """
+
+    real_dtypes = (np.float32, np.float64)
+    dtypes = real_dtypes + (np.complex64, np.complex128)
+
+    def _check(self, x, routine, *args, **kwargs):
+        x2 = x.copy()
+        routine(x2, *args, **kwargs)
+        sig = routine.__name__
+        if args:
+            sig += repr(args)
+        if kwargs:
+            sig += repr(kwargs)
+        assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, *args, **kwargs):
+        # rng = np.random.default_rng(1234)
+        rng = np.random.RandomState(1234)
+        # np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = rng.randn(*shape) + 1j*rng.randn(*shape)
+        else:
+            data = rng.randn(*shape)
+        data = data.astype(dtype)
+        self._check(data, routine, *args, **kwargs)
+
+    def test_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(diff, dtype, (16,))
+
+    def test_tilbert(self):
+        for dtype in self.dtypes:
+            self._check_1d(tilbert, dtype, (16,), 1.6)
+
+    def test_itilbert(self):
+        for dtype in self.dtypes:
+            self._check_1d(itilbert, dtype, (16,), 1.6)
+
+    def test_hilbert(self):
+        for dtype in self.dtypes:
+            self._check_1d(hilbert, dtype, (16,))
+
+    def test_cs_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(cs_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_sc_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(sc_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_ss_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(ss_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_cc_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(cc_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_shift(self):
+        for dtype in self.dtypes:
+            self._check_1d(shift, dtype, (16,), 1.0)
diff --git a/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..876af8f18a312f88c508c6b2ae96f1e5c1dad96d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py
@@ -0,0 +1,837 @@
+from os.path import join, dirname
+import threading
+
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_equal
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fftpack._realtransforms import (
+    dct, idct, dst, idst, dctn, idctn, dstn, idstn)
+
+# Matlab reference data
+MDATA = np.load(join(dirname(__file__), 'test.npz'))
+X = [MDATA['x%d' % i] for i in range(8)]
+Y = [MDATA['y%d' % i] for i in range(8)]
+
+# FFTW reference data: the data are organized as follows:
+#    * SIZES is an array containing all available sizes
+#    * for every type (1, 2, 3, 4) and every size, the array dct_type_size
+#    contains the output of the DCT applied to the input np.linspace(0, size-1,
+#    size)
+FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz'))
+FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz'))
+FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
+
+
+def fftw_dct_ref(type, size, dt):
+    x = np.linspace(0, size-1, size).astype(dt)
+    dt = np.result_type(np.float32, dt)
+    if dt == np.float64:
+        data = FFTWDATA_DOUBLE
+    elif dt == np.float32:
+        data = FFTWDATA_SINGLE
+    else:
+        raise ValueError()
+    y = (data['dct_%d_%d' % (type, size)]).astype(dt)
+    return x, y, dt
+
+
+def fftw_dst_ref(type, size, dt):
+    x = np.linspace(0, size-1, size).astype(dt)
+    dt = np.result_type(np.float32, dt)
+    if dt == np.float64:
+        data = FFTWDATA_DOUBLE
+    elif dt == np.float32:
+        data = FFTWDATA_SINGLE
+    else:
+        raise ValueError()
+    y = (data['dst_%d_%d' % (type, size)]).astype(dt)
+    return x, y, dt
+
+
+def dct_2d_ref(x, **kwargs):
+    """Calculate reference values for testing dct2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = dct(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = dct(x[:, col], **kwargs)
+    return x
+
+
+def idct_2d_ref(x, **kwargs):
+    """Calculate reference values for testing idct2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = idct(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = idct(x[:, col], **kwargs)
+    return x
+
+
+def dst_2d_ref(x, **kwargs):
+    """Calculate reference values for testing dst2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = dst(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = dst(x[:, col], **kwargs)
+    return x
+
+
+def idst_2d_ref(x, **kwargs):
+    """Calculate reference values for testing idst2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = idst(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = idst(x[:, col], **kwargs)
+    return x
+
+
+def naive_dct1(x, norm=None):
+    """Calculate textbook definition version of DCT-I."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    M = N-1
+    y = np.zeros(N)
+    m0, m = 1, 2
+    if norm == 'ortho':
+        m0 = np.sqrt(1.0/M)
+        m = np.sqrt(2.0/M)
+    for k in range(N):
+        for n in range(1, N-1):
+            y[k] += m*x[n]*np.cos(np.pi*n*k/M)
+        y[k] += m0 * x[0]
+        y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
+    if norm == 'ortho':
+        y[0] *= 1/np.sqrt(2)
+        y[N-1] *= 1/np.sqrt(2)
+    return y
+
+
+def naive_dst1(x, norm=None):
+    """Calculate textbook definition version  of DST-I."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    M = N+1
+    y = np.zeros(N)
+    for k in range(N):
+        for n in range(N):
+            y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
+    if norm == 'ortho':
+        y *= np.sqrt(0.5/M)
+    return y
+
+
+def naive_dct4(x, norm=None):
+    """Calculate textbook definition version of DCT-IV."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    y = np.zeros(N)
+    for k in range(N):
+        for n in range(N):
+            y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
+    if norm == 'ortho':
+        y *= np.sqrt(2.0/N)
+    else:
+        y *= 2
+    return y
+
+
+def naive_dst4(x, norm=None):
+    """Calculate textbook definition version of DST-IV."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    y = np.zeros(N)
+    for k in range(N):
+        for n in range(N):
+            y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
+    if norm == 'ortho':
+        y *= np.sqrt(2.0/N)
+    else:
+        y *= 2
+    return y
+
+
+class TestComplex:
+    def test_dct_complex64(self):
+        y = dct(1j*np.arange(5, dtype=np.complex64))
+        x = 1j*dct(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_dct_complex(self):
+        y = dct(np.arange(5)*1j)
+        x = 1j*dct(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_idct_complex(self):
+        y = idct(np.arange(5)*1j)
+        x = 1j*idct(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_dst_complex64(self):
+        y = dst(np.arange(5, dtype=np.complex64)*1j)
+        x = 1j*dst(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_dst_complex(self):
+        y = dst(np.arange(5)*1j)
+        x = 1j*dst(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_idst_complex(self):
+        y = idst(np.arange(5)*1j)
+        x = 1j*idst(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+
+class _TestDCTBase:
+    def setup_method(self):
+        self.rdt = None
+        self.dec = 14
+        self.type = None
+
+    @pytest.fixture
+    def dct_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, dct_lock):
+        for i in FFTWDATA_SIZES:
+            with dct_lock:
+                x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
+            y = dct(x, type=self.type)
+            assert_equal(y.dtype, dt)
+            # XXX: we divide by np.max(y) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
+                    err_msg="Size %d failed" % i)
+
+    def test_axis(self):
+        nt = 2
+        rng = np.random.RandomState(1234)
+        for i in [7, 8, 9, 16, 32, 64]:
+            x = rng.randn(nt, i)
+            y = dct(x, type=self.type)
+            for j in range(nt):
+                assert_array_almost_equal(y[j], dct(x[j], type=self.type),
+                        decimal=self.dec)
+
+            x = x.T
+            y = dct(x, axis=0, type=self.type)
+            for j in range(nt):
+                assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
+                        decimal=self.dec)
+
+
+class _TestDCTIBase(_TestDCTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dct(x, norm='ortho', type=1)
+            y2 = naive_dct1(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+class _TestDCTIIBase(_TestDCTBase):
+    def test_definition_matlab(self):
+        # Test correspondence with MATLAB (orthornomal mode).
+        dt = np.result_type(np.float32, self.rdt)
+        for xr, yr in zip(X, Y):
+            x = np.array(xr, dtype=dt)
+            y = dct(x, norm="ortho", type=2)
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y, yr, decimal=self.dec)
+
+
+class _TestDCTIIIBase(_TestDCTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dct(x, norm='ortho', type=2)
+            xi = dct(y, norm="ortho", type=3)
+            assert_equal(xi.dtype, dt)
+            assert_array_almost_equal(xi, x, decimal=self.dec)
+
+class _TestDCTIVBase(_TestDCTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dct(x, norm='ortho', type=4)
+            y2 = naive_dct4(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+
+class TestDCTIDouble(_TestDCTIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 1
+
+
+class TestDCTIFloat(_TestDCTIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestDCTIInt(_TestDCTIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 1
+
+
+class TestDCTIIDouble(_TestDCTIIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 2
+
+
+class TestDCTIIFloat(_TestDCTIIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 2
+
+
+class TestDCTIIInt(_TestDCTIIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 2
+
+
+class TestDCTIIIDouble(_TestDCTIIIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestDCTIIIFloat(_TestDCTIIIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 3
+
+
+class TestDCTIIIInt(_TestDCTIIIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 3
+
+
+class TestDCTIVDouble(_TestDCTIVBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 3
+
+
+class TestDCTIVFloat(_TestDCTIVBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 3
+
+
+class TestDCTIVInt(_TestDCTIVBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 3
+
+
+class _TestIDCTBase:
+    def setup_method(self):
+        self.rdt = None
+        self.dec = 14
+        self.type = None
+
+    @pytest.fixture
+    def idct_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, idct_lock):
+        for i in FFTWDATA_SIZES:
+            with idct_lock:
+                xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
+            x = idct(yr, type=self.type)
+            if self.type == 1:
+                x /= 2 * (i-1)
+            else:
+                x /= 2 * i
+            assert_equal(x.dtype, dt)
+            # XXX: we divide by np.max(y) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
+                    err_msg="Size %d failed" % i)
+
+
+class TestIDCTIDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 1
+
+
+class TestIDCTIFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDCTIInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDCTIIDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 2
+
+
+class TestIDCTIIFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 2
+
+
+class TestIDCTIIInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 2
+
+
+class TestIDCTIIIDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestIDCTIIIFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 3
+
+
+class TestIDCTIIIInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 3
+
+class TestIDCTIVDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 4
+
+
+class TestIDCTIVFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 4
+
+
+class TestIDCTIVInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 4
+
+class _TestDSTBase:
+    def setup_method(self):
+        self.rdt = None  # dtype
+        self.dec = None  # number of decimals to match
+        self.type = None  # dst type
+
+    @pytest.fixture
+    def dst_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, dst_lock):
+        for i in FFTWDATA_SIZES:
+            with dst_lock:
+                xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
+            y = dst(xr, type=self.type)
+            assert_equal(y.dtype, dt)
+            # XXX: we divide by np.max(y) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
+                    err_msg="Size %d failed" % i)
+
+
+class _TestDSTIBase(_TestDSTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dst(x, norm='ortho', type=1)
+            y2 = naive_dst1(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+class _TestDSTIVBase(_TestDSTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dst(x, norm='ortho', type=4)
+            y2 = naive_dst4(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y, y2, decimal=self.dec)
+
+class TestDSTIDouble(_TestDSTIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 1
+
+
+class TestDSTIFloat(_TestDSTIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestDSTIInt(_TestDSTIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 1
+
+
+class TestDSTIIDouble(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 2
+
+
+class TestDSTIIFloat(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 2
+
+
+class TestDSTIIInt(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 2
+
+
+class TestDSTIIIDouble(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestDSTIIIFloat(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 7
+        self.type = 3
+
+
+class TestDSTIIIInt(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 7
+        self.type = 3
+
+
+class TestDSTIVDouble(_TestDSTIVBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 4
+
+
+class TestDSTIVFloat(_TestDSTIVBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 4
+
+
+class TestDSTIVInt(_TestDSTIVBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 4
+
+
+class _TestIDSTBase:
+    def setup_method(self):
+        self.rdt = None
+        self.dec = None
+        self.type = None
+
+    @pytest.fixture
+    def idst_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, idst_lock):
+        for i in FFTWDATA_SIZES:
+            with idst_lock:
+                xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
+            x = idst(yr, type=self.type)
+            if self.type == 1:
+                x /= 2 * (i+1)
+            else:
+                x /= 2 * i
+            assert_equal(x.dtype, dt)
+            # XXX: we divide by np.max(x) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
+                    err_msg="Size %d failed" % i)
+
+
+class TestIDSTIDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 1
+
+
+class TestIDSTIFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDSTIInt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDSTIIDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 2
+
+
+class TestIDSTIIFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 2
+
+
+class TestIDSTIIInt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 2
+
+
+class TestIDSTIIIDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestIDSTIIIFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 3
+
+
+class TestIDSTIIIInt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 3
+
+
+class TestIDSTIVDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 4
+
+
+class TestIDSTIVFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 4
+
+
+class TestIDSTIVnt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 4
+
+
+class TestOverwrite:
+    """Check input overwrite behavior."""
+
+    real_dtypes = [np.float32, np.float64]
+
+    def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
+        x2 = x.copy()
+        routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)
+
+        sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+               f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+        if not overwrite_x:
+            assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, axis):
+        rng = np.random.RandomState(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = rng.randn(*shape) + 1j*rng.randn(*shape)
+        else:
+            data = rng.randn(*shape)
+        data = data.astype(dtype)
+
+        for type in [1, 2, 3, 4]:
+            for overwrite_x in [True, False]:
+                for norm in [None, 'ortho']:
+                    self._check(data, routine, type, None, axis, norm,
+                                overwrite_x)
+
+    def test_dct(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(dct, dtype, (16,), -1)
+            self._check_1d(dct, dtype, (16, 2), 0)
+            self._check_1d(dct, dtype, (2, 16), 1)
+
+    def test_idct(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(idct, dtype, (16,), -1)
+            self._check_1d(idct, dtype, (16, 2), 0)
+            self._check_1d(idct, dtype, (2, 16), 1)
+
+    def test_dst(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(dst, dtype, (16,), -1)
+            self._check_1d(dst, dtype, (16, 2), 0)
+            self._check_1d(dst, dtype, (2, 16), 1)
+
+    def test_idst(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(idst, dtype, (16,), -1)
+            self._check_1d(idst, dtype, (16, 2), 0)
+            self._check_1d(idst, dtype, (2, 16), 1)
+
+
+class Test_DCTN_IDCTN:
+    dec = 14
+    dct_type = [1, 2, 3, 4]
+    norms = [None, 'ortho']
+    rstate = np.random.RandomState(1234)
+    shape = (32, 16)
+    data = rstate.randn(*shape)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [None,
+                                      1, (1,), [1],
+                                      0, (0,), [0],
+                                      (0, 1), [0, 1],
+                                      (-2, -1), [-2, -1]])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', ['ortho'])
+    def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
+        tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
+        tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
+        assert_array_almost_equal(self.data, tmp, decimal=12)
+
+    @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
+                                                       (dstn, dst_2d_ref)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', norms)
+    def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
+                                  dct_type, norm):
+        y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
+        y2 = fforward_ref(self.data, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
+                                                       (idstn, idst_2d_ref)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', [None, 'ortho'])
+    def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
+                                   dct_type, norm):
+        fdata = dctn(self.data, type=dct_type, norm=norm)
+        y1 = finverse(fdata, type=dct_type, norm=norm)
+        y2 = finverse_ref(fdata, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    def test_axes_and_shape(self, fforward, finverse):
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, shape=self.data.shape[0], axes=(0, 1))
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, shape=self.data.shape[0], axes=None)
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, shape=self.data.shape, axes=0)
+
+    @pytest.mark.parametrize('fforward', [dctn, dstn])
+    def test_shape(self, fforward):
+        tmp = fforward(self.data, shape=(128, 128), axes=None)
+        assert_equal(tmp.shape, (128, 128))
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [1, (1,), [1],
+                                      0, (0,), [0]])
+    def test_shape_is_none_with_axes(self, fforward, finverse, axes):
+        tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
+        tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
+        assert_array_almost_equal(self.data, tmp, decimal=self.dec)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__init__.pxd b/venv/lib/python3.10/site-packages/scipy/linalg/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..c7c49f9ad8f4c90ee93725fdcdbe73c2e7f5aacd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/__init__.pxd
@@ -0,0 +1 @@
+from scipy.linalg cimport cython_blas, cython_lapack
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__init__.py b/venv/lib/python3.10/site-packages/scipy/linalg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9381d7a02c15a3234f38ee4bdee5d12d11d4afd1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/__init__.py
@@ -0,0 +1,236 @@
+"""
+====================================
+Linear algebra (:mod:`scipy.linalg`)
+====================================
+
+.. currentmodule:: scipy.linalg
+
+.. toctree::
+   :hidden:
+
+   linalg.blas
+   linalg.cython_blas
+   linalg.cython_lapack
+   linalg.interpolative
+   linalg.lapack
+
+Linear algebra functions.
+
+.. eventually, we should replace the numpy.linalg HTML link with just `numpy.linalg`
+
+.. seealso::
+
+   `numpy.linalg `__
+   for more linear algebra functions. Note that
+   although `scipy.linalg` imports most of them, identically named
+   functions from `scipy.linalg` may offer more or slightly differing
+   functionality.
+
+
+Basics
+======
+
+.. autosummary::
+   :toctree: generated/
+
+   inv - Find the inverse of a square matrix
+   solve - Solve a linear system of equations
+   solve_banded - Solve a banded linear system
+   solveh_banded - Solve a Hermitian or symmetric banded system
+   solve_circulant - Solve a circulant system
+   solve_triangular - Solve a triangular matrix
+   solve_toeplitz - Solve a toeplitz matrix
+   matmul_toeplitz - Multiply a Toeplitz matrix with an array.
+   det - Find the determinant of a square matrix
+   norm - Matrix and vector norm
+   lstsq - Solve a linear least-squares problem
+   pinv - Pseudo-inverse (Moore-Penrose) using lstsq
+   pinvh - Pseudo-inverse of hermitian matrix
+   kron - Kronecker product of two arrays
+   khatri_rao - Khatri-Rao product of two arrays
+   orthogonal_procrustes - Solve an orthogonal Procrustes problem
+   matrix_balance - Balance matrix entries with a similarity transformation
+   subspace_angles - Compute the subspace angles between two matrices
+   bandwidth - Return the lower and upper bandwidth of an array
+   issymmetric - Check if a square 2D array is symmetric
+   ishermitian - Check if a square 2D array is Hermitian
+   LinAlgError
+   LinAlgWarning
+
+Eigenvalue Problems
+===================
+
+.. autosummary::
+   :toctree: generated/
+
+   eig - Find the eigenvalues and eigenvectors of a square matrix
+   eigvals - Find just the eigenvalues of a square matrix
+   eigh - Find the e-vals and e-vectors of a Hermitian or symmetric matrix
+   eigvalsh - Find just the eigenvalues of a Hermitian or symmetric matrix
+   eig_banded - Find the eigenvalues and eigenvectors of a banded matrix
+   eigvals_banded - Find just the eigenvalues of a banded matrix
+   eigh_tridiagonal - Find the eigenvalues and eigenvectors of a tridiagonal matrix
+   eigvalsh_tridiagonal - Find just the eigenvalues of a tridiagonal matrix
+
+Decompositions
+==============
+
+.. autosummary::
+   :toctree: generated/
+
+   lu - LU decomposition of a matrix
+   lu_factor - LU decomposition returning unordered matrix and pivots
+   lu_solve - Solve Ax=b using back substitution with output of lu_factor
+   svd - Singular value decomposition of a matrix
+   svdvals - Singular values of a matrix
+   diagsvd - Construct matrix of singular values from output of svd
+   orth - Construct orthonormal basis for the range of A using svd
+   null_space - Construct orthonormal basis for the null space of A using svd
+   ldl - LDL.T decomposition of a Hermitian or a symmetric matrix.
+   cholesky - Cholesky decomposition of a matrix
+   cholesky_banded - Cholesky decomp. of a sym. or Hermitian banded matrix
+   cho_factor - Cholesky decomposition for use in solving a linear system
+   cho_solve - Solve previously factored linear system
+   cho_solve_banded - Solve previously factored banded linear system
+   polar - Compute the polar decomposition.
+   qr - QR decomposition of a matrix
+   qr_multiply - QR decomposition and multiplication by Q
+   qr_update - Rank k QR update
+   qr_delete - QR downdate on row or column deletion
+   qr_insert - QR update on row or column insertion
+   rq - RQ decomposition of a matrix
+   qz - QZ decomposition of a pair of matrices
+   ordqz - QZ decomposition of a pair of matrices with reordering
+   schur - Schur decomposition of a matrix
+   rsf2csf - Real to complex Schur form
+   hessenberg - Hessenberg form of a matrix
+   cdf2rdf - Complex diagonal form to real diagonal block form
+   cossin - Cosine sine decomposition of a unitary or orthogonal matrix
+
+.. seealso::
+
+   `scipy.linalg.interpolative` -- Interpolative matrix decompositions
+
+
+Matrix Functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   expm - Matrix exponential
+   logm - Matrix logarithm
+   cosm - Matrix cosine
+   sinm - Matrix sine
+   tanm - Matrix tangent
+   coshm - Matrix hyperbolic cosine
+   sinhm - Matrix hyperbolic sine
+   tanhm - Matrix hyperbolic tangent
+   signm - Matrix sign
+   sqrtm - Matrix square root
+   funm - Evaluating an arbitrary matrix function
+   expm_frechet - Frechet derivative of the matrix exponential
+   expm_cond - Relative condition number of expm in the Frobenius norm
+   fractional_matrix_power - Fractional matrix power
+
+
+Matrix Equation Solvers
+=======================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_sylvester - Solve the Sylvester matrix equation
+   solve_continuous_are - Solve the continuous-time algebraic Riccati equation
+   solve_discrete_are - Solve the discrete-time algebraic Riccati equation
+   solve_continuous_lyapunov - Solve the continuous-time Lyapunov equation
+   solve_discrete_lyapunov - Solve the discrete-time Lyapunov equation
+
+
+Sketches and Random Projections
+===============================
+
+.. autosummary::
+   :toctree: generated/
+
+   clarkson_woodruff_transform - Applies the Clarkson Woodruff Sketch (a.k.a CountMin Sketch)
+
+Special Matrices
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   block_diag - Construct a block diagonal matrix from submatrices
+   circulant - Circulant matrix
+   companion - Companion matrix
+   convolution_matrix - Convolution matrix
+   dft - Discrete Fourier transform matrix
+   fiedler - Fiedler matrix
+   fiedler_companion - Fiedler companion matrix
+   hadamard - Hadamard matrix of order 2**n
+   hankel - Hankel matrix
+   helmert - Helmert matrix
+   hilbert - Hilbert matrix
+   invhilbert - Inverse Hilbert matrix
+   leslie - Leslie matrix
+   pascal - Pascal matrix
+   invpascal - Inverse Pascal matrix
+   toeplitz - Toeplitz matrix
+
+Low-level routines
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   get_lapack_funcs
+   find_best_blas_type
+
+.. seealso::
+
+   `scipy.linalg.blas` -- Low-level BLAS functions
+
+   `scipy.linalg.lapack` -- Low-level LAPACK functions
+
+   `scipy.linalg.cython_blas` -- Low-level BLAS functions for Cython
+
+   `scipy.linalg.cython_lapack` -- Low-level LAPACK functions for Cython
+
+"""  # noqa: E501
+
+from ._misc import *
+from ._cythonized_array_utils import *
+from ._basic import *
+from ._decomp import *
+from ._decomp_lu import *
+from ._decomp_ldl import *
+from ._decomp_cholesky import *
+from ._decomp_qr import *
+from ._decomp_qz import *
+from ._decomp_svd import *
+from ._decomp_schur import *
+from ._decomp_polar import *
+from ._matfuncs import *
+from .blas import *
+from .lapack import *
+from ._special_matrices import *
+from ._solvers import *
+from ._procrustes import *
+from ._decomp_update import *
+from ._sketches import *
+from ._decomp_cossin import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    decomp, decomp_cholesky, decomp_lu, decomp_qr, decomp_svd, decomp_schur,
+    basic, misc, special_matrices, matfuncs,
+)
+
+__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.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ef47105c4631c9b441ea24160f30020b53e1246
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..738a39bb36f839e1bba424ef8af797480c3551c0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6c8cd1389efaf5c2ffa5d7f138e9417ea0db303
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..382550584ae884546a10f6a44a0598a1a273a031
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be01089b5b6603c05124c37952efc1841f32b380
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cea9d677f3af2f789d1240d44ef2b6e4166b6553
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09265a1fbc0ac0357d0a29a4f93d8e1bf3ef4b21
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cd0042fe9dca26f2be90343f09af91e40353899
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c98279f12007d882aea232a76c71989225030ea4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b2b8e48e70ab8061cb88709f4784c215da7038d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1f1bcc41cdbe4bbbda5624a67182766f6bc9693
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..400c1ac4b9c6680bc25f74b781c8a385ca273285
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28b9f90537f8166fb0e075f4dfd55b9a2eb3bd80
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc120ec40f52b623a472d223f66429456470d384
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54cfb74e1f4ae044adc78fdc26ffbc802df2fcd7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c86de6e4c3aa213b8431d7bc788bdde1a08ed50d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3483ae6e2794fb940e7ec4d458715d5e2b2cb554
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c2e9b0f93c7f549a6c6118d2f5843616057b5c9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62bfaa8f51433fa3cd34989e7bbcb5bf5f8de0f8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7805c141844a993d8d064fb445a59dfff57268e9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0344942bace2e6a90d1a6c8bda97ee3e6b0aeb96
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fc7fef30f94f64c4de9d29d281607f8765aa372
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..668d65dc523ad7f4ac0655c265dd1dfcb5a7fee6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85947ace457d665ab803f82192f57dcfcef3e582
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d68dcafbc2d7d435e37574742170f4476ab044d5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb73458a2df06daa7e7dca66da922aa9c9cc19d3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ebb86f8e1f72f7466803acf68b57a3d96ed13cd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..506dee428335eb120b37e2aa02b515a1a06fb4e9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7165333c89b0cc865d736b5fabc7797aa1a7bc4a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a332016430360635abd6799c85cd6602653ad21f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..791f3adf822818dd4ad961cca14363188be38184
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15f2d222f54951e718498de10c0ee9b383de095e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e376800069aef885c2ab0ce74fcb97ad1a4cac00
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb4c8317fa2114fb5a3cd8815b3d31a45bbb078a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b29d053aa81ab40e07a59f781f1ede652062a9a1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_basic.py b/venv/lib/python3.10/site-packages/scipy/linalg/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..70841fa80976c62ed7d894d824fdfbbcb4673273
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_basic.py
@@ -0,0 +1,2119 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# w/ additions by Travis Oliphant, March 2002
+#              and Jake Vanderplas, August 2012
+
+import warnings
+from warnings import warn
+from itertools import product
+import numpy as np
+from numpy import atleast_1d, atleast_2d
+from .lapack import get_lapack_funcs, _compute_lwork
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from ._decomp import _asarray_validated
+from . import _decomp, _decomp_svd
+from ._solve_toeplitz import levinson
+from ._cythonized_array_utils import (find_det_from_lu, bandwidth, issymmetric,
+                                      ishermitian)
+
+__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+           'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+           'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz']
+
+
+# The numpy facilities for type-casting checks are too slow for small sized
+# arrays and eat away the time budget for the checkups. Here we set a
+# precomputed dict container of the numpy.can_cast() table.
+
+# It can be used to determine quickly what a dtype can be cast to LAPACK
+# compatible types, i.e., 'float32, float64, complex64, complex128'.
+# Then it can be checked via "casting_dict[arr.dtype.char]"
+lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+
+# Linear equations
+def _solve_check(n, info, lamch=None, rcond=None):
+    """ Check arguments during the different steps of the solution phase """
+    if info < 0:
+        raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument.')
+    elif 0 < info:
+        raise LinAlgError('Matrix is singular.')
+
+    if lamch is None:
+        return
+    E = lamch('E')
+    if rcond < E:
+        warn(f'Ill-conditioned matrix (rcond={rcond:.6g}): '
+             'result may not be accurate.',
+             LinAlgWarning, stacklevel=3)
+
+
+def _find_matrix_structure(a):
+    n = a.shape[0]
+    n_below, n_above = bandwidth(a)
+
+    if n_below == n_above == 0:
+        kind = 'diagonal'
+    elif n_above == 0:
+        kind = 'lower triangular'
+    elif n_below == 0:
+        kind = 'upper triangular'
+    elif n_above <= 1 and n_below <= 1 and n > 3:
+        kind = 'tridiagonal'
+    elif np.issubdtype(a.dtype, np.complexfloating) and ishermitian(a):
+        kind = 'hermitian'
+    elif issymmetric(a):
+        kind = 'symmetric'
+    else:
+        kind = 'general'
+
+    return kind, n_below, n_above
+
+
+def solve(a, b, lower=False, overwrite_a=False,
+          overwrite_b=False, check_finite=True, assume_a=None,
+          transposed=False):
+    """
+    Solves the linear equation set ``a @ x == b`` for the unknown ``x``
+    for square `a` matrix.
+
+    If the data matrix is known to be a particular type then supplying the
+    corresponding string to ``assume_a`` key chooses the dedicated solver.
+    The available options are
+
+    ===================  ================================
+     diagonal             'diagonal'
+     tridiagonal          'tridiagonal'
+     banded               'banded'
+     upper triangular     'upper triangular'
+     lower triangular     'lower triangular'
+     symmetric            'symmetric' (or 'sym')
+     hermitian            'hermitian' (or 'her')
+     positive definite    'positive definite' (or 'pos')
+     general              'general' (or 'gen')
+    ===================  ================================
+
+    Parameters
+    ----------
+    a : (N, N) array_like
+        Square input data
+    b : (N, NRHS) array_like
+        Input data for the right hand side.
+    lower : bool, default: False
+        Ignored unless ``assume_a`` is one of ``'sym'``, ``'her'``, or ``'pos'``.
+        If True, the calculation uses only the data in the lower triangle of `a`;
+        entries above the diagonal are ignored. If False (default), the
+        calculation uses only the data in the upper triangle of `a`; entries
+        below the diagonal are ignored.
+    overwrite_a : bool, default: False
+        Allow overwriting data in `a` (may enhance performance).
+    overwrite_b : bool, default: False
+        Allow overwriting data in `b` (may enhance performance).
+    check_finite : bool, default: True
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    assume_a : str, optional
+        Valid entries are described above.
+        If omitted or ``None``, checks are performed to identify structure so the
+        appropriate solver can be called.
+    transposed : bool, default: False
+        If True, solve ``a.T @ x == b``. Raises `NotImplementedError`
+        for complex `a`.
+
+    Returns
+    -------
+    x : (N, NRHS) ndarray
+        The solution array.
+
+    Raises
+    ------
+    ValueError
+        If size mismatches detected or input a is not square.
+    LinAlgError
+        If the matrix is singular.
+    LinAlgWarning
+        If an ill-conditioned input a is detected.
+    NotImplementedError
+        If transposed is True and input a is a complex matrix.
+
+    Notes
+    -----
+    If the input b matrix is a 1-D array with N elements, when supplied
+    together with an NxN input a, it is assumed as a valid column vector
+    despite the apparent size mismatch. This is compatible with the
+    numpy.dot() behavior and the returned result is still 1-D array.
+
+    The general, symmetric, Hermitian and positive definite solutions are
+    obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
+    LAPACK respectively.
+
+    The datatype of the arrays define which solver is called regardless
+    of the values. In other words, even when the complex array entries have
+    precisely zero imaginary parts, the complex solver will be called based
+    on the data type of the array.
+
+    Examples
+    --------
+    Given `a` and `b`, solve for `x`:
+
+    >>> import numpy as np
+    >>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
+    >>> b = np.array([2, 4, -1])
+    >>> from scipy import linalg
+    >>> x = linalg.solve(a, b)
+    >>> x
+    array([ 2., -2.,  9.])
+    >>> np.dot(a, x) == b
+    array([ True,  True,  True], dtype=bool)
+
+    """
+    # Flags for 1-D or N-D right-hand side
+    b_is_1D = False
+
+    # check finite after determining structure
+    a1 = atleast_2d(_asarray_validated(a, check_finite=False))
+    b1 = atleast_1d(_asarray_validated(b, check_finite=False))
+    a1, b1 = _ensure_dtype_cdsz(a1, b1)
+    n = a1.shape[0]
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if a1.shape[0] != a1.shape[1]:
+        raise ValueError('Input a needs to be a square matrix.')
+
+    if n != b1.shape[0]:
+        # Last chance to catch 1x1 scalar a and 1-D b arrays
+        if not (n == 1 and b1.size != 0):
+            raise ValueError('Input b has to have same number of rows as '
+                             'input a')
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    # regularize 1-D b arrays to 2D
+    if b1.ndim == 1:
+        if n == 1:
+            b1 = b1[None, :]
+        else:
+            b1 = b1[:, None]
+        b_is_1D = True
+
+    if assume_a not in {None, 'diagonal', 'tridiagonal', 'banded', 'lower triangular',
+                        'upper triangular', 'symmetric', 'hermitian',
+                        'positive definite', 'general', 'sym', 'her', 'pos', 'gen'}:
+        raise ValueError(f'{assume_a} is not a recognized matrix structure')
+
+    # for a real matrix, describe it as "symmetric", not "hermitian"
+    # (lapack doesn't know what to do with real hermitian matrices)
+    if assume_a in {'hermitian', 'her'} and not np.iscomplexobj(a1):
+        assume_a = 'symmetric'
+
+    n_below, n_above = None, None
+    if assume_a is None:
+        assume_a, n_below, n_above = _find_matrix_structure(a1)
+
+    # Get the correct lamch function.
+    # The LAMCH functions only exists for S and D
+    # So for complex values we have to convert to real/double.
+    if a1.dtype.char in 'fF':  # single precision
+        lamch = get_lapack_funcs('lamch', dtype='f')
+    else:
+        lamch = get_lapack_funcs('lamch', dtype='d')
+
+    # Currently we do not have the other forms of the norm calculators
+    #   lansy, lanpo, lanhe.
+    # However, in any case they only reduce computations slightly...
+    if assume_a == 'diagonal':
+        _matrix_norm = _matrix_norm_diagonal
+    elif assume_a == 'tridiagonal':
+        _matrix_norm = _matrix_norm_tridiagonal
+    elif assume_a in {'lower triangular', 'upper triangular'}:
+        _matrix_norm = _matrix_norm_triangular(assume_a)
+    else:
+        _matrix_norm = _matrix_norm_general
+
+    # Since the I-norm and 1-norm are the same for symmetric matrices
+    # we can collect them all in this one call
+    # Note however, that when issuing 'gen' and form!='none', then
+    # the I-norm should be used
+    if transposed:
+        trans = 1
+        norm = 'I'
+        if np.iscomplexobj(a1):
+            raise NotImplementedError('scipy.linalg.solve can currently '
+                                      'not solve a^T x = b or a^H x = b '
+                                      'for complex matrices.')
+    else:
+        trans = 0
+        norm = '1'
+
+    anorm = _matrix_norm(norm, a1, check_finite)
+
+    info, rcond = 0, np.inf
+
+    # Generalized case 'gesv'
+    if assume_a in {'general', 'gen'}:
+        gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),
+                                               (a1, b1))
+        lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)
+        _solve_check(n, info)
+        x, info = getrs(lu, ipvt, b1,
+                        trans=trans, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = gecon(lu, anorm, norm=norm)
+    # Hermitian case 'hesv'
+    elif assume_a in {'hermitian', 'her'}:
+        hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',
+                                                 'hesv_lwork'), (a1, b1))
+        lwork = _compute_lwork(hesv_lw, n, lower)
+        lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,
+                                 lower=lower,
+                                 overwrite_a=overwrite_a,
+                                 overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = hecon(lu, ipvt, anorm)
+    # Symmetric case 'sysv'
+    elif assume_a in {'symmetric', 'sym'}:
+        sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',
+                                                 'sysv_lwork'), (a1, b1))
+        lwork = _compute_lwork(sysv_lw, n, lower)
+        lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,
+                                 lower=lower,
+                                 overwrite_a=overwrite_a,
+                                 overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = sycon(lu, ipvt, anorm)
+    # Diagonal case
+    elif assume_a == 'diagonal':
+        diag_a = np.diag(a1)
+        x = (b1.T / diag_a).T
+        abs_diag_a = np.abs(diag_a)
+        rcond = abs_diag_a.min() / abs_diag_a.max()
+    # Tri-diagonal case
+    elif assume_a == 'tridiagonal':
+        a1 = a1.T if transposed else a1
+        dl, d, du = np.diag(a1, -1), np.diag(a1, 0), np.diag(a1, 1)
+        _gttrf, _gttrs, _gtcon = get_lapack_funcs(('gttrf', 'gttrs', 'gtcon'), (a1, b1))
+        dl, d, du, du2, ipiv, info = _gttrf(dl, d, du)
+        _solve_check(n, info)
+        x, info = _gttrs(dl, d, du, du2, ipiv, b1, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = _gtcon(dl, d, du, du2, ipiv, anorm)
+    # Banded case
+    elif assume_a == 'banded':
+        a1, n_below, n_above = ((a1.T, n_above, n_below) if transposed
+                                else (a1, n_below, n_above))
+        n_below, n_above = bandwidth(a1) if n_below is None else (n_below, n_above)
+        ab = _to_banded(n_below, n_above, a1)
+        gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
+        # Next two lines copied from `solve_banded`
+        a2 = np.zeros((2*n_below + n_above + 1, ab.shape[1]), dtype=gbsv.dtype)
+        a2[n_below:, :] = ab
+        _, _, x, info = gbsv(n_below, n_above, a2, b1,
+                             overwrite_ab=True, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        # TODO: wrap gbcon and use to get rcond
+    # Triangular case
+    elif assume_a in {'lower triangular', 'upper triangular'}:
+        lower = assume_a == 'lower triangular'
+        x, info = _solve_triangular(a1, b1, lower=lower, overwrite_b=overwrite_b,
+                                    trans=transposed)
+        _solve_check(n, info)
+        _trcon = get_lapack_funcs(('trcon'), (a1, b1))
+        rcond, info = _trcon(a1, uplo='L' if lower else 'U')
+    # Positive definite case 'posv'
+    else:
+        pocon, posv = get_lapack_funcs(('pocon', 'posv'),
+                                       (a1, b1))
+        lu, x, info = posv(a1, b1, lower=lower,
+                           overwrite_a=overwrite_a,
+                           overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = pocon(lu, anorm)
+
+    _solve_check(n, info, lamch, rcond)
+
+    if b_is_1D:
+        x = x.ravel()
+
+    return x
+
+
+def _matrix_norm_diagonal(_, a, check_finite):
+    # Equivalent of dlange for diagonal matrix, assuming
+    # norm is either 'I' or '1' (really just not the Frobenius norm)
+    d = np.diag(a)
+    d = np.asarray_chkfinite(d) if check_finite else d
+    return np.abs(d).max()
+
+
+def _matrix_norm_tridiagonal(norm, a, check_finite):
+    # Equivalent of dlange for tridiagonal matrix, assuming
+    # norm is either 'I' or '1'
+    if norm == 'I':
+        a = a.T
+    # Context to avoid warning before error in cases like -inf + inf
+    with np.errstate(invalid='ignore'):
+        d = np.abs(np.diag(a))
+        d[1:] += np.abs(np.diag(a, 1))
+        d[:-1] += np.abs(np.diag(a, -1))
+    d = np.asarray_chkfinite(d) if check_finite else d
+    return d.max()
+
+
+def _matrix_norm_triangular(structure):
+    def fun(norm, a, check_finite):
+        a = np.asarray_chkfinite(a) if check_finite else a
+        lantr = get_lapack_funcs('lantr', (a,))
+        return lantr(norm, a, 'L' if structure == 'lower triangular' else 'U' )
+    return fun
+
+
+def _matrix_norm_general(norm, a, check_finite):
+    a = np.asarray_chkfinite(a) if check_finite else a
+    lange = get_lapack_funcs('lange', (a,))
+    return lange(norm, a)
+
+
+def _to_banded(n_below, n_above, a):
+    n = a.shape[0]
+    rows = n_above + n_below + 1
+    ab = np.zeros((rows, n), dtype=a.dtype)
+    ab[n_above] = np.diag(a)
+    for i in range(1, n_above + 1):
+        ab[n_above - i, i:] = np.diag(a, i)
+    for i in range(1, n_below + 1):
+        ab[n_above + i, :-i] = np.diag(a, -i)
+    return ab
+
+
+def _ensure_dtype_cdsz(*arrays):
+    # Ensure that the dtype of arrays is one of the standard types
+    # compatible with LAPACK functions (single or double precision
+    # real or complex).
+    dtype = np.result_type(*arrays)
+    if not np.issubdtype(dtype, np.inexact):
+        return (array.astype(np.float64) for array in arrays)
+    complex = np.issubdtype(dtype, np.complexfloating)
+    if np.finfo(dtype).bits <= 32:
+        dtype = np.complex64 if complex else np.float32
+    elif np.finfo(dtype).bits >= 64:
+        dtype = np.complex128 if complex else np.float64
+    return (array.astype(dtype, copy=False) for array in arrays)
+
+
+def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
+                     overwrite_b=False, check_finite=True):
+    """
+    Solve the equation ``a x = b`` for `x`, assuming a is a triangular matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A triangular matrix
+    b : (M,) or (M, N) array_like
+        Right-hand side matrix in ``a x = b``
+    lower : bool, optional
+        Use only data contained in the lower triangle of `a`.
+        Default is to use upper triangle.
+    trans : {0, 1, 2, 'N', 'T', 'C'}, optional
+        Type of system to solve:
+
+        ========  =========
+        trans     system
+        ========  =========
+        0 or 'N'  a x  = b
+        1 or 'T'  a^T x = b
+        2 or 'C'  a^H x = b
+        ========  =========
+    unit_diagonal : bool, optional
+        If True, diagonal elements of `a` are assumed to be 1 and
+        will not be referenced.
+    overwrite_b : bool, optional
+        Allow overwriting data in `b` (may enhance performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, N) ndarray
+        Solution to the system ``a x = b``.  Shape of return matches `b`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular
+
+    Notes
+    -----
+    .. versionadded:: 0.9.0
+
+    Examples
+    --------
+    Solve the lower triangular system a x = b, where::
+
+             [3  0  0  0]       [4]
+        a =  [2  1  0  0]   b = [2]
+             [1  0  1  0]       [4]
+             [1  1  1  1]       [2]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_triangular
+    >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])
+    >>> b = np.array([4, 2, 4, 2])
+    >>> x = solve_triangular(a, b, lower=True)
+    >>> x
+    array([ 1.33333333, -0.66666667,  2.66666667, -1.33333333])
+    >>> a.dot(x)  # Check the result
+    array([ 4.,  2.,  4.,  2.])
+
+    """
+
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    if a1.shape[0] != b1.shape[0]:
+        raise ValueError(f'shapes of a {a1.shape} and b {b1.shape} are incompatible')
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt_nonempty = solve_triangular(
+            np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)
+        ).dtype
+        return np.empty_like(b1, dtype=dt_nonempty)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    x, _ = _solve_triangular(a1, b1, trans, lower, unit_diagonal, overwrite_b)
+    return x
+
+
+# solve_triangular without the input validation
+def _solve_triangular(a1, b1, trans=0, lower=False, unit_diagonal=False,
+                      overwrite_b=False):
+
+    trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans)
+    trtrs, = get_lapack_funcs(('trtrs',), (a1, b1))
+    if a1.flags.f_contiguous or trans == 2:
+        x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,
+                        trans=trans, unitdiag=unit_diagonal)
+    else:
+        # transposed system is solved since trtrs expects Fortran ordering
+        x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower,
+                        trans=not trans, unitdiag=unit_diagonal)
+
+    if info == 0:
+        return x, info
+    if info > 0:
+        raise LinAlgError("singular matrix: resolution failed at diagonal %d" %
+                          (info-1))
+    raise ValueError('illegal value in %dth argument of internal trtrs' %
+                     (-info))
+
+
+def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,
+                 check_finite=True):
+    """
+    Solve the equation a x = b for x, assuming a is banded matrix.
+
+    The matrix a is stored in `ab` using the matrix diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]
+
+    Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::
+
+        *    a01  a12  a23  a34  a45
+        a00  a11  a22  a33  a44  a55
+        a10  a21  a32  a43  a54   *
+        a20  a31  a42  a53   *    *
+
+    Parameters
+    ----------
+    (l, u) : (integer, integer)
+        Number of non-zero lower and upper diagonals
+    ab : (`l` + `u` + 1, M) array_like
+        Banded matrix
+    b : (M,) or (M, K) array_like
+        Right-hand side
+    overwrite_ab : bool, optional
+        Discard data in `ab` (may enhance performance)
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system a x = b. Returned shape depends on the
+        shape of `b`.
+
+    Examples
+    --------
+    Solve the banded system a x = b, where::
+
+            [5  2 -1  0  0]       [0]
+            [1  4  2 -1  0]       [1]
+        a = [0  1  3  2 -1]   b = [2]
+            [0  0  1  2  2]       [2]
+            [0  0  0  1  1]       [3]
+
+    There is one nonzero diagonal below the main diagonal (l = 1), and
+    two above (u = 2). The diagonal banded form of the matrix is::
+
+             [*  * -1 -1 -1]
+        ab = [*  2  2  2  2]
+             [5  4  3  2  1]
+             [1  1  1  1  *]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_banded
+    >>> ab = np.array([[0,  0, -1, -1, -1],
+    ...                [0,  2,  2,  2,  2],
+    ...                [5,  4,  3,  2,  1],
+    ...                [1,  1,  1,  1,  0]])
+    >>> b = np.array([0, 1, 2, 2, 3])
+    >>> x = solve_banded((1, 2), ab, b)
+    >>> x
+    array([-2.37288136,  3.93220339, -4.        ,  4.3559322 , -1.3559322 ])
+
+    """
+
+    a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True)
+    b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True)
+
+    # Validate shapes.
+    if a1.shape[-1] != b1.shape[0]:
+        raise ValueError("shapes of ab and b are not compatible.")
+
+    (nlower, nupper) = l_and_u
+    if nlower + nupper + 1 != a1.shape[0]:
+        raise ValueError("invalid values for the number of lower and upper "
+                         "diagonals: l+u+1 (%d) does not equal ab.shape[0] "
+                         "(%d)" % (nlower + nupper + 1, ab.shape[0]))
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+    if a1.shape[-1] == 1:
+        b2 = np.array(b1, copy=(not overwrite_b))
+        # a1.shape[-1] == 1 -> original matrix is 1x1. Typically, the user
+        # will pass u = l = 0 and `a1` will be 1x1. However, the rest of the
+        # function works with unnecessary rows in `a1` as long as
+        # `a1[u + i - j, j] == a[i,j]`. In the 1x1 case, we want i = j = 0,
+        # so the diagonal is in row `u` of `a1`. See gh-8906.
+        b2 /= a1[nupper, 0]
+        return b2
+    if nlower == nupper == 1:
+        overwrite_ab = overwrite_ab or _datacopied(a1, ab)
+        gtsv, = get_lapack_funcs(('gtsv',), (a1, b1))
+        du = a1[0, 1:]
+        d = a1[1, :]
+        dl = a1[2, :-1]
+        du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab,
+                                   overwrite_ab, overwrite_b)
+    else:
+        gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
+        a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype)
+        a2[nlower:, :] = a1
+        lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True,
+                                overwrite_b=overwrite_b)
+    if info == 0:
+        return x
+    if info > 0:
+        raise LinAlgError("singular matrix")
+    raise ValueError('illegal value in %d-th argument of internal '
+                     'gbsv/gtsv' % -info)
+
+
+def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,
+                  check_finite=True):
+    """
+    Solve equation a x = b. a is Hermitian positive-definite banded matrix.
+
+    Uses Thomas' Algorithm, which is more efficient than standard LU
+    factorization, but should only be used for Hermitian positive-definite
+    matrices.
+
+    The matrix ``a`` is stored in `ab` either in lower diagonal or upper
+    diagonal ordered form:
+
+        ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        ab[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals,
+    ``u`` =2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    ab : (``u`` + 1, M) array_like
+        Banded matrix
+    b : (M,) or (M, K) array_like
+        Right-hand side
+    overwrite_ab : bool, optional
+        Discard data in `ab` (may enhance performance)
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system ``a x = b``. Shape of return matches shape
+        of `b`.
+
+    Notes
+    -----
+    In the case of a non-positive definite matrix ``a``, the solver
+    `solve_banded` may be used.
+
+    Examples
+    --------
+    Solve the banded system ``A x = b``, where::
+
+            [ 4  2 -1  0  0  0]       [1]
+            [ 2  5  2 -1  0  0]       [2]
+        A = [-1  2  6  2 -1  0]   b = [2]
+            [ 0 -1  2  7  2 -1]       [3]
+            [ 0  0 -1  2  8  2]       [3]
+            [ 0  0  0 -1  2  9]       [3]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solveh_banded
+
+    ``ab`` contains the main diagonal and the nonzero diagonals below the
+    main diagonal. That is, we use the lower form:
+
+    >>> ab = np.array([[ 4,  5,  6,  7, 8, 9],
+    ...                [ 2,  2,  2,  2, 2, 0],
+    ...                [-1, -1, -1, -1, 0, 0]])
+    >>> b = np.array([1, 2, 2, 3, 3, 3])
+    >>> x = solveh_banded(ab, b, lower=True)
+    >>> x
+    array([ 0.03431373,  0.45938375,  0.05602241,  0.47759104,  0.17577031,
+            0.34733894])
+
+
+    Solve the Hermitian banded system ``H x = b``, where::
+
+            [ 8   2-1j   0     0  ]        [ 1  ]
+        H = [2+1j  5     1j    0  ]    b = [1+1j]
+            [ 0   -1j    9   -2-1j]        [1-2j]
+            [ 0    0   -2+1j   6  ]        [ 0  ]
+
+    In this example, we put the upper diagonals in the array ``hb``:
+
+    >>> hb = np.array([[0, 2-1j, 1j, -2-1j],
+    ...                [8,  5,    9,   6  ]])
+    >>> b = np.array([1, 1+1j, 1-2j, 0])
+    >>> x = solveh_banded(hb, b)
+    >>> x
+    array([ 0.07318536-0.02939412j,  0.11877624+0.17696461j,
+            0.10077984-0.23035393j, -0.00479904-0.09358128j])
+
+    """
+    a1 = _asarray_validated(ab, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+
+    # Validate shapes.
+    if a1.shape[-1] != b1.shape[0]:
+        raise ValueError("shapes of ab and b are not compatible.")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+    overwrite_ab = overwrite_ab or _datacopied(a1, ab)
+
+    if a1.shape[0] == 2:
+        ptsv, = get_lapack_funcs(('ptsv',), (a1, b1))
+        if lower:
+            d = a1[0, :].real
+            e = a1[1, :-1]
+        else:
+            d = a1[1, :].real
+            e = a1[0, 1:].conj()
+        d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab,
+                              overwrite_b)
+    else:
+        pbsv, = get_lapack_funcs(('pbsv',), (a1, b1))
+        c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab,
+                          overwrite_b=overwrite_b)
+    if info > 0:
+        raise LinAlgError("%dth leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal '
+                         'pbsv' % -info)
+    return x
+
+
+def solve_toeplitz(c_or_cr, b, check_finite=True):
+    r"""Solve a Toeplitz system using Levinson Recursion
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    .. warning::
+
+        Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+        not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+        before passing them to `solve_toeplitz`.
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``.
+    b : (M,) or (M, K) array_like
+        Right-hand side in ``T x = b``.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system ``T x = b``. Shape of return matches shape
+        of `b`.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+
+    Notes
+    -----
+    The solution is computed using Levinson-Durbin recursion, which is faster
+    than generic least-squares methods, but can be less numerically stable.
+
+    Examples
+    --------
+    Solve the Toeplitz system T x = b, where::
+
+            [ 1 -1 -2 -3]       [1]
+        T = [ 3  1 -1 -2]   b = [2]
+            [ 6  3  1 -1]       [2]
+            [10  6  3  1]       [5]
+
+    To specify the Toeplitz matrix, only the first column and the first
+    row are needed.
+
+    >>> import numpy as np
+    >>> c = np.array([1, 3, 6, 10])    # First column of T
+    >>> r = np.array([1, -1, -2, -3])  # First row of T
+    >>> b = np.array([1, 2, 2, 5])
+
+    >>> from scipy.linalg import solve_toeplitz, toeplitz
+    >>> x = solve_toeplitz((c, r), b)
+    >>> x
+    array([ 1.66666667, -1.        , -2.66666667,  2.33333333])
+
+    Check the result by creating the full Toeplitz matrix and
+    multiplying it by `x`.  We should get `b`.
+
+    >>> T = toeplitz(c, r)
+    >>> T.dot(x)
+    array([ 1.,  2.,  2.,  5.])
+
+    """
+    # If numerical stability of this algorithm is a problem, a future
+    # developer might consider implementing other O(N^2) Toeplitz solvers,
+    # such as GKO (https://www.jstor.org/stable/2153371) or Bareiss.
+
+    r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops(
+        c_or_cr, b, check_finite, keep_b_shape=True)
+
+    # accommodate empty arrays
+    if b.size == 0:
+        return np.empty_like(b)
+
+    # Form a 1-D array of values to be used in the matrix, containing a
+    # reversed copy of r[1:], followed by c.
+    vals = np.concatenate((r[-1:0:-1], c))
+    if b is None:
+        raise ValueError('illegal value, `b` is a required argument')
+
+    if b.ndim == 1:
+        x, _ = levinson(vals, np.ascontiguousarray(b))
+    else:
+        x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0]
+                             for i in range(b.shape[1])])
+        x = x.reshape(*b_shape)
+
+    return x
+
+
+def _get_axis_len(aname, a, axis):
+    ax = axis
+    if ax < 0:
+        ax += a.ndim
+    if 0 <= ax < a.ndim:
+        return a.shape[ax]
+    raise ValueError(f"'{aname}axis' entry is out of bounds")
+
+
+def solve_circulant(c, b, singular='raise', tol=None,
+                    caxis=-1, baxis=0, outaxis=0):
+    """Solve C x = b for x, where C is a circulant matrix.
+
+    `C` is the circulant matrix associated with the vector `c`.
+
+    The system is solved by doing division in Fourier space. The
+    calculation is::
+
+        x = ifft(fft(b) / fft(c))
+
+    where `fft` and `ifft` are the fast Fourier transform and its inverse,
+    respectively. For a large vector `c`, this is *much* faster than
+    solving the system with the full circulant matrix.
+
+    Parameters
+    ----------
+    c : array_like
+        The coefficients of the circulant matrix.
+    b : array_like
+        Right-hand side matrix in ``a x = b``.
+    singular : str, optional
+        This argument controls how a near singular circulant matrix is
+        handled.  If `singular` is "raise" and the circulant matrix is
+        near singular, a `LinAlgError` is raised. If `singular` is
+        "lstsq", the least squares solution is returned. Default is "raise".
+    tol : float, optional
+        If any eigenvalue of the circulant matrix has an absolute value
+        that is less than or equal to `tol`, the matrix is considered to be
+        near singular. If not given, `tol` is set to::
+
+            tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps
+
+        where `abs_eigs` is the array of absolute values of the eigenvalues
+        of the circulant matrix.
+    caxis : int
+        When `c` has dimension greater than 1, it is viewed as a collection
+        of circulant vectors. In this case, `caxis` is the axis of `c` that
+        holds the vectors of circulant coefficients.
+    baxis : int
+        When `b` has dimension greater than 1, it is viewed as a collection
+        of vectors. In this case, `baxis` is the axis of `b` that holds the
+        right-hand side vectors.
+    outaxis : int
+        When `c` or `b` are multidimensional, the value returned by
+        `solve_circulant` is multidimensional. In this case, `outaxis` is
+        the axis of the result that holds the solution vectors.
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the system ``C x = b``.
+
+    Raises
+    ------
+    LinAlgError
+        If the circulant matrix associated with `c` is near singular.
+
+    See Also
+    --------
+    circulant : circulant matrix
+
+    Notes
+    -----
+    For a 1-D vector `c` with length `m`, and an array `b`
+    with shape ``(m, ...)``,
+
+        solve_circulant(c, b)
+
+    returns the same result as
+
+        solve(circulant(c), b)
+
+    where `solve` and `circulant` are from `scipy.linalg`.
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_circulant, solve, circulant, lstsq
+
+    >>> c = np.array([2, 2, 4])
+    >>> b = np.array([1, 2, 3])
+    >>> solve_circulant(c, b)
+    array([ 0.75, -0.25,  0.25])
+
+    Compare that result to solving the system with `scipy.linalg.solve`:
+
+    >>> solve(circulant(c), b)
+    array([ 0.75, -0.25,  0.25])
+
+    A singular example:
+
+    >>> c = np.array([1, 1, 0, 0])
+    >>> b = np.array([1, 2, 3, 4])
+
+    Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`.  For the
+    least square solution, use the option ``singular='lstsq'``:
+
+    >>> solve_circulant(c, b, singular='lstsq')
+    array([ 0.25,  1.25,  2.25,  1.25])
+
+    Compare to `scipy.linalg.lstsq`:
+
+    >>> x, resid, rnk, s = lstsq(circulant(c), b)
+    >>> x
+    array([ 0.25,  1.25,  2.25,  1.25])
+
+    A broadcasting example:
+
+    Suppose we have the vectors of two circulant matrices stored in an array
+    with shape (2, 5), and three `b` vectors stored in an array with shape
+    (3, 5).  For example,
+
+    >>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])
+    >>> b = np.arange(15).reshape(-1, 5)
+
+    We want to solve all combinations of circulant matrices and `b` vectors,
+    with the result stored in an array with shape (2, 3, 5). When we
+    disregard the axes of `c` and `b` that hold the vectors of coefficients,
+    the shapes of the collections are (2,) and (3,), respectively, which are
+    not compatible for broadcasting. To have a broadcast result with shape
+    (2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has
+    shape (2, 1, 5). The last dimension holds the coefficients of the
+    circulant matrices, so when we call `solve_circulant`, we can use the
+    default ``caxis=-1``. The coefficients of the `b` vectors are in the last
+    dimension of the array `b`, so we use ``baxis=-1``. If we use the
+    default `outaxis`, the result will have shape (5, 2, 3), so we'll use
+    ``outaxis=-1`` to put the solution vectors in the last dimension.
+
+    >>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)
+    >>> x.shape
+    (2, 3, 5)
+    >>> np.set_printoptions(precision=3)  # For compact output of numbers.
+    >>> x
+    array([[[-0.118,  0.22 ,  1.277, -0.142,  0.302],
+            [ 0.651,  0.989,  2.046,  0.627,  1.072],
+            [ 1.42 ,  1.758,  2.816,  1.396,  1.841]],
+           [[ 0.401,  0.304,  0.694, -0.867,  0.377],
+            [ 0.856,  0.758,  1.149, -0.412,  0.831],
+            [ 1.31 ,  1.213,  1.603,  0.042,  1.286]]])
+
+    Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):
+
+    >>> solve_circulant(c[1], b[1, :])
+    array([ 0.856,  0.758,  1.149, -0.412,  0.831])
+
+    """
+    c = np.atleast_1d(c)
+    nc = _get_axis_len("c", c, caxis)
+    b = np.atleast_1d(b)
+    nb = _get_axis_len("b", b, baxis)
+    if nc != nb:
+        raise ValueError(f'Shapes of c {c.shape} and b {b.shape} are incompatible')
+
+    # accommodate empty arrays
+    if b.size == 0:
+        dt = solve_circulant(np.arange(3, dtype=c.dtype),
+                             np.ones(3, dtype=b.dtype)).dtype
+        return np.empty_like(b, dtype=dt)
+
+    fc = np.fft.fft(np.moveaxis(c, caxis, -1), axis=-1)
+    abs_fc = np.abs(fc)
+    if tol is None:
+        # This is the same tolerance as used in np.linalg.matrix_rank.
+        tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps
+        if tol.shape != ():
+            tol.shape = tol.shape + (1,)
+        else:
+            tol = np.atleast_1d(tol)
+
+    near_zeros = abs_fc <= tol
+    is_near_singular = np.any(near_zeros)
+    if is_near_singular:
+        if singular == 'raise':
+            raise LinAlgError("near singular circulant matrix.")
+        else:
+            # Replace the small values with 1 to avoid errors in the
+            # division fb/fc below.
+            fc[near_zeros] = 1
+
+    fb = np.fft.fft(np.moveaxis(b, baxis, -1), axis=-1)
+
+    q = fb / fc
+
+    if is_near_singular:
+        # `near_zeros` is a boolean array, same shape as `c`, that is
+        # True where `fc` is (near) zero. `q` is the broadcasted result
+        # of fb / fc, so to set the values of `q` to 0 where `fc` is near
+        # zero, we use a mask that is the broadcast result of an array
+        # of True values shaped like `b` with `near_zeros`.
+        mask = np.ones_like(b, dtype=bool) & near_zeros
+        q[mask] = 0
+
+    x = np.fft.ifft(q, axis=-1)
+    if not (np.iscomplexobj(c) or np.iscomplexobj(b)):
+        x = x.real
+    if outaxis != -1:
+        x = np.moveaxis(x, -1, outaxis)
+    return x
+
+
+# matrix inversion
+def inv(a, overwrite_a=False, check_finite=True):
+    """
+    Compute the inverse of a matrix.
+
+    Parameters
+    ----------
+    a : array_like
+        Square matrix to be inverted.
+    overwrite_a : bool, optional
+        Discard data in `a` (may improve performance). Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    ainv : ndarray
+        Inverse of the matrix `a`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular.
+    ValueError
+        If `a` is not square, or not 2D.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1., 2.], [3., 4.]])
+    >>> linalg.inv(a)
+    array([[-2. ,  1. ],
+           [ 1.5, -0.5]])
+    >>> np.dot(a, linalg.inv(a))
+    array([[ 1.,  0.],
+           [ 0.,  1.]])
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    # accommodate empty square matrices
+    if a1.size == 0:
+        dt = inv(np.eye(2, dtype=a1.dtype)).dtype
+        return np.empty_like(a1, dtype=dt)
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri',
+                                                  'getri_lwork'),
+                                                 (a1,))
+    lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
+    if info == 0:
+        lwork = _compute_lwork(getri_lwork, a1.shape[0])
+
+        # XXX: the following line fixes curious SEGFAULT when
+        # benchmarking 500x500 matrix inverse. This seems to
+        # be a bug in LAPACK ?getri routine because if lwork is
+        # minimal (when using lwork[0] instead of lwork[1]) then
+        # all tests pass. Further investigation is required if
+        # more such SEGFAULTs occur.
+        lwork = int(1.01 * lwork)
+        inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
+    if info > 0:
+        raise LinAlgError("singular matrix")
+    if info < 0:
+        raise ValueError('illegal value in %d-th argument of internal '
+                         'getrf|getri' % -info)
+    return inv_a
+
+
+# Determinant
+
+def det(a, overwrite_a=False, check_finite=True):
+    """
+    Compute the determinant of a matrix
+
+    The determinant is a scalar that is a function of the associated square
+    matrix coefficients. The determinant value is zero for singular matrices.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Input array to compute determinants for.
+    overwrite_a : bool, optional
+        Allow overwriting data in a (may enhance performance).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    det : (...) float or complex
+        Determinant of `a`. For stacked arrays, a scalar is returned for each
+        (m, m) slice in the last two dimensions of the input. For example, an
+        input of shape (p, q, m, m) will produce a result of shape (p, q). If
+        all dimensions are 1 a scalar is returned regardless of ndim.
+
+    Notes
+    -----
+    The determinant is computed by performing an LU factorization of the
+    input with LAPACK routine 'getrf', and then calculating the product of
+    diagonal entries of the U factor.
+
+    Even if the input array is single precision (float32 or complex64), the
+    result will be returned in double precision (float64 or complex128) to
+    prevent overflows.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])  # A singular matrix
+    >>> linalg.det(a)
+    0.0
+    >>> b = np.array([[0,2,3], [4,5,6], [7,8,9]])
+    >>> linalg.det(b)
+    3.0
+    >>> # An array with the shape (3, 2, 2, 2)
+    >>> c = np.array([[[[1., 2.], [3., 4.]],
+    ...                [[5., 6.], [7., 8.]]],
+    ...               [[[9., 10.], [11., 12.]],
+    ...                [[13., 14.], [15., 16.]]],
+    ...               [[[17., 18.], [19., 20.]],
+    ...                [[21., 22.], [23., 24.]]]])
+    >>> linalg.det(c)  # The resulting shape is (3, 2)
+    array([[-2., -2.],
+           [-2., -2.],
+           [-2., -2.]])
+    >>> linalg.det(c[0, 0])  # Confirm the (0, 0) slice, [[1, 2], [3, 4]]
+    -2.0
+    """
+    # The goal is to end up with a writable contiguous array to pass to Cython
+
+    # First we check and make arrays.
+    a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+    if a1.shape[-1] != a1.shape[-2]:
+        raise ValueError('Last 2 dimensions of the array must be square'
+                         f' but received shape {a1.shape}.')
+
+    # Also check if dtype is LAPACK compatible
+    if a1.dtype.char not in 'fdFD':
+        dtype_char = lapack_cast_dict[a1.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype "{a1.dtype.name}" cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a1 = a1.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+
+    # Empty array has determinant 1 because math.
+    if min(*a1.shape) == 0:
+        dtyp = np.float64 if a1.dtype.char not in 'FD' else np.complex128
+        if a1.ndim == 2:
+            return dtyp(1.0)
+        else:
+            return np.ones(shape=a1.shape[:-2], dtype=dtyp)
+
+    # Scalar case
+    if a1.shape[-2:] == (1, 1):
+        a1 = a1[..., 0, 0]
+        if a1.ndim == 0:
+            a1 = a1[()]
+        # Convert float32 to float64, and complex64 to complex128.
+        if a1.dtype.char in 'dD':
+            return a1
+        return a1.astype('d') if a1.dtype.char == 'f' else a1.astype('D')
+
+    # Then check overwrite permission
+    if not _datacopied(a1, a):  # "a"  still alive through "a1"
+        if not overwrite_a:
+            # Data belongs to "a" so make a copy
+            a1 = a1.copy(order='C')
+        #  else: Do nothing we'll use "a" if possible
+    # else:  a1 has its own data thus free to scratch
+
+    # Then layout checks, might happen that overwrite is allowed but original
+    # array was read-only or non-C-contiguous.
+    if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
+        a1 = a1.copy(order='C')
+
+    if a1.ndim == 2:
+        det = find_det_from_lu(a1)
+        # Convert float, complex to NumPy scalars
+        return (np.float64(det) if np.isrealobj(det) else np.complex128(det))
+
+    # loop over the stacked array, and avoid overflows for single precision
+    # Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32))
+    dtype_char = a1.dtype.char
+    if dtype_char in 'fF':
+        dtype_char = 'd' if dtype_char.islower() else 'D'
+
+    det = np.empty(a1.shape[:-2], dtype=dtype_char)
+    for ind in product(*[range(x) for x in a1.shape[:-2]]):
+        det[ind] = find_det_from_lu(a1[ind])
+    return det
+
+
+# Linear Least Squares
+def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,
+          check_finite=True, lapack_driver=None):
+    """
+    Compute least-squares solution to equation Ax = b.
+
+    Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Left-hand side array
+    b : (M,) or (M, K) array_like
+        Right hand side array
+    cond : float, optional
+        Cutoff for 'small' singular values; used to determine effective
+        rank of a. Singular values smaller than
+        ``cond * largest_singular_value`` are considered zero.
+    overwrite_a : bool, optional
+        Discard data in `a` (may enhance performance). Default is False.
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance). Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : str, optional
+        Which LAPACK driver is used to solve the least-squares problem.
+        Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default
+        (``'gelsd'``) is a good choice.  However, ``'gelsy'`` can be slightly
+        faster on many problems.  ``'gelss'`` was used historically.  It is
+        generally slow but uses less memory.
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    x : (N,) or (N, K) ndarray
+        Least-squares solution.
+    residues : (K,) ndarray or float
+        Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and
+        ``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise a
+        (0,)-shaped array is returned.
+    rank : int
+        Effective rank of `a`.
+    s : (min(M, N),) ndarray or None
+        Singular values of `a`. The condition number of ``a`` is
+        ``s[0] / s[-1]``.
+
+    Raises
+    ------
+    LinAlgError
+        If computation does not converge.
+
+    ValueError
+        When parameters are not compatible.
+
+    See Also
+    --------
+    scipy.optimize.nnls : linear least squares with non-negativity constraint
+
+    Notes
+    -----
+    When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped
+    array and `s` is always ``None``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lstsq
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have the following data:
+
+    >>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
+    >>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])
+
+    We want to fit a quadratic polynomial of the form ``y = a + b*x**2``
+    to this data.  We first form the "design matrix" M, with a constant
+    column of 1s and a column containing ``x**2``:
+
+    >>> M = x[:, np.newaxis]**[0, 2]
+    >>> M
+    array([[  1.  ,   1.  ],
+           [  1.  ,   6.25],
+           [  1.  ,  12.25],
+           [  1.  ,  16.  ],
+           [  1.  ,  25.  ],
+           [  1.  ,  49.  ],
+           [  1.  ,  72.25]])
+
+    We want to find the least-squares solution to ``M.dot(p) = y``,
+    where ``p`` is a vector with length 2 that holds the parameters
+    ``a`` and ``b``.
+
+    >>> p, res, rnk, s = lstsq(M, y)
+    >>> p
+    array([ 0.20925829,  0.12013861])
+
+    Plot the data and the fitted curve.
+
+    >>> plt.plot(x, y, 'o', label='data')
+    >>> xx = np.linspace(0, 9, 101)
+    >>> yy = p[0] + p[1]*xx**2
+    >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
+    >>> plt.xlabel('x')
+    >>> plt.ylabel('y')
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.grid(alpha=0.25)
+    >>> plt.show()
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+    if len(a1.shape) != 2:
+        raise ValueError('Input array a should be 2D')
+    m, n = a1.shape
+    if len(b1.shape) == 2:
+        nrhs = b1.shape[1]
+    else:
+        nrhs = 1
+    if m != b1.shape[0]:
+        raise ValueError('Shape mismatch: a and b should have the same number'
+                         f' of rows ({m} != {b1.shape[0]}).')
+    if m == 0 or n == 0:  # Zero-sized problem, confuses LAPACK
+        x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1))
+        if n == 0:
+            residues = np.linalg.norm(b1, axis=0)**2
+        else:
+            residues = np.empty((0,))
+        return x, residues, 0, np.empty((0,))
+
+    driver = lapack_driver
+    if driver is None:
+        driver = lstsq.default_lapack_driver
+    if driver not in ('gelsd', 'gelsy', 'gelss'):
+        raise ValueError(f'LAPACK driver "{driver}" is not found')
+
+    lapack_func, lapack_lwork = get_lapack_funcs((driver,
+                                                 f'{driver}_lwork'),
+                                                 (a1, b1))
+    real_data = True if (lapack_func.dtype.kind == 'f') else False
+
+    if m < n:
+        # need to extend b matrix as it will be filled with
+        # a larger solution matrix
+        if len(b1.shape) == 2:
+            b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype)
+            b2[:m, :] = b1
+        else:
+            b2 = np.zeros(n, dtype=lapack_func.dtype)
+            b2[:m] = b1
+        b1 = b2
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if cond is None:
+        cond = np.finfo(lapack_func.dtype).eps
+
+    if driver in ('gelss', 'gelsd'):
+        if driver == 'gelss':
+            lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+            v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork,
+                                                    overwrite_a=overwrite_a,
+                                                    overwrite_b=overwrite_b)
+
+        elif driver == 'gelsd':
+            if real_data:
+                lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+                x, s, rank, info = lapack_func(a1, b1, lwork,
+                                               iwork, cond, False, False)
+            else:  # complex data
+                lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n,
+                                                     nrhs, cond)
+                x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork,
+                                               cond, False, False)
+        if info > 0:
+            raise LinAlgError("SVD did not converge in Linear Least Squares")
+        if info < 0:
+            raise ValueError('illegal value in %d-th argument of internal %s'
+                             % (-info, lapack_driver))
+        resids = np.asarray([], dtype=x.dtype)
+        if m > n:
+            x1 = x[:n]
+            if rank == n:
+                resids = np.sum(np.abs(x[n:])**2, axis=0)
+            x = x1
+        return x, resids, rank, s
+
+    elif driver == 'gelsy':
+        lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+        jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+        v, x, j, rank, info = lapack_func(a1, b1, jptv, cond,
+                                          lwork, False, False)
+        if info < 0:
+            raise ValueError("illegal value in %d-th argument of internal "
+                             "gelsy" % -info)
+        if m > n:
+            x1 = x[:n]
+            x = x1
+        return x, np.array([], x.dtype), rank, None
+
+
+lstsq.default_lapack_driver = 'gelsd'
+
+
+def pinv(a, *, atol=None, rtol=None, return_rank=False, check_finite=True):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a matrix.
+
+    Calculate a generalized inverse of a matrix using its
+    singular-value decomposition ``U @ S @ V`` in the economy mode and picking
+    up only the columns/rows that are associated with significant singular
+    values.
+
+    If ``s`` is the maximum singular value of ``a``, then the
+    significance cut-off value is determined by ``atol + rtol * s``. Any
+    singular value below this value is assumed insignificant.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be pseudo-inverted.
+    atol : float, optional
+        Absolute threshold term, default value is 0.
+
+        .. versionadded:: 1.7.0
+
+    rtol : float, optional
+        Relative threshold term, default value is ``max(M, N) * eps`` where
+        ``eps`` is the machine precision value of the datatype of ``a``.
+
+        .. versionadded:: 1.7.0
+
+    return_rank : bool, optional
+        If True, return the effective rank of the matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    B : (N, M) ndarray
+        The pseudo-inverse of matrix `a`.
+    rank : int
+        The effective rank of the matrix. Returned if `return_rank` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    pinvh : Moore-Penrose pseudoinverse of a hermitian matrix.
+
+    Notes
+    -----
+    If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly
+    the inverse of ``A`` [1]_. If ``A`` is not invertible then the
+    Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such
+    that ``||Ax - b||`` is minimized [1]_.
+
+    References
+    ----------
+    .. [1] Penrose, R. (1956). On best approximate solutions of linear matrix
+           equations. Mathematical Proceedings of the Cambridge Philosophical
+           Society, 52(1), 17-19. doi:10.1017/S0305004100030929
+
+    Examples
+    --------
+
+    Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four
+    Moore-Penrose conditions are:
+
+    1. ``ABA = A`` (``B`` is a generalized inverse of ``A``),
+    2. ``BAB = B`` (``A`` is a generalized inverse of ``B``),
+    3. ``(AB)* = AB`` (``AB`` is hermitian),
+    4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_.
+
+    Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose
+    pseudoinverse is a unique ``B`` that satisfies all four of these
+    conditions and exists for any ``A``. Note that, unlike the standard
+    matrix inverse, ``A`` does not have to be a square matrix or have
+    linearly independent columns/rows.
+
+    As an example, we can calculate the Moore-Penrose pseudoinverse of a
+    random non-square matrix and verify it satisfies the four conditions.
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> A = rng.standard_normal((9, 6))
+    >>> B = linalg.pinv(A)
+    >>> np.allclose(A @ B @ A, A)  # Condition 1
+    True
+    >>> np.allclose(B @ A @ B, B)  # Condition 2
+    True
+    >>> np.allclose((A @ B).conj().T, A @ B)  # Condition 3
+    True
+    >>> np.allclose((B @ A).conj().T, B @ A)  # Condition 4
+    True
+
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    u, s, vh = _decomp_svd.svd(a, full_matrices=False, check_finite=False)
+    t = u.dtype.char.lower()
+    maxS = np.max(s, initial=0.)
+
+    atol = 0. if atol is None else atol
+    rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
+
+    if (atol < 0.) or (rtol < 0.):
+        raise ValueError("atol and rtol values must be positive.")
+
+    val = atol + maxS * rtol
+    rank = np.sum(s > val)
+
+    u = u[:, :rank]
+    u /= s[:rank]
+    B = (u @ vh[:rank]).conj().T
+
+    if return_rank:
+        return B, rank
+    else:
+        return B
+
+
+def pinvh(a, atol=None, rtol=None, lower=True, return_rank=False,
+          check_finite=True):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
+
+    Calculate a generalized inverse of a complex Hermitian/real symmetric
+    matrix using its eigenvalue decomposition and including all eigenvalues
+    with 'large' absolute value.
+
+    Parameters
+    ----------
+    a : (N, N) array_like
+        Real symmetric or complex hermetian matrix to be pseudo-inverted
+
+    atol : float, optional
+        Absolute threshold term, default value is 0.
+
+        .. versionadded:: 1.7.0
+
+    rtol : float, optional
+        Relative threshold term, default value is ``N * eps`` where
+        ``eps`` is the machine precision value of the datatype of ``a``.
+
+        .. versionadded:: 1.7.0
+
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of `a`. (Default: lower)
+    return_rank : bool, optional
+        If True, return the effective rank of the matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    B : (N, N) ndarray
+        The pseudo-inverse of matrix `a`.
+    rank : int
+        The effective rank of the matrix.  Returned if `return_rank` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue algorithm does not converge.
+
+    See Also
+    --------
+    pinv : Moore-Penrose pseudoinverse of a matrix.
+
+    Examples
+    --------
+
+    For a more detailed example see `pinv`.
+
+    >>> import numpy as np
+    >>> from scipy.linalg import pinvh
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((9, 6))
+    >>> a = np.dot(a, a.T)
+    >>> B = pinvh(a)
+    >>> np.allclose(a, a @ B @ a)
+    True
+    >>> np.allclose(B, B @ a @ B)
+    True
+
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    s, u = _decomp.eigh(a, lower=lower, check_finite=False, driver='ev')
+    t = u.dtype.char.lower()
+    maxS = np.max(np.abs(s), initial=0.)
+
+    atol = 0. if atol is None else atol
+    rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
+
+    if (atol < 0.) or (rtol < 0.):
+        raise ValueError("atol and rtol values must be positive.")
+
+    val = atol + maxS * rtol
+    above_cutoff = (abs(s) > val)
+
+    psigma_diag = 1.0 / s[above_cutoff]
+    u = u[:, above_cutoff]
+
+    B = (u * psigma_diag) @ u.conj().T
+
+    if return_rank:
+        return B, len(psigma_diag)
+    else:
+        return B
+
+
+def matrix_balance(A, permute=True, scale=True, separate=False,
+                   overwrite_a=False):
+    """
+    Compute a diagonal similarity transformation for row/column balancing.
+
+    The balancing tries to equalize the row and column 1-norms by applying
+    a similarity transformation such that the magnitude variation of the
+    matrix entries is reflected to the scaling matrices.
+
+    Moreover, if enabled, the matrix is first permuted to isolate the upper
+    triangular parts of the matrix and, again if scaling is also enabled,
+    only the remaining subblocks are subjected to scaling.
+
+    The balanced matrix satisfies the following equality
+
+    .. math::
+
+                        B = T^{-1} A T
+
+    The scaling coefficients are approximated to the nearest power of 2
+    to avoid round-off errors.
+
+    Parameters
+    ----------
+    A : (n, n) array_like
+        Square data matrix for the balancing.
+    permute : bool, optional
+        The selector to define whether permutation of A is also performed
+        prior to scaling.
+    scale : bool, optional
+        The selector to turn on and off the scaling. If False, the matrix
+        will not be scaled.
+    separate : bool, optional
+        This switches from returning a full matrix of the transformation
+        to a tuple of two separate 1-D permutation and scaling arrays.
+    overwrite_a : bool, optional
+        This is passed to xGEBAL directly. Essentially, overwrites the result
+        to the data. It might increase the space efficiency. See LAPACK manual
+        for details. This is False by default.
+
+    Returns
+    -------
+    B : (n, n) ndarray
+        Balanced matrix
+    T : (n, n) ndarray
+        A possibly permuted diagonal matrix whose nonzero entries are
+        integer powers of 2 to avoid numerical truncation errors.
+    scale, perm : (n,) ndarray
+        If ``separate`` keyword is set to True then instead of the array
+        ``T`` above, the scaling and the permutation vectors are given
+        separately as a tuple without allocating the full array ``T``.
+
+    Notes
+    -----
+    This algorithm is particularly useful for eigenvalue and matrix
+    decompositions and in many cases it is already called by various
+    LAPACK routines.
+
+    The algorithm is based on the well-known technique of [1]_ and has
+    been modified to account for special cases. See [2]_ for details
+    which have been implemented since LAPACK v3.5.0. Before this version
+    there are corner cases where balancing can actually worsen the
+    conditioning. See [3]_ for such examples.
+
+    The code is a wrapper around LAPACK's xGEBAL routine family for matrix
+    balancing.
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for
+       Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik,
+       Vol.13(4), 1969, :doi:`10.1007/BF02165404`
+    .. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and
+       eigenvector computation", 2014, :arxiv:`1401.5766`
+    .. [3] D.S. Watkins. A case where balancing is harmful.
+       Electron. Trans. Numer. Anal, Vol.23, 2006.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])
+
+    >>> y, permscale = linalg.matrix_balance(x)
+    >>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
+    array([ 3.66666667,  0.4995005 ,  0.91312162])
+
+    >>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
+    array([ 1.2       ,  1.27041742,  0.92658316])  # may vary
+
+    >>> permscale  # only powers of 2 (0.5 == 2^(-1))
+    array([[  0.5,   0. ,  0. ],  # may vary
+           [  0. ,   1. ,  0. ],
+           [  0. ,   0. ,  1. ]])
+
+    """
+
+    A = np.atleast_2d(_asarray_validated(A, check_finite=True))
+
+    if not np.equal(*A.shape):
+        raise ValueError('The data matrix for balancing should be square.')
+
+    # accommodate empty arrays
+    if A.size == 0:
+        b_n, t_n = matrix_balance(np.eye(2, dtype=A.dtype))
+        B = np.empty_like(A, dtype=b_n.dtype)
+        if separate:
+            scaling = np.ones_like(A, shape=len(A))
+            perm = np.arange(len(A))
+            return B, (scaling, perm)
+        return B, np.empty_like(A, dtype=t_n.dtype)
+
+    gebal = get_lapack_funcs(('gebal'), (A,))
+    B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute,
+                                overwrite_a=overwrite_a)
+
+    if info < 0:
+        raise ValueError('xGEBAL exited with the internal error '
+                         f'"illegal value in argument number {-info}.". See '
+                         'LAPACK documentation for the xGEBAL error codes.')
+
+    # Separate the permutations from the scalings and then convert to int
+    scaling = np.ones_like(ps, dtype=float)
+    scaling[lo:hi+1] = ps[lo:hi+1]
+
+    # gebal uses 1-indexing
+    ps = ps.astype(int, copy=False) - 1
+    n = A.shape[0]
+    perm = np.arange(n)
+
+    # LAPACK permutes with the ordering n --> hi, then 0--> lo
+    if hi < n:
+        for ind, x in enumerate(ps[hi+1:][::-1], 1):
+            if n-ind == x:
+                continue
+            perm[[x, n-ind]] = perm[[n-ind, x]]
+
+    if lo > 0:
+        for ind, x in enumerate(ps[:lo]):
+            if ind == x:
+                continue
+            perm[[x, ind]] = perm[[ind, x]]
+
+    if separate:
+        return B, (scaling, perm)
+
+    # get the inverse permutation
+    iperm = np.empty_like(perm)
+    iperm[perm] = np.arange(n)
+
+    return B, np.diag(scaling)[iperm, :]
+
+
+def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape,
+                                    enforce_square=True):
+    """Validate arguments and format inputs for toeplitz functions
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
+        actual shape of ``c``, it will be converted to a 1-D array. If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
+        of ``r``, it will be converted to a 1-D array.
+    b : (M,) or (M, K) array_like
+        Right-hand side in ``T x = b``.
+    check_finite : bool
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+    keep_b_shape : bool
+        Whether to convert a (M,) dimensional b into a (M, 1) dimensional
+        matrix.
+    enforce_square : bool, optional
+        If True (default), this verifies that the Toeplitz matrix is square.
+
+    Returns
+    -------
+    r : array
+        1d array corresponding to the first row of the Toeplitz matrix.
+    c: array
+        1d array corresponding to the first column of the Toeplitz matrix.
+    b: array
+        (M,), (M, 1) or (M, K) dimensional array, post validation,
+        corresponding to ``b``.
+    dtype: numpy datatype
+        ``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of
+        ``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``,
+        otherwise, it is ``np.float``.
+    b_shape: tuple
+        Shape of ``b`` after passing it through ``_asarray_validated``.
+
+    """
+
+    if isinstance(c_or_cr, tuple):
+        c, r = c_or_cr
+        c = _asarray_validated(c, check_finite=check_finite)
+        r = _asarray_validated(r, check_finite=check_finite)
+    else:
+        c = _asarray_validated(c_or_cr, check_finite=check_finite)
+        r = c.conjugate()
+
+    if c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a "
+               "batch, not `ravel`ed. To preserve the existing behavior and silence "
+               "this warning, `ravel` arguments before passing them to "
+               "`toeplitz`, `matmul_toeplitz`, and `solve_toeplitz`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+        c = c.ravel()
+        r = r.ravel()
+
+    if b is None:
+        raise ValueError('`b` must be an array, not None.')
+
+    b = _asarray_validated(b, check_finite=check_finite)
+    b_shape = b.shape
+
+    is_not_square = r.shape[0] != c.shape[0]
+    if (enforce_square and is_not_square) or b.shape[0] != r.shape[0]:
+        raise ValueError('Incompatible dimensions.')
+
+    is_cmplx = np.iscomplexobj(r) or np.iscomplexobj(c) or np.iscomplexobj(b)
+    dtype = np.complex128 if is_cmplx else np.float64
+    r, c, b = (np.asarray(i, dtype=dtype) for i in (r, c, b))
+
+    if b.ndim == 1 and not keep_b_shape:
+        b = b.reshape(-1, 1)
+    elif b.ndim != 1:
+        b = b.reshape(b.shape[0], -1 if b.size > 0 else 0)
+
+    return r, c, b, dtype, b_shape
+
+
+def matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None):
+    r"""Efficient Toeplitz Matrix-Matrix Multiplication using FFT
+
+    This function returns the matrix multiplication between a Toeplitz
+    matrix and a dense matrix.
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    .. warning::
+
+        Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+        not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+        before passing them to `matmul_toeplitz`.
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``.
+    x : (M,) or (M, K) array_like
+        Matrix with which to multiply.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+    workers : int, optional
+        To pass to scipy.fft.fft and ifft. Maximum number of workers to use
+        for parallel computation. If negative, the value wraps around from
+        ``os.cpu_count()``. See scipy.fft.fft for more details.
+
+    Returns
+    -------
+    T @ x : (M,) or (M, K) ndarray
+        The result of the matrix multiplication ``T @ x``. Shape of return
+        matches shape of `x`.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    solve_toeplitz : Solve a Toeplitz system using Levinson Recursion
+
+    Notes
+    -----
+    The Toeplitz matrix is embedded in a circulant matrix and the FFT is used
+    to efficiently calculate the matrix-matrix product.
+
+    Because the computation is based on the FFT, integer inputs will
+    result in floating point outputs.  This is unlike NumPy's `matmul`,
+    which preserves the data type of the input.
+
+    This is partly based on the implementation that can be found in [1]_,
+    licensed under the MIT license. More information about the method can be
+    found in reference [2]_. References [3]_ and [4]_ have more reference
+    implementations in Python.
+
+    .. versionadded:: 1.6.0
+
+    References
+    ----------
+    .. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian
+       Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix
+       Gaussian Process Inference with GPU Acceleration" with contributions
+       from Max Balandat and Ruihan Wu. Available online:
+       https://github.com/cornellius-gp/gpytorch
+
+    .. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear
+       Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der
+       Vorst, editors. Templates for the Solution of Algebraic Eigenvalue
+       Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at:
+       http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html
+
+    .. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python
+       package for audio room simulations and array processing algorithms,
+       Proc. IEEE ICASSP, Calgary, CA, 2018.
+       https://github.com/LCAV/pyroomacoustics/blob/pypi-release/
+       pyroomacoustics/adaptive/util.py
+
+    .. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting
+       Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of
+       the Seismological Society of America., January, 2017. Vol. 107(1),
+       pp. 276-291.
+
+    Examples
+    --------
+    Multiply the Toeplitz matrix T with matrix x::
+
+            [ 1 -1 -2 -3]       [1 10]
+        T = [ 3  1 -1 -2]   x = [2 11]
+            [ 6  3  1 -1]       [2 11]
+            [10  6  3  1]       [5 19]
+
+    To specify the Toeplitz matrix, only the first column and the first
+    row are needed.
+
+    >>> import numpy as np
+    >>> c = np.array([1, 3, 6, 10])    # First column of T
+    >>> r = np.array([1, -1, -2, -3])  # First row of T
+    >>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]])
+
+    >>> from scipy.linalg import toeplitz, matmul_toeplitz
+    >>> matmul_toeplitz((c, r), x)
+    array([[-20., -80.],
+           [ -7.,  -8.],
+           [  9.,  85.],
+           [ 33., 218.]])
+
+    Check the result by creating the full Toeplitz matrix and
+    multiplying it by ``x``.
+
+    >>> toeplitz(c, r) @ x
+    array([[-20, -80],
+           [ -7,  -8],
+           [  9,  85],
+           [ 33, 218]])
+
+    The full matrix is never formed explicitly, so this routine
+    is suitable for very large Toeplitz matrices.
+
+    >>> n = 1000000
+    >>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n))
+    array([1., 1., 1., ..., 1., 1., 1.], shape=(1000000,))
+
+    """
+
+    from ..fft import fft, ifft, rfft, irfft
+
+    r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops(
+        c_or_cr, x, check_finite, keep_b_shape=False, enforce_square=False)
+    n, m = x.shape
+
+    T_nrows = len(c)
+    T_ncols = len(r)
+    p = T_nrows + T_ncols - 1  # equivalent to len(embedded_col)
+    return_shape = (T_nrows,) if len(x_shape) == 1 else (T_nrows, m)
+
+    # accommodate empty arrays
+    if x.size == 0:
+        return np.empty_like(x, shape=return_shape)
+
+    embedded_col = np.concatenate((c, r[-1:0:-1]))
+
+    if np.iscomplexobj(embedded_col) or np.iscomplexobj(x):
+        fft_mat = fft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
+        fft_x = fft(x, n=p, axis=0, workers=workers)
+
+        mat_times_x = ifft(fft_mat*fft_x, axis=0,
+                           workers=workers)[:T_nrows, :]
+    else:
+        # Real inputs; using rfft is faster
+        fft_mat = rfft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
+        fft_x = rfft(x, n=p, axis=0, workers=workers)
+
+        mat_times_x = irfft(fft_mat*fft_x, axis=0,
+                            workers=workers, n=p)[:T_nrows, :]
+
+    return mat_times_x.reshape(*return_shape)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h b/venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..a175ca15f4adbed6d5c576e9e5ee1117abbd31ec
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h
@@ -0,0 +1,164 @@
+/*
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+*/
+
+#include "npy_cblas.h"
+#include "fortran_defs.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void BLAS_FUNC(caxpy)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(ccopy)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void F_FUNC(cdotcwrp,CDOTCWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void F_FUNC(cdotuwrp,CDOTUWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(cgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(cgemv)(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cgerc)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cgeru)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(chbmv)(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(chemm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(chemv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cher)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cher2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cher2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(cherk)(char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(chpmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(chpr)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
+void BLAS_FUNC(chpr2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap);
+void BLAS_FUNC(crotg)(npy_complex64 *ca, npy_complex64 *cb, float *c, npy_complex64 *s);
+void BLAS_FUNC(cscal)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(csrot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, float *s);
+void BLAS_FUNC(csscal)(int *n, float *sa, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(cswap)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(csymm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(csyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(csyrk)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(ctbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+double BLAS_FUNC(dasum)(int *n, double *dx, int *incx);
+void BLAS_FUNC(daxpy)(int *n, double *da, double *dx, int *incx, double *dy, int *incy);
+double BLAS_FUNC(dcabs1)(npy_complex128 *z);
+void BLAS_FUNC(dcopy)(int *n, double *dx, int *incx, double *dy, int *incy);
+double BLAS_FUNC(ddot)(int *n, double *dx, int *incx, double *dy, int *incy);
+void BLAS_FUNC(dgbmv)(char *trans, int *m, int *n, int *kl, int *ku, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dgemm)(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dgemv)(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dger)(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
+double BLAS_FUNC(dnrm2)(int *n, double *x, int *incx);
+void BLAS_FUNC(drot)(int *n, double *dx, int *incx, double *dy, int *incy, double *c, double *s);
+void BLAS_FUNC(drotg)(double *da, double *db, double *c, double *s);
+void BLAS_FUNC(drotm)(int *n, double *dx, int *incx, double *dy, int *incy, double *dparam);
+void BLAS_FUNC(drotmg)(double *dd1, double *dd2, double *dx1, double *dy1, double *dparam);
+void BLAS_FUNC(dsbmv)(char *uplo, int *n, int *k, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dscal)(int *n, double *da, double *dx, int *incx);
+double BLAS_FUNC(dsdot)(int *n, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(dspmv)(char *uplo, int *n, double *alpha, double *ap, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dspr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *ap);
+void BLAS_FUNC(dspr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *ap);
+void BLAS_FUNC(dswap)(int *n, double *dx, int *incx, double *dy, int *incy);
+void BLAS_FUNC(dsymm)(char *side, char *uplo, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dsymv)(char *uplo, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dsyr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *a, int *lda);
+void BLAS_FUNC(dsyr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
+void BLAS_FUNC(dsyr2k)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dsyrk)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dtbmv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtbsv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtpmv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
+void BLAS_FUNC(dtpsv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
+void BLAS_FUNC(dtrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dtrmv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dtrsv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
+double BLAS_FUNC(dzasum)(int *n, npy_complex128 *zx, int *incx);
+double BLAS_FUNC(dznrm2)(int *n, npy_complex128 *x, int *incx);
+int BLAS_FUNC(icamax)(int *n, npy_complex64 *cx, int *incx);
+int BLAS_FUNC(idamax)(int *n, double *dx, int *incx);
+int BLAS_FUNC(isamax)(int *n, float *sx, int *incx);
+int BLAS_FUNC(izamax)(int *n, npy_complex128 *zx, int *incx);
+int BLAS_FUNC(lsame)(char *ca, char *cb);
+float BLAS_FUNC(sasum)(int *n, float *sx, int *incx);
+void BLAS_FUNC(saxpy)(int *n, float *sa, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(scasum)(int *n, npy_complex64 *cx, int *incx);
+float BLAS_FUNC(scnrm2)(int *n, npy_complex64 *x, int *incx);
+void BLAS_FUNC(scopy)(int *n, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(sdot)(int *n, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(sdsdot)(int *n, float *sb, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(sgbmv)(char *trans, int *m, int *n, int *kl, int *ku, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sgemm)(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(sgemv)(char *trans, int *m, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sger)(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
+float BLAS_FUNC(snrm2)(int *n, float *x, int *incx);
+void BLAS_FUNC(srot)(int *n, float *sx, int *incx, float *sy, int *incy, float *c, float *s);
+void BLAS_FUNC(srotg)(float *sa, float *sb, float *c, float *s);
+void BLAS_FUNC(srotm)(int *n, float *sx, int *incx, float *sy, int *incy, float *sparam);
+void BLAS_FUNC(srotmg)(float *sd1, float *sd2, float *sx1, float *sy1, float *sparam);
+void BLAS_FUNC(ssbmv)(char *uplo, int *n, int *k, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sscal)(int *n, float *sa, float *sx, int *incx);
+void BLAS_FUNC(sspmv)(char *uplo, int *n, float *alpha, float *ap, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sspr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *ap);
+void BLAS_FUNC(sspr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *ap);
+void BLAS_FUNC(sswap)(int *n, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(ssymm)(char *side, char *uplo, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(ssymv)(char *uplo, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(ssyr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *a, int *lda);
+void BLAS_FUNC(ssyr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
+void BLAS_FUNC(ssyr2k)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(ssyrk)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c, int *ldc);
+void BLAS_FUNC(stbmv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(stbsv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(stpmv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
+void BLAS_FUNC(stpsv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
+void BLAS_FUNC(strmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(strmv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(strsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(strsv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(zaxpy)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zcopy)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void F_FUNC(zdotcwrp,ZDOTCWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void F_FUNC(zdotuwrp,ZDOTUWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zdrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, double *s);
+void BLAS_FUNC(zdscal)(int *n, double *da, npy_complex128 *zx, int *incx);
+void BLAS_FUNC(zgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zgemv)(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zgerc)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zgeru)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zhbmv)(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zhemm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zhemv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zher)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zher2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zher2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zherk)(char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zhpmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zhpr)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
+void BLAS_FUNC(zhpr2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap);
+void BLAS_FUNC(zrotg)(npy_complex128 *ca, npy_complex128 *cb, double *c, npy_complex128 *s);
+void BLAS_FUNC(zscal)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx);
+void BLAS_FUNC(zswap)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zsymm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zsyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zsyrk)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(ztbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd b/venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ccec61c078e57ba7b6a310ec57189fcf236c972d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd
@@ -0,0 +1,40 @@
+cimport numpy as cnp
+
+ctypedef fused lapack_t:
+    float
+    double
+    (float complex)
+    (double complex)
+
+ctypedef fused lapack_cz_t:
+    (float complex)
+    (double complex)
+
+ctypedef fused lapack_sd_t:
+    float
+    double
+
+ctypedef fused np_numeric_t:
+    cnp.int8_t
+    cnp.int16_t
+    cnp.int32_t
+    cnp.int64_t
+    cnp.uint8_t
+    cnp.uint16_t
+    cnp.uint32_t
+    cnp.uint64_t
+    cnp.float32_t
+    cnp.float64_t
+    cnp.longdouble_t
+    cnp.complex64_t
+    cnp.complex128_t
+
+ctypedef fused np_complex_numeric_t:
+    cnp.complex64_t
+    cnp.complex128_t
+
+
+cdef void swap_c_and_f_layout(lapack_t *a, lapack_t *b, int r, int c) noexcept nogil
+cdef (int, int) band_check_internal_c(np_numeric_t[:, ::1]A) noexcept nogil
+cdef bint is_sym_her_real_c_internal(np_numeric_t[:, ::1]A) noexcept nogil
+cdef bint is_sym_her_complex_c_internal(np_complex_numeric_t[:, ::1]A) noexcept nogil
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi b/venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5633cb61ecf3a90eba901120f64fa6cc6634fa5a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
@@ -0,0 +1,16 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def bandwidth(a: NDArray[Any]) -> tuple[int, int]: ...
+
+def issymmetric(
+    a: NDArray[Any],
+    atol: None | float = ...,
+    rtol: None | float = ...,
+) -> bool: ...
+
+def ishermitian(
+    a: NDArray[Any],
+    atol: None | float = ...,
+    rtol: None | float = ...,
+) -> bool: ...
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c520d6b04b6bf0a22c4fcad62d98a17faea7c9fd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py
@@ -0,0 +1,1632 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# additions by Travis Oliphant, March 2002
+# additions by Eric Jones,      June 2002
+# additions by Johannes Loehnert, June 2006
+# additions by Bart Vandereycken, June 2006
+# additions by Andrew D Straw, May 2007
+# additions by Tiziano Zito, November 2008
+#
+# April 2010: Functions for LU, QR, SVD, Schur, and Cholesky decompositions
+# were moved to their own files. Still in this file are functions for
+# eigenstuff and for the Hessenberg form.
+
+__all__ = ['eig', 'eigvals', 'eigh', 'eigvalsh',
+           'eig_banded', 'eigvals_banded',
+           'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf']
+
+import numpy as np
+from numpy import (array, isfinite, inexact, nonzero, iscomplexobj,
+                   flatnonzero, conj, asarray, argsort, empty,
+                   iscomplex, zeros, einsum, eye, inf)
+# Local imports
+from scipy._lib._util import _asarray_validated
+from ._misc import LinAlgError, _datacopied, norm
+from .lapack import get_lapack_funcs, _compute_lwork
+
+
+_I = np.array(1j, dtype='F')
+
+
+def _make_complex_eigvecs(w, vin, dtype):
+    """
+    Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
+    """
+    # - see LAPACK man page DGGEV at ALPHAI
+    v = np.array(vin, dtype=dtype)
+    m = (w.imag > 0)
+    m[:-1] |= (w.imag[1:] < 0)  # workaround for LAPACK bug, cf. ticket #709
+    for i in flatnonzero(m):
+        v.imag[:, i] = vin[:, i+1]
+        conj(v[:, i], v[:, i+1])
+    return v
+
+
+def _make_eigvals(alpha, beta, homogeneous_eigvals):
+    if homogeneous_eigvals:
+        if beta is None:
+            return np.vstack((alpha, np.ones_like(alpha)))
+        else:
+            return np.vstack((alpha, beta))
+    else:
+        if beta is None:
+            return alpha
+        else:
+            w = np.empty_like(alpha)
+            alpha_zero = (alpha == 0)
+            beta_zero = (beta == 0)
+            beta_nonzero = ~beta_zero
+            w[beta_nonzero] = alpha[beta_nonzero]/beta[beta_nonzero]
+            # Use np.inf for complex values too since
+            # 1/np.inf = 0, i.e., it correctly behaves as projective
+            # infinity.
+            w[~alpha_zero & beta_zero] = np.inf
+            if np.all(alpha.imag == 0):
+                w[alpha_zero & beta_zero] = np.nan
+            else:
+                w[alpha_zero & beta_zero] = complex(np.nan, np.nan)
+            return w
+
+
+def _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
+            homogeneous_eigvals):
+    ggev, = get_lapack_funcs(('ggev',), (a1, b1))
+    cvl, cvr = left, right
+    res = ggev(a1, b1, lwork=-1)
+    lwork = res[-2][0].real.astype(np.int_)
+    if ggev.typecode in 'cz':
+        alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
+                                               overwrite_a, overwrite_b)
+        w = _make_eigvals(alpha, beta, homogeneous_eigvals)
+    else:
+        alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr,
+                                                        lwork, overwrite_a,
+                                                        overwrite_b)
+        alpha = alphar + _I * alphai
+        w = _make_eigvals(alpha, beta, homogeneous_eigvals)
+    _check_info(info, 'generalized eig algorithm (ggev)')
+
+    only_real = np.all(w.imag == 0.0)
+    if not (ggev.typecode in 'cz' or only_real):
+        t = w.dtype.char
+        if left:
+            vl = _make_complex_eigvecs(w, vl, t)
+        if right:
+            vr = _make_complex_eigvecs(w, vr, t)
+
+    # the eigenvectors returned by the lapack function are NOT normalized
+    for i in range(vr.shape[0]):
+        if right:
+            vr[:, i] /= norm(vr[:, i])
+        if left:
+            vl[:, i] /= norm(vl[:, i])
+
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+def eig(a, b=None, left=False, right=True, overwrite_a=False,
+        overwrite_b=False, check_finite=True, homogeneous_eigvals=False):
+    """
+    Solve an ordinary or generalized eigenvalue problem of a square matrix.
+
+    Find eigenvalues w and right or left eigenvectors of a general matrix::
+
+        a   vr[:,i] = w[i]        b   vr[:,i]
+        a.H vl[:,i] = w[i].conj() b.H vl[:,i]
+
+    where ``.H`` is the Hermitian conjugation.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex or real matrix whose eigenvalues and eigenvectors
+        will be computed.
+    b : (M, M) array_like, optional
+        Right-hand side matrix in a generalized eigenvalue problem.
+        Default is None, identity matrix is assumed.
+    left : bool, optional
+        Whether to calculate and return left eigenvectors.  Default is False.
+    right : bool, optional
+        Whether to calculate and return right eigenvectors.  Default is True.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.  Default is False.
+    overwrite_b : bool, optional
+        Whether to overwrite `b`; may improve performance.  Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    homogeneous_eigvals : bool, optional
+        If True, return the eigenvalues in homogeneous coordinates.
+        In this case ``w`` is a (2, M) array so that::
+
+            w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
+
+        Default is False.
+
+    Returns
+    -------
+    w : (M,) or (2, M) double or complex ndarray
+        The eigenvalues, each repeated according to its
+        multiplicity. The shape is (M,) unless
+        ``homogeneous_eigvals=True``.
+    vl : (M, M) double or complex ndarray
+        The left eigenvector corresponding to the eigenvalue
+        ``w[i]`` is the column ``vl[:,i]``. Only returned if ``left=True``.
+        The left eigenvector is not normalized.
+    vr : (M, M) double or complex ndarray
+        The normalized right eigenvector corresponding to the eigenvalue
+        ``w[i]`` is the column ``vr[:,i]``.  Only returned if ``right=True``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals : eigenvalues of general arrays
+    eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+    eigh_tridiagonal : eigenvalues and right eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
+    >>> linalg.eigvals(a, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [1.+0.j, 1.+0.j, 1.+0.j]])
+
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a) == linalg.eig(a)[0]
+    array([ True,  True])
+    >>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector
+    array([[-0.70710678+0.j        , -0.70710678-0.j        ],
+           [-0.        +0.70710678j, -0.        -0.70710678j]])
+    >>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector
+    array([[0.70710678+0.j        , 0.70710678-0.j        ],
+           [0.        -0.70710678j, 0.        +0.70710678j]])
+
+
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, vr_n = eig(np.eye(2, dtype=a1.dtype))
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+        vl = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
+        vr = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
+        if not (left or right):
+            return w
+        if left:
+            if right:
+                return w, vl, vr
+            return w, vl
+        return w, vr
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    if b is not None:
+        b1 = _asarray_validated(b, check_finite=check_finite)
+        overwrite_b = overwrite_b or _datacopied(b1, b)
+        if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
+            raise ValueError('expected square matrix')
+        if b1.shape != a1.shape:
+            raise ValueError('a and b must have the same shape')
+        return _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
+                       homogeneous_eigvals)
+
+    geev, geev_lwork = get_lapack_funcs(('geev', 'geev_lwork'), (a1,))
+    compute_vl, compute_vr = left, right
+
+    lwork = _compute_lwork(geev_lwork, a1.shape[0],
+                           compute_vl=compute_vl,
+                           compute_vr=compute_vr)
+
+    if geev.typecode in 'cz':
+        w, vl, vr, info = geev(a1, lwork=lwork,
+                               compute_vl=compute_vl,
+                               compute_vr=compute_vr,
+                               overwrite_a=overwrite_a)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+    else:
+        wr, wi, vl, vr, info = geev(a1, lwork=lwork,
+                                    compute_vl=compute_vl,
+                                    compute_vr=compute_vr,
+                                    overwrite_a=overwrite_a)
+        w = wr + _I * wi
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+
+    _check_info(info, 'eig algorithm (geev)',
+                positive='did not converge (only eigenvalues '
+                         'with order >= %d have converged)')
+
+    only_real = np.all(w.imag == 0.0)
+    if not (geev.typecode in 'cz' or only_real):
+        t = w.dtype.char
+        if left:
+            vl = _make_complex_eigvecs(w, vl, t)
+        if right:
+            vr = _make_complex_eigvecs(w, vr, t)
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+def eigh(a, b=None, *, lower=True, eigvals_only=False, overwrite_a=False,
+         overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
+         subset_by_value=None, driver=None):
+    """
+    Solve a standard or generalized eigenvalue problem for a complex
+    Hermitian or real symmetric matrix.
+
+    Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of
+    array ``a``, where ``b`` is positive definite such that for every
+    eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of
+    ``v``) satisfies::
+
+                      a @ vi = λ * b @ vi
+        vi.conj().T @ a @ vi = λ
+        vi.conj().T @ b @ vi = 1
+
+    In the standard problem, ``b`` is assumed to be the identity matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex Hermitian or real symmetric matrix whose eigenvalues and
+        eigenvectors will be computed.
+    b : (M, M) array_like, optional
+        A complex Hermitian or real symmetric definite positive matrix in.
+        If omitted, identity matrix is assumed.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of ``a`` and, if applicable, ``b``. (Default: lower)
+    eigvals_only : bool, optional
+        Whether to calculate only eigenvalues and no eigenvectors.
+        (Default: both are calculated)
+    subset_by_index : iterable, optional
+        If provided, this two-element iterable defines the start and the end
+        indices of the desired eigenvalues (ascending order and 0-indexed).
+        To return only the second smallest to fifth smallest eigenvalues,
+        ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
+        available with "evr", "evx", and "gvx" drivers. The entries are
+        directly converted to integers via ``int()``.
+    subset_by_value : iterable, optional
+        If provided, this two-element iterable defines the half-open interval
+        ``(a, b]`` that, if any, only the eigenvalues between these values
+        are returned. Only available with "evr", "evx", and "gvx" drivers. Use
+        ``np.inf`` for the unconstrained ends.
+    driver : str, optional
+        Defines which LAPACK driver should be used. Valid options are "ev",
+        "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
+        generalized (where b is not None) problems. See the Notes section.
+        The default for standard problems is "evr". For generalized problems,
+        "gvd" is used for full set, and "gvx" for subset requested cases.
+    type : int, optional
+        For the generalized problems, this keyword specifies the problem type
+        to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
+        inputs)::
+
+            1 =>     a @ v = w @ b @ v
+            2 => a @ b @ v = w @ v
+            3 => b @ a @ v = w @ v
+
+        This keyword is ignored for standard problems.
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default
+        is False.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default
+        is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (N,) ndarray
+        The N (N<=M) selected eigenvalues, in ascending order, each
+        repeated according to its multiplicity.
+    v : (M, N) ndarray
+        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
+        the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge, an error occurred, or
+        b matrix is not definite positive. Note that if input matrices are
+        not symmetric or Hermitian, no error will be reported but results will
+        be wrong.
+
+    See Also
+    --------
+    eigvalsh : eigenvalues of symmetric or Hermitian arrays
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+    eigh_tridiagonal : eigenvalues and right eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Notes
+    -----
+    This function does not check the input array for being Hermitian/symmetric
+    in order to allow for representing arrays with only their upper/lower
+    triangular parts. Also, note that even though not taken into account,
+    finiteness check applies to the whole array and unaffected by "lower"
+    keyword.
+
+    This function uses LAPACK drivers for computations in all possible keyword
+    combinations, prefixed with ``sy`` if arrays are real and ``he`` if
+    complex, e.g., a float array with "evr" driver is solved via
+    "syevr", complex arrays with "gvx" driver problem is solved via "hegvx"
+    etc.
+
+    As a brief summary, the slowest and the most robust driver is the
+    classical ``ev`` which uses symmetric QR. ``evr`` is seen as
+    the optimal choice for the most general cases. However, there are certain
+    occasions that ``evd`` computes faster at the expense of more
+    memory usage. ``evx``, while still being faster than ``ev``,
+    often performs worse than the rest except when very few eigenvalues are
+    requested for large arrays though there is still no performance guarantee.
+
+    Note that the underlying LAPACK algorithms are different depending on whether
+    `eigvals_only` is True or False --- thus the eigenvalues may differ
+    depending on whether eigenvectors are requested or not. The difference is
+    generally of the order of machine epsilon times the largest eigenvalue,
+    so is likely only visible for zero or nearly zero eigenvalues.
+
+    For the generalized problem, normalization with respect to the given
+    type argument::
+
+            type 1 and 3 :      v.conj().T @ a @ v = w
+            type 2       : inv(v).conj().T @ a @ inv(v) = w
+
+            type 1 or 2  :      v.conj().T @ b @ v  = I
+            type 3       : v.conj().T @ inv(b) @ v  = I
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigh
+    >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
+    >>> w, v = eigh(A)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+
+    Request only the eigenvalues
+
+    >>> w = eigh(A, eigvals_only=True)
+
+    Request eigenvalues that are less than 10.
+
+    >>> A = np.array([[34, -4, -10, -7, 2],
+    ...               [-4, 7, 2, 12, 0],
+    ...               [-10, 2, 44, 2, -19],
+    ...               [-7, 12, 2, 79, -34],
+    ...               [2, 0, -19, -34, 29]])
+    >>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10])
+    array([6.69199443e-07, 9.11938152e+00])
+
+    Request the second smallest eigenvalue and its eigenvector
+
+    >>> w, v = eigh(A, subset_by_index=[1, 1])
+    >>> w
+    array([9.11938152])
+    >>> v.shape  # only a single column is returned
+    (5, 1)
+
+    """
+    # set lower
+    uplo = 'L' if lower else 'U'
+    # Set job for Fortran routines
+    _job = 'N' if eigvals_only else 'V'
+
+    drv_str = [None, "ev", "evd", "evr", "evx", "gv", "gvd", "gvx"]
+    if driver not in drv_str:
+        raise ValueError('"{}" is unknown. Possible values are "None", "{}".'
+                         ''.format(driver, '", "'.join(drv_str[1:])))
+
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square "a" matrix')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, v_n = eigh(np.eye(2, dtype=a1.dtype))
+
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    cplx = True if iscomplexobj(a1) else False
+    n = a1.shape[0]
+    drv_args = {'overwrite_a': overwrite_a}
+
+    if b is not None:
+        b1 = _asarray_validated(b, check_finite=check_finite)
+        overwrite_b = overwrite_b or _datacopied(b1, b)
+        if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
+            raise ValueError('expected square "b" matrix')
+
+        if b1.shape != a1.shape:
+            raise ValueError(f"wrong b dimensions {b1.shape}, should be {a1.shape}")
+
+        if type not in [1, 2, 3]:
+            raise ValueError('"type" keyword only accepts 1, 2, and 3.')
+
+        cplx = True if iscomplexobj(b1) else (cplx or False)
+        drv_args.update({'overwrite_b': overwrite_b, 'itype': type})
+
+    subset = (subset_by_index is not None) or (subset_by_value is not None)
+
+    # Both subsets can't be given
+    if subset_by_index and subset_by_value:
+        raise ValueError('Either index or value subset can be requested.')
+
+    # Check indices if given
+    if subset_by_index:
+        lo, hi = (int(x) for x in subset_by_index)
+        if not (0 <= lo <= hi < n):
+            raise ValueError('Requested eigenvalue indices are not valid. '
+                             f'Valid range is [0, {n-1}] and start <= end, but '
+                             f'start={lo}, end={hi} is given')
+        # fortran is 1-indexed
+        drv_args.update({'range': 'I', 'il': lo + 1, 'iu': hi + 1})
+
+    if subset_by_value:
+        lo, hi = subset_by_value
+        if not (-inf <= lo < hi <= inf):
+            raise ValueError('Requested eigenvalue bounds are not valid. '
+                             'Valid range is (-inf, inf) and low < high, but '
+                             f'low={lo}, high={hi} is given')
+
+        drv_args.update({'range': 'V', 'vl': lo, 'vu': hi})
+
+    # fix prefix for lapack routines
+    pfx = 'he' if cplx else 'sy'
+
+    # decide on the driver if not given
+    # first early exit on incompatible choice
+    if driver:
+        if b is None and (driver in ["gv", "gvd", "gvx"]):
+            raise ValueError(f'{driver} requires input b array to be supplied '
+                             'for generalized eigenvalue problems.')
+        if (b is not None) and (driver in ['ev', 'evd', 'evr', 'evx']):
+            raise ValueError(f'"{driver}" does not accept input b array '
+                             'for standard eigenvalue problems.')
+        if subset and (driver in ["ev", "evd", "gv", "gvd"]):
+            raise ValueError(f'"{driver}" cannot compute subsets of eigenvalues')
+
+    # Default driver is evr and gvd
+    else:
+        driver = "evr" if b is None else ("gvx" if subset else "gvd")
+
+    lwork_spec = {
+                  'syevd': ['lwork', 'liwork'],
+                  'syevr': ['lwork', 'liwork'],
+                  'heevd': ['lwork', 'liwork', 'lrwork'],
+                  'heevr': ['lwork', 'lrwork', 'liwork'],
+                  }
+
+    if b is None:  # Standard problem
+        drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
+                                      [a1])
+        clw_args = {'n': n, 'lower': lower}
+        if driver == 'evd':
+            clw_args.update({'compute_v': 0 if _job == "N" else 1})
+
+        lw = _compute_lwork(drvlw, **clw_args)
+        # Multiple lwork vars
+        if isinstance(lw, tuple):
+            lwork_args = dict(zip(lwork_spec[pfx+driver], lw))
+        else:
+            lwork_args = {'lwork': lw}
+
+        drv_args.update({'lower': lower, 'compute_v': 0 if _job == "N" else 1})
+        w, v, *other_args, info = drv(a=a1, **drv_args, **lwork_args)
+
+    else:  # Generalized problem
+        # 'gvd' doesn't have lwork query
+        if driver == "gvd":
+            drv = get_lapack_funcs(pfx + "gvd", [a1, b1])
+            lwork_args = {}
+        else:
+            drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
+                                          [a1, b1])
+            # generalized drivers use uplo instead of lower
+            lw = _compute_lwork(drvlw, n, uplo=uplo)
+            lwork_args = {'lwork': lw}
+
+        drv_args.update({'uplo': uplo, 'jobz': _job})
+
+        w, v, *other_args, info = drv(a=a1, b=b1, **drv_args, **lwork_args)
+
+    # m is always the first extra argument
+    w = w[:other_args[0]] if subset else w
+    v = v[:, :other_args[0]] if (subset and not eigvals_only) else v
+
+    # Check if we had a  successful exit
+    if info == 0:
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+    else:
+        if info < -1:
+            raise LinAlgError(f'Illegal value in argument {-info} of internal '
+                              f'{drv.typecode + pfx + driver}')
+        elif info > n:
+            raise LinAlgError(f'The leading minor of order {info-n} of B is not '
+                              'positive definite. The factorization of B '
+                              'could not be completed and no eigenvalues '
+                              'or eigenvectors were computed.')
+        else:
+            drv_err = {'ev': 'The algorithm failed to converge; {} '
+                             'off-diagonal elements of an intermediate '
+                             'tridiagonal form did not converge to zero.',
+                       'evx': '{} eigenvectors failed to converge.',
+                       'evd': 'The algorithm failed to compute an eigenvalue '
+                              'while working on the submatrix lying in rows '
+                              'and columns {0}/{1} through mod({0},{1}).',
+                       'evr': 'Internal Error.'
+                       }
+            if driver in ['ev', 'gv']:
+                msg = drv_err['ev'].format(info)
+            elif driver in ['evx', 'gvx']:
+                msg = drv_err['evx'].format(info)
+            elif driver in ['evd', 'gvd']:
+                if eigvals_only:
+                    msg = drv_err['ev'].format(info)
+                else:
+                    msg = drv_err['evd'].format(info, n+1)
+            else:
+                msg = drv_err['evr']
+
+            raise LinAlgError(msg)
+
+
+_conv_dict = {0: 0, 1: 1, 2: 2,
+              'all': 0, 'value': 1, 'index': 2,
+              'a': 0, 'v': 1, 'i': 2}
+
+
+def _check_select(select, select_range, max_ev, max_len):
+    """Check that select is valid, convert to Fortran style."""
+    if isinstance(select, str):
+        select = select.lower()
+    try:
+        select = _conv_dict[select]
+    except KeyError as e:
+        raise ValueError('invalid argument for select') from e
+    vl, vu = 0., 1.
+    il = iu = 1
+    if select != 0:  # (non-all)
+        sr = asarray(select_range)
+        if sr.ndim != 1 or sr.size != 2 or sr[1] < sr[0]:
+            raise ValueError('select_range must be a 2-element array-like '
+                             'in nondecreasing order')
+        if select == 1:  # (value)
+            vl, vu = sr
+            if max_ev == 0:
+                max_ev = max_len
+        else:  # 2 (index)
+            if sr.dtype.char.lower() not in 'hilqp':
+                raise ValueError(
+                    f'when using select="i", select_range must '
+                    f'contain integers, got dtype {sr.dtype} ({sr.dtype.char})'
+                )
+            # translate Python (0 ... N-1) into Fortran (1 ... N) with + 1
+            il, iu = sr + 1
+            if min(il, iu) < 1 or max(il, iu) > max_len:
+                raise ValueError('select_range out of bounds')
+            max_ev = iu - il + 1
+    return select, vl, vu, il, iu, max_ev
+
+
+def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
+               select='a', select_range=None, max_ev=0, check_finite=True):
+    """
+    Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
+
+    Find eigenvalues w and optionally right eigenvectors v of a::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    The matrix a is stored in a_band either in lower diagonal or upper
+    diagonal ordered form:
+
+        a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    where u is the number of bands above the diagonal.
+
+    Example of a_band (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    a_band : (u+1, M) array_like
+        The bands of the M by M matrix a.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    eigvals_only : bool, optional
+        Compute only the eigenvalues and no eigenvectors.
+        (Default: calculate also eigenvectors)
+    overwrite_a_band : bool, optional
+        Discard data in a_band (may enhance performance)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    max_ev : int, optional
+        For select=='v', maximum number of eigenvalues expected.
+        For other values of select, has no meaning.
+
+        In doubt, leave this parameter untouched.
+
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+    v : (M, M) float or complex ndarray
+        The normalized eigenvector corresponding to the eigenvalue w[i] is
+        the column v[:,i]. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eig : eigenvalues and right eigenvectors of general arrays.
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eigh_tridiagonal : eigenvalues and right eigenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eig_banded
+    >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
+    >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
+    >>> w, v = eig_banded(Ab, lower=True)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+    >>> w = eig_banded(Ab, lower=True, eigvals_only=True)
+    >>> w
+    array([-4.26200532, -2.22987175,  3.95222349, 12.53965359])
+
+    Request only the eigenvalues between ``[-3, 4]``
+
+    >>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4])
+    >>> w
+    array([-2.22987175,  3.95222349])
+
+    """
+    if eigvals_only or overwrite_a_band:
+        a1 = _asarray_validated(a_band, check_finite=check_finite)
+        overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))
+    else:
+        a1 = array(a_band)
+        if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():
+            raise ValueError("array must not contain infs or NaNs")
+        overwrite_a_band = 1
+
+    if len(a1.shape) != 2:
+        raise ValueError('expected a 2-D array')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=a1.dtype))
+
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    select, vl, vu, il, iu, max_ev = _check_select(
+        select, select_range, max_ev, a1.shape[1])
+
+    del select_range
+    if select == 0:
+        if a1.dtype.char in 'GFD':
+            # FIXME: implement this somewhen, for now go with builtin values
+            # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)
+            #        or by using calc_lwork.f ???
+            # lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower)
+            internal_name = 'hbevd'
+        else:  # a1.dtype.char in 'fd':
+            # FIXME: implement this somewhen, for now go with builtin values
+            #         see above
+            # lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower)
+            internal_name = 'sbevd'
+        bevd, = get_lapack_funcs((internal_name,), (a1,))
+        w, v, info = bevd(a1, compute_v=not eigvals_only,
+                          lower=lower, overwrite_ab=overwrite_a_band)
+    else:  # select in [1, 2]
+        if eigvals_only:
+            max_ev = 1
+        # calculate optimal abstol for dsbevx (see manpage)
+        if a1.dtype.char in 'fF':  # single precision
+            lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))
+        else:
+            lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))
+        abstol = 2 * lamch('s')
+        if a1.dtype.char in 'GFD':
+            internal_name = 'hbevx'
+        else:  # a1.dtype.char in 'gfd'
+            internal_name = 'sbevx'
+        bevx, = get_lapack_funcs((internal_name,), (a1,))
+        w, v, m, ifail, info = bevx(
+            a1, vl, vu, il, iu, compute_v=not eigvals_only, mmax=max_ev,
+            range=select, lower=lower, overwrite_ab=overwrite_a_band,
+            abstol=abstol)
+        # crop off w and v
+        w = w[:m]
+        if not eigvals_only:
+            v = v[:, :m]
+    _check_info(info, internal_name)
+
+    if eigvals_only:
+        return w
+    return w, v
+
+
+def eigvals(a, b=None, overwrite_a=False, check_finite=True,
+            homogeneous_eigvals=False):
+    """
+    Compute eigenvalues from an ordinary or generalized eigenvalue problem.
+
+    Find eigenvalues of a general matrix::
+
+        a   vr[:,i] = w[i]        b   vr[:,i]
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex or real matrix whose eigenvalues and eigenvectors
+        will be computed.
+    b : (M, M) array_like, optional
+        Right-hand side matrix in a generalized eigenvalue problem.
+        If omitted, identity matrix is assumed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities
+        or NaNs.
+    homogeneous_eigvals : bool, optional
+        If True, return the eigenvalues in homogeneous coordinates.
+        In this case ``w`` is a (2, M) array so that::
+
+            w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
+
+        Default is False.
+
+    Returns
+    -------
+    w : (M,) or (2, M) double or complex ndarray
+        The eigenvalues, each repeated according to its multiplicity
+        but not in any specific order. The shape is (M,) unless
+        ``homogeneous_eigvals=True``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge
+
+    See Also
+    --------
+    eig : eigenvalues and right eigenvectors of general arrays.
+    eigvalsh : eigenvalues of symmetric or Hermitian arrays
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
+    >>> linalg.eigvals(a, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [1.+0.j, 1.+0.j, 1.+0.j]])
+
+    """
+    return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
+               check_finite=check_finite,
+               homogeneous_eigvals=homogeneous_eigvals)
+
+
+def eigvalsh(a, b=None, *, lower=True, overwrite_a=False,
+             overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
+             subset_by_value=None, driver=None):
+    """
+    Solves a standard or generalized eigenvalue problem for a complex
+    Hermitian or real symmetric matrix.
+
+    Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive
+    definite such that for every eigenvalue λ (i-th entry of w) and its
+    eigenvector vi (i-th column of v) satisfies::
+
+                      a @ vi = λ * b @ vi
+        vi.conj().T @ a @ vi = λ
+        vi.conj().T @ b @ vi = 1
+
+    In the standard problem, b is assumed to be the identity matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex Hermitian or real symmetric matrix whose eigenvalues will
+        be computed.
+    b : (M, M) array_like, optional
+        A complex Hermitian or real symmetric definite positive matrix in.
+        If omitted, identity matrix is assumed.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of ``a`` and, if applicable, ``b``. (Default: lower)
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default
+        is False.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default
+        is False.
+    type : int, optional
+        For the generalized problems, this keyword specifies the problem type
+        to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
+        inputs)::
+
+            1 =>     a @ v = w @ b @ v
+            2 => a @ b @ v = w @ v
+            3 => b @ a @ v = w @ v
+
+        This keyword is ignored for standard problems.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    subset_by_index : iterable, optional
+        If provided, this two-element iterable defines the start and the end
+        indices of the desired eigenvalues (ascending order and 0-indexed).
+        To return only the second smallest to fifth smallest eigenvalues,
+        ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
+        available with "evr", "evx", and "gvx" drivers. The entries are
+        directly converted to integers via ``int()``.
+    subset_by_value : iterable, optional
+        If provided, this two-element iterable defines the half-open interval
+        ``(a, b]`` that, if any, only the eigenvalues between these values
+        are returned. Only available with "evr", "evx", and "gvx" drivers. Use
+        ``np.inf`` for the unconstrained ends.
+    driver : str, optional
+        Defines which LAPACK driver should be used. Valid options are "ev",
+        "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
+        generalized (where b is not None) problems. See the Notes section of
+        `scipy.linalg.eigh`.
+
+    Returns
+    -------
+    w : (N,) ndarray
+        The N (N<=M) selected eigenvalues, in ascending order, each
+        repeated according to its multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge, an error occurred, or
+        b matrix is not definite positive. Note that if input matrices are
+        not symmetric or Hermitian, no error will be reported but results will
+        be wrong.
+
+    See Also
+    --------
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eigvals : eigenvalues of general arrays
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+
+    Notes
+    -----
+    This function does not check the input array for being Hermitian/symmetric
+    in order to allow for representing arrays with only their upper/lower
+    triangular parts.
+
+    This function serves as a one-liner shorthand for `scipy.linalg.eigh` with
+    the option ``eigvals_only=True`` to get the eigenvalues and not the
+    eigenvectors. Here it is kept as a legacy convenience. It might be
+    beneficial to use the main function to have full control and to be a bit
+    more pythonic.
+
+    Examples
+    --------
+    For more examples see `scipy.linalg.eigh`.
+
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvalsh
+    >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
+    >>> w = eigvalsh(A)
+    >>> w
+    array([-3.74637491, -0.76263923,  6.08502336, 12.42399079])
+
+    """
+    return eigh(a, b=b, lower=lower, eigvals_only=True, overwrite_a=overwrite_a,
+                overwrite_b=overwrite_b, type=type, check_finite=check_finite,
+                subset_by_index=subset_by_index, subset_by_value=subset_by_value,
+                driver=driver)
+
+
+def eigvals_banded(a_band, lower=False, overwrite_a_band=False,
+                   select='a', select_range=None, check_finite=True):
+    """
+    Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
+
+    Find eigenvalues w of a::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    The matrix a is stored in a_band either in lower diagonal or upper
+    diagonal ordered form:
+
+        a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    where u is the number of bands above the diagonal.
+
+    Example of a_band (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    a_band : (u+1, M) array_like
+        The bands of the M by M matrix a.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    overwrite_a_band : bool, optional
+        Discard data in a_band (may enhance performance)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+    eigvals : eigenvalues of general arrays
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvals_banded
+    >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
+    >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
+    >>> w = eigvals_banded(Ab, lower=True)
+    >>> w
+    array([-4.26200532, -2.22987175,  3.95222349, 12.53965359])
+    """
+    return eig_banded(a_band, lower=lower, eigvals_only=1,
+                      overwrite_a_band=overwrite_a_band, select=select,
+                      select_range=select_range, check_finite=check_finite)
+
+
+def eigvalsh_tridiagonal(d, e, select='a', select_range=None,
+                         check_finite=True, tol=0., lapack_driver='auto'):
+    """
+    Solve eigenvalue problem for a real symmetric tridiagonal matrix.
+
+    Find eigenvalues `w` of ``a``::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    For a real symmetric matrix ``a`` with diagonal elements `d` and
+    off-diagonal elements `e`.
+
+    Parameters
+    ----------
+    d : ndarray, shape (ndim,)
+        The diagonal elements of the array.
+    e : ndarray, shape (ndim-1,)
+        The off-diagonal elements of the array.
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    tol : float
+        The absolute tolerance to which each eigenvalue is required
+        (only used when ``lapack_driver='stebz'``).
+        An eigenvalue (or cluster) is considered to have converged if it
+        lies in an interval of this width. If <= 0. (default),
+        the value ``eps*|a|`` is used where eps is the machine precision,
+        and ``|a|`` is the 1-norm of the matrix ``a``.
+    lapack_driver : str
+        LAPACK function to use, can be 'auto', 'stemr', 'stebz',  'sterf',
+        or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
+        and 'stebz' otherwise. 'sterf' and 'stev' can only be used when
+        ``select='a'``.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigh_tridiagonal : eigenvalues and right eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh
+    >>> d = 3*np.ones(4)
+    >>> e = -1*np.ones(3)
+    >>> w = eigvalsh_tridiagonal(d, e)
+    >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
+    >>> w2 = eigvalsh(A)  # Verify with other eigenvalue routines
+    >>> np.allclose(w - w2, np.zeros(4))
+    True
+    """
+    return eigh_tridiagonal(
+        d, e, eigvals_only=True, select=select, select_range=select_range,
+        check_finite=check_finite, tol=tol, lapack_driver=lapack_driver)
+
+
+def eigh_tridiagonal(d, e, eigvals_only=False, select='a', select_range=None,
+                     check_finite=True, tol=0., lapack_driver='auto'):
+    """
+    Solve eigenvalue problem for a real symmetric tridiagonal matrix.
+
+    Find eigenvalues `w` and optionally right eigenvectors `v` of ``a``::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    For a real symmetric matrix ``a`` with diagonal elements `d` and
+    off-diagonal elements `e`.
+
+    Parameters
+    ----------
+    d : ndarray, shape (ndim,)
+        The diagonal elements of the array.
+    e : ndarray, shape (ndim-1,)
+        The off-diagonal elements of the array.
+    eigvals_only : bool, optional
+        Compute only the eigenvalues and no eigenvectors.
+        (Default: calculate also eigenvectors)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    tol : float
+        The absolute tolerance to which each eigenvalue is required
+        (only used when 'stebz' is the `lapack_driver`).
+        An eigenvalue (or cluster) is considered to have converged if it
+        lies in an interval of this width. If <= 0. (default),
+        the value ``eps*|a|`` is used where eps is the machine precision,
+        and ``|a|`` is the 1-norm of the matrix ``a``.
+    lapack_driver : str
+        LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
+        or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
+        and 'stebz' otherwise. When 'stebz' is used to find the eigenvalues and
+        ``eigvals_only=False``, then a second LAPACK call (to ``?STEIN``) is
+        used to find the corresponding eigenvectors. 'sterf' can only be
+        used when ``eigvals_only=True`` and ``select='a'``. 'stev' can only
+        be used when ``select='a'``.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+    v : (M, M) ndarray
+        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
+        the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+
+    Notes
+    -----
+    This function makes use of LAPACK ``S/DSTEMR`` routines.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigh_tridiagonal
+    >>> d = 3*np.ones(4)
+    >>> e = -1*np.ones(3)
+    >>> w, v = eigh_tridiagonal(d, e)
+    >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+    """
+    d = _asarray_validated(d, check_finite=check_finite)
+    e = _asarray_validated(e, check_finite=check_finite)
+    for check in (d, e):
+        if check.ndim != 1:
+            raise ValueError('expected a 1-D array')
+        if check.dtype.char in 'GFD':  # complex
+            raise TypeError('Only real arrays currently supported')
+    if d.size != e.size + 1:
+        raise ValueError(f'd ({d.size}) must have one more element than e ({e.size})')
+    select, vl, vu, il, iu, _ = _check_select(
+        select, select_range, 0, d.size)
+    if not isinstance(lapack_driver, str):
+        raise TypeError('lapack_driver must be str')
+    drivers = ('auto', 'stemr', 'sterf', 'stebz', 'stev')
+    if lapack_driver not in drivers:
+        raise ValueError(f'lapack_driver must be one of {drivers}, '
+                         f'got {lapack_driver}')
+    if lapack_driver == 'auto':
+        lapack_driver = 'stemr' if select == 0 else 'stebz'
+
+    # Quick exit for 1x1 case
+    if len(d) == 1:
+        if select == 1 and (not (vl < d[0] <= vu)):  # request by value
+            w = array([])
+            v = empty([1, 0], dtype=d.dtype)
+        else:  # all and request by index
+            w = array([d[0]], dtype=d.dtype)
+            v = array([[1.]], dtype=d.dtype)
+
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    func, = get_lapack_funcs((lapack_driver,), (d, e))
+    compute_v = not eigvals_only
+    if lapack_driver == 'sterf':
+        if select != 0:
+            raise ValueError('sterf can only be used when select == "a"')
+        if not eigvals_only:
+            raise ValueError('sterf can only be used when eigvals_only is '
+                             'True')
+        w, info = func(d, e)
+        m = len(w)
+    elif lapack_driver == 'stev':
+        if select != 0:
+            raise ValueError('stev can only be used when select == "a"')
+        w, v, info = func(d, e, compute_v=compute_v)
+        m = len(w)
+    elif lapack_driver == 'stebz':
+        tol = float(tol)
+        internal_name = 'stebz'
+        stebz, = get_lapack_funcs((internal_name,), (d, e))
+        # If getting eigenvectors, needs to be block-ordered (B) instead of
+        # matrix-ordered (E), and we will reorder later
+        order = 'E' if eigvals_only else 'B'
+        m, w, iblock, isplit, info = stebz(d, e, select, vl, vu, il, iu, tol,
+                                           order)
+    else:   # 'stemr'
+        # ?STEMR annoyingly requires size N instead of N-1
+        e_ = empty(e.size+1, e.dtype)
+        e_[:-1] = e
+        stemr_lwork, = get_lapack_funcs(('stemr_lwork',), (d, e))
+        lwork, liwork, info = stemr_lwork(d, e_, select, vl, vu, il, iu,
+                                          compute_v=compute_v)
+        _check_info(info, 'stemr_lwork')
+        m, w, v, info = func(d, e_, select, vl, vu, il, iu,
+                             compute_v=compute_v, lwork=lwork, liwork=liwork)
+    _check_info(info, lapack_driver + ' (eigh_tridiagonal)')
+    w = w[:m]
+    if eigvals_only:
+        return w
+    else:
+        # Do we still need to compute the eigenvalues?
+        if lapack_driver == 'stebz':
+            func, = get_lapack_funcs(('stein',), (d, e))
+            v, info = func(d, e, w, iblock, isplit)
+            _check_info(info, 'stein (eigh_tridiagonal)',
+                        positive='%d eigenvectors failed to converge')
+            # Convert block-order to matrix-order
+            order = argsort(w)
+            w, v = w[order], v[:, order]
+        else:
+            v = v[:, :m]
+        return w, v
+
+
+def _check_info(info, driver, positive='did not converge (LAPACK info=%d)'):
+    """Check info return value."""
+    if info < 0:
+        raise ValueError('illegal value in argument %d of internal %s'
+                         % (-info, driver))
+    if info > 0 and positive:
+        raise LinAlgError(("%s " + positive) % (driver, info,))
+
+
+def hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True):
+    """
+    Compute Hessenberg form of a matrix.
+
+    The Hessenberg decomposition is::
+
+        A = Q H Q^H
+
+    where `Q` is unitary/orthogonal and `H` has only zero elements below
+    the first sub-diagonal.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to bring into Hessenberg form.
+    calc_q : bool, optional
+        Whether to compute the transformation matrix.  Default is False.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    H : (M, M) ndarray
+        Hessenberg form of `a`.
+    Q : (M, M) ndarray
+        Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.
+        Only returned if ``calc_q=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import hessenberg
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> H, Q = hessenberg(A, calc_q=True)
+    >>> H
+    array([[  2.        , -11.65843866,   1.42005301,   0.25349066],
+           [ -9.94987437,  14.53535354,  -5.31022304,   2.43081618],
+           [  0.        ,  -1.83299243,   0.38969961,  -0.51527034],
+           [  0.        ,   0.        ,  -3.83189513,   1.07494686]])
+    >>> np.allclose(Q @ H @ Q.conj().T - A, np.zeros((4, 4)))
+    True
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
+        raise ValueError('expected square matrix')
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if a1.size == 0:
+        h3 = hessenberg(np.eye(3, dtype=a1.dtype))
+        h = np.empty(a1.shape, dtype=h3.dtype)
+        if not calc_q:
+            return h
+        else:
+            h3, q3 = hessenberg(np.eye(3, dtype=a1.dtype), calc_q=True)
+            q = np.empty(a1.shape, dtype=q3.dtype)
+            h = np.empty(a1.shape, dtype=h3.dtype)
+            return h, q
+
+    # if 2x2 or smaller: already in Hessenberg
+    if a1.shape[0] <= 2:
+        if calc_q:
+            return a1, eye(a1.shape[0])
+        return a1
+
+    gehrd, gebal, gehrd_lwork = get_lapack_funcs(('gehrd', 'gebal',
+                                                  'gehrd_lwork'), (a1,))
+    ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a)
+    _check_info(info, 'gebal (hessenberg)', positive=False)
+    n = len(a1)
+
+    lwork = _compute_lwork(gehrd_lwork, ba.shape[0], lo=lo, hi=hi)
+
+    hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
+    _check_info(info, 'gehrd (hessenberg)', positive=False)
+    h = np.triu(hq, -1)
+    if not calc_q:
+        return h
+
+    # use orghr/unghr to compute q
+    orghr, orghr_lwork = get_lapack_funcs(('orghr', 'orghr_lwork'), (a1,))
+    lwork = _compute_lwork(orghr_lwork, n, lo=lo, hi=hi)
+
+    q, info = orghr(a=hq, tau=tau, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
+    _check_info(info, 'orghr (hessenberg)', positive=False)
+    return h, q
+
+
+def cdf2rdf(w, v):
+    """
+    Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real
+    eigenvalues in a block diagonal form ``wr`` and the associated real
+    eigenvectors ``vr``, such that::
+
+        vr @ wr = X @ vr
+
+    continues to hold, where ``X`` is the original array for which ``w`` and
+    ``v`` are the eigenvalues and eigenvectors.
+
+    .. versionadded:: 1.1.0
+
+    Parameters
+    ----------
+    w : (..., M) array_like
+        Complex or real eigenvalues, an array or stack of arrays
+
+        Conjugate pairs must not be interleaved, else the wrong result
+        will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result,
+        but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not.
+
+    v : (..., M, M) array_like
+        Complex or real eigenvectors, a square array or stack of square arrays.
+
+    Returns
+    -------
+    wr : (..., M, M) ndarray
+        Real diagonal block form of eigenvalues
+    vr : (..., M, M) ndarray
+        Real eigenvectors associated with ``wr``
+
+    See Also
+    --------
+    eig : Eigenvalues and right eigenvectors for non-symmetric arrays
+    rsf2csf : Convert real Schur form to complex Schur form
+
+    Notes
+    -----
+    ``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``.
+    For example, obtained by ``w, v = scipy.linalg.eig(X)`` or
+    ``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent
+    stacked arrays.
+
+    .. versionadded:: 1.1.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+    >>> X
+    array([[ 1,  2,  3],
+           [ 0,  4,  5],
+           [ 0, -5,  4]])
+
+    >>> from scipy import linalg
+    >>> w, v = linalg.eig(X)
+    >>> w
+    array([ 1.+0.j,  4.+5.j,  4.-5.j])
+    >>> v
+    array([[ 1.00000+0.j     , -0.01906-0.40016j, -0.01906+0.40016j],
+           [ 0.00000+0.j     ,  0.00000-0.64788j,  0.00000+0.64788j],
+           [ 0.00000+0.j     ,  0.64788+0.j     ,  0.64788-0.j     ]])
+
+    >>> wr, vr = linalg.cdf2rdf(w, v)
+    >>> wr
+    array([[ 1.,  0.,  0.],
+           [ 0.,  4.,  5.],
+           [ 0., -5.,  4.]])
+    >>> vr
+    array([[ 1.     ,  0.40016, -0.01906],
+           [ 0.     ,  0.64788,  0.     ],
+           [ 0.     ,  0.     ,  0.64788]])
+
+    >>> vr @ wr
+    array([[ 1.     ,  1.69593,  1.9246 ],
+           [ 0.     ,  2.59153,  3.23942],
+           [ 0.     , -3.23942,  2.59153]])
+    >>> X @ vr
+    array([[ 1.     ,  1.69593,  1.9246 ],
+           [ 0.     ,  2.59153,  3.23942],
+           [ 0.     , -3.23942,  2.59153]])
+    """
+    w, v = _asarray_validated(w), _asarray_validated(v)
+
+    # check dimensions
+    if w.ndim < 1:
+        raise ValueError('expected w to be at least 1D')
+    if v.ndim < 2:
+        raise ValueError('expected v to be at least 2D')
+    if v.ndim != w.ndim + 1:
+        raise ValueError('expected eigenvectors array to have exactly one '
+                         'dimension more than eigenvalues array')
+
+    # check shapes
+    n = w.shape[-1]
+    M = w.shape[:-1]
+    if v.shape[-2] != v.shape[-1]:
+        raise ValueError('expected v to be a square matrix or stacked square '
+                         'matrices: v.shape[-2] = v.shape[-1]')
+    if v.shape[-1] != n:
+        raise ValueError('expected the same number of eigenvalues as '
+                         'eigenvectors')
+
+    # get indices for each first pair of complex eigenvalues
+    complex_mask = iscomplex(w)
+    n_complex = complex_mask.sum(axis=-1)
+
+    # check if all complex eigenvalues have conjugate pairs
+    if not (n_complex % 2 == 0).all():
+        raise ValueError('expected complex-conjugate pairs of eigenvalues')
+
+    # find complex indices
+    idx = nonzero(complex_mask)
+    idx_stack = idx[:-1]
+    idx_elem = idx[-1]
+
+    # filter them to conjugate indices, assuming pairs are not interleaved
+    j = idx_elem[0::2]
+    k = idx_elem[1::2]
+    stack_ind = ()
+    for i in idx_stack:
+        # should never happen, assuming nonzero orders by the last axis
+        assert (i[0::2] == i[1::2]).all(), \
+                "Conjugate pair spanned different arrays!"
+        stack_ind += (i[0::2],)
+
+    # all eigenvalues to diagonal form
+    wr = zeros(M + (n, n), dtype=w.real.dtype)
+    di = range(n)
+    wr[..., di, di] = w.real
+
+    # complex eigenvalues to real block diagonal form
+    wr[stack_ind + (j, k)] = w[stack_ind + (j,)].imag
+    wr[stack_ind + (k, j)] = w[stack_ind + (k,)].imag
+
+    # compute real eigenvectors associated with real block diagonal eigenvalues
+    u = zeros(M + (n, n), dtype=np.cdouble)
+    u[..., di, di] = 1.0
+    u[stack_ind + (j, j)] = 0.5j
+    u[stack_ind + (j, k)] = 0.5
+    u[stack_ind + (k, j)] = -0.5j
+    u[stack_ind + (k, k)] = 0.5
+
+    # multiply matrices v and u (equivalent to v @ u)
+    vr = einsum('...ij,...jk->...ik', v, u).real
+
+    return wr, vr
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..c35b6a4920dea6bb638fe54a1fa719ebc74fb773
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
@@ -0,0 +1,398 @@
+"""Cholesky decomposition functions."""
+
+import numpy as np
+from numpy import asarray_chkfinite, asarray, atleast_2d, empty_like
+
+# Local imports
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs
+
+__all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+           'cho_solve_banded']
+
+
+def _cholesky(a, lower=False, overwrite_a=False, clean=True,
+              check_finite=True):
+    """Common code for cholesky() and cho_factor()."""
+
+    a1 = asarray_chkfinite(a) if check_finite else asarray(a)
+    a1 = atleast_2d(a1)
+
+    # Dimension check
+    if a1.ndim != 2:
+        raise ValueError(f'Input array needs to be 2D but received a {a1.ndim}d-array.')
+    # Squareness check
+    if a1.shape[0] != a1.shape[1]:
+        raise ValueError('Input array is expected to be square but has '
+                         f'the shape: {a1.shape}.')
+
+    # Quick return for square empty array
+    if a1.size == 0:
+        dt = cholesky(np.eye(1, dtype=a1.dtype)).dtype
+        return empty_like(a1, dtype=dt), lower
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    potrf, = get_lapack_funcs(('potrf',), (a1,))
+    c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
+    if info > 0:
+        raise LinAlgError("%d-th leading minor of the array is not positive "
+                          "definite" % info)
+    if info < 0:
+        raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument'
+                         'on entry to "POTRF".')
+    return c, lower
+
+
+def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
+    """
+    Compute the Cholesky decomposition of a matrix.
+
+    Returns the Cholesky decomposition, :math:`A = L L^*` or
+    :math:`A = U^* U` of a Hermitian positive-definite matrix A.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to be decomposed
+    lower : bool, optional
+        Whether to compute the upper- or lower-triangular Cholesky
+        factorization. During decomposition, only the selected half of the
+        matrix is referenced. Default is upper-triangular.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance).
+    check_finite : bool, optional
+        Whether to check that the entire input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (M, M) ndarray
+        Upper- or lower-triangular Cholesky factor of `a`.
+
+    Raises
+    ------
+    LinAlgError : if decomposition fails.
+
+    Notes
+    -----
+    During the finiteness check (if selected), the entire matrix `a` is
+    checked. During decomposition, `a` is assumed to be symmetric or Hermitian
+    (as applicable), and only the half selected by option `lower` is referenced.
+    Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
+    succeed if the symmetric/Hermitian matrix represented by the selected half
+    is positive definite, yet it may fail if an element in the other half is
+    non-finite.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky
+    >>> a = np.array([[1,-2j],[2j,5]])
+    >>> L = cholesky(a, lower=True)
+    >>> L
+    array([[ 1.+0.j,  0.+0.j],
+           [ 0.+2.j,  1.+0.j]])
+    >>> L @ L.T.conj()
+    array([[ 1.+0.j,  0.-2.j],
+           [ 0.+2.j,  5.+0.j]])
+
+    """
+    c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True,
+                         check_finite=check_finite)
+    return c
+
+
+def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
+    """
+    Compute the Cholesky decomposition of a matrix, to use in cho_solve
+
+    Returns a matrix containing the Cholesky decomposition,
+    ``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`.
+    The return value can be directly used as the first parameter to cho_solve.
+
+    .. warning::
+        The returned matrix also contains random data in the entries not
+        used by the Cholesky decomposition. If you need to zero these
+        entries, use the function `cholesky` instead.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to be decomposed
+    lower : bool, optional
+        Whether to compute the upper or lower triangular Cholesky factorization.
+        During decomposition, only the selected half of the matrix is referenced.
+        (Default: upper-triangular)
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the entire input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (M, M) ndarray
+        Matrix whose upper or lower triangle contains the Cholesky factor
+        of `a`. Other parts of the matrix contain random data.
+    lower : bool
+        Flag indicating whether the factor is in the lower or upper triangle
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails.
+
+    See Also
+    --------
+    cho_solve : Solve a linear set equations using the Cholesky factorization
+                of a matrix.
+
+    Notes
+    -----
+    During the finiteness check (if selected), the entire matrix `a` is
+    checked. During decomposition, `a` is assumed to be symmetric or Hermitian
+    (as applicable), and only the half selected by option `lower` is referenced.
+    Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
+    succeed if the symmetric/Hermitian matrix represented by the selected half
+    is positive definite, yet it may fail if an element in the other half is
+    non-finite.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cho_factor
+    >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
+    >>> c, low = cho_factor(A)
+    >>> c
+    array([[3.        , 1.        , 0.33333333, 1.66666667],
+           [3.        , 2.44948974, 1.90515869, -0.27216553],
+           [1.        , 5.        , 2.29330749, 0.8559528 ],
+           [5.        , 1.        , 2.        , 1.55418563]])
+    >>> np.allclose(np.triu(c).T @ np. triu(c) - A, np.zeros((4, 4)))
+    True
+
+    """
+    c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
+                         check_finite=check_finite)
+    return c, lower
+
+
+def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
+    """Solve the linear equations A x = b, given the Cholesky factorization of A.
+
+    Parameters
+    ----------
+    (c, lower) : tuple, (array, bool)
+        Cholesky factorization of a, as given by cho_factor
+    b : array
+        Right-hand side
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        The solution to the system A x = b
+
+    See Also
+    --------
+    cho_factor : Cholesky factorization of a matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cho_factor, cho_solve
+    >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
+    >>> c, low = cho_factor(A)
+    >>> x = cho_solve((c, low), [1, 1, 1, 1])
+    >>> np.allclose(A @ x - [1, 1, 1, 1], np.zeros(4))
+    True
+
+    """
+    (c, lower) = c_and_lower
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+        c = asarray_chkfinite(c)
+    else:
+        b1 = asarray(b)
+        c = asarray(c)
+
+    if c.ndim != 2 or c.shape[0] != c.shape[1]:
+        raise ValueError("The factored matrix c is not square.")
+    if c.shape[1] != b1.shape[0]:
+        raise ValueError(f"incompatible dimensions ({c.shape} and {b1.shape})")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = cho_solve((np.eye(2, dtype=b1.dtype), True),
+                        np.ones(2, dtype=c.dtype)).dtype
+        return empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    potrs, = get_lapack_funcs(('potrs',), (c, b1))
+    x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)
+    if info != 0:
+        raise ValueError('illegal value in %dth argument of internal potrs'
+                         % -info)
+    return x
+
+
+def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True):
+    """
+    Cholesky decompose a banded Hermitian positive-definite matrix
+
+    The matrix a is stored in ab either in lower-diagonal or upper-
+    diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        ab[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    Example of ab (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Parameters
+    ----------
+    ab : (u + 1, M) array_like
+        Banded matrix
+    overwrite_ab : bool, optional
+        Discard data in ab (may enhance performance)
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (u + 1, M) ndarray
+        Cholesky factorization of a, in the same banded format as ab
+
+    See Also
+    --------
+    cho_solve_banded :
+        Solve a linear set equations, given the Cholesky factorization
+        of a banded Hermitian.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky_banded
+    >>> from numpy import allclose, zeros, diag
+    >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
+    >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
+    >>> A = A + A.conj().T + np.diag(Ab[2, :])
+    >>> c = cholesky_banded(Ab)
+    >>> C = np.diag(c[0, 2:], k=2) + np.diag(c[1, 1:], k=1) + np.diag(c[2, :])
+    >>> np.allclose(C.conj().T @ C - A, np.zeros((5, 5)))
+    True
+
+    """
+    if check_finite:
+        ab = asarray_chkfinite(ab)
+    else:
+        ab = asarray(ab)
+
+    # accommodate square empty matrices
+    if ab.size == 0:
+        dt = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=ab.dtype)).dtype
+        return empty_like(ab, dtype=dt)
+
+    pbtrf, = get_lapack_funcs(('pbtrf',), (ab,))
+    c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab)
+    if info > 0:
+        raise LinAlgError("%d-th leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %d-th argument of internal pbtrf'
+                         % -info)
+    return c
+
+
+def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True):
+    """
+    Solve the linear equations ``A x = b``, given the Cholesky factorization of
+    the banded Hermitian ``A``.
+
+    Parameters
+    ----------
+    (cb, lower) : tuple, (ndarray, bool)
+        `cb` is the Cholesky factorization of A, as given by cholesky_banded.
+        `lower` must be the same value that was given to cholesky_banded.
+    b : array_like
+        Right-hand side
+    overwrite_b : bool, optional
+        If True, the function will overwrite the values in `b`.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        The solution to the system A x = b
+
+    See Also
+    --------
+    cholesky_banded : Cholesky factorization of a banded matrix
+
+    Notes
+    -----
+
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky_banded, cho_solve_banded
+    >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
+    >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
+    >>> A = A + A.conj().T + np.diag(Ab[2, :])
+    >>> c = cholesky_banded(Ab)
+    >>> x = cho_solve_banded((c, False), np.ones(5))
+    >>> np.allclose(A @ x - np.ones(5), np.zeros(5))
+    True
+
+    """
+    (cb, lower) = cb_and_lower
+    if check_finite:
+        cb = asarray_chkfinite(cb)
+        b = asarray_chkfinite(b)
+    else:
+        cb = asarray(cb)
+        b = asarray(b)
+
+    # Validate shapes.
+    if cb.shape[-1] != b.shape[0]:
+        raise ValueError("shapes of cb and b are not compatible.")
+
+    # accommodate empty arrays
+    if b.size == 0:
+        m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=cb.dtype))
+        dt = cho_solve_banded((m, True), np.ones(2, dtype=b.dtype)).dtype
+        return empty_like(b, dtype=dt)
+
+    pbtrs, = get_lapack_funcs(('pbtrs',), (cb, b))
+    x, info = pbtrs(cb, b, lower=lower, overwrite_b=overwrite_b)
+    if info > 0:
+        raise LinAlgError("%dth leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal pbtrs'
+                         % -info)
+    return x
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10c04fe5ebc196e1b84724b25f0fc20a5e46857
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py
@@ -0,0 +1,221 @@
+from collections.abc import Iterable
+import numpy as np
+
+from scipy._lib._util import _asarray_validated
+from scipy.linalg import block_diag, LinAlgError
+from .lapack import _compute_lwork, get_lapack_funcs
+
+__all__ = ['cossin']
+
+
+def cossin(X, p=None, q=None, separate=False,
+           swap_sign=False, compute_u=True, compute_vh=True):
+    """
+    Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix.
+
+    X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following
+    where upper left block has the shape of ``(p, q)``::
+
+                                   ┌                   ┐
+                                   │ 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 │
+                                   └                   ┘
+
+    ``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, and ``C`` and ``S`` are ``(r, r)`` nonnegative diagonal
+    matrices satisfying ``C^2 + S^2 = I`` where ``r = min(p, m-p, q, m-q)``.
+
+    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.
+
+    X can be supplied either by itself and block specifications p, q or its
+    subblocks in an iterable from which the shapes would be derived. See the
+    examples below.
+
+    Parameters
+    ----------
+    X : array_like, iterable
+        complex unitary or real orthogonal matrix to be decomposed, or iterable
+        of subblocks ``X11``, ``X12``, ``X21``, ``X22``, when ``p``, ``q`` are
+        omitted.
+    p : int, optional
+        Number of rows of the upper left block ``X11``, used only when X is
+        given as an array.
+    q : int, optional
+        Number of columns of the upper left block ``X11``, used only when X is
+        given as an array.
+    separate : bool, optional
+        if ``True``, the low level components are returned instead of the
+        matrix factors, i.e. ``(u1,u2)``, ``theta``, ``(v1h,v2h)`` instead of
+        ``u``, ``cs``, ``vh``.
+    swap_sign : bool, optional
+        if ``True``, the ``-S``, ``-I`` block will be the bottom left,
+        otherwise (by default) they will be in the upper right block.
+    compute_u : bool, optional
+        if ``False``, ``u`` won't be computed and an empty array is returned.
+    compute_vh : bool, optional
+        if ``False``, ``vh`` won't be computed and an empty array is returned.
+
+    Returns
+    -------
+    u : ndarray
+        When ``compute_u=True``, contains the block diagonal orthogonal/unitary
+        matrix consisting of the blocks ``U1`` (``p`` x ``p``) and ``U2``
+        (``m-p`` x ``m-p``) orthogonal/unitary matrices. If ``separate=True``,
+        this contains the tuple of ``(U1, U2)``.
+    cs : ndarray
+        The cosine-sine factor with the structure described above.
+         If ``separate=True``, this contains the ``theta`` array containing the
+         angles in radians.
+    vh : ndarray
+        When ``compute_vh=True`, contains the block diagonal orthogonal/unitary
+        matrix consisting of the blocks ``V1H`` (``q`` x ``q``) and ``V2H``
+        (``m-q`` x ``m-q``) orthogonal/unitary matrices. If ``separate=True``,
+        this contains the tuple of ``(V1H, V2H)``.
+
+    References
+    ----------
+    .. [1] Brian D. Sutton. Computing the complete CS decomposition. Numer.
+           Algorithms, 50(1):33-65, 2009.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cossin
+    >>> from scipy.stats import unitary_group
+    >>> x = unitary_group.rvs(4)
+    >>> u, cs, vdh = cossin(x, p=2, q=2)
+    >>> np.allclose(x, u @ cs @ vdh)
+    True
+
+    Same can be entered via subblocks without the need of ``p`` and ``q``. Also
+    let's skip the computation of ``u``
+
+    >>> ue, cs, vdh = cossin((x[:2, :2], x[:2, 2:], x[2:, :2], x[2:, 2:]),
+    ...                      compute_u=False)
+    >>> print(ue)
+    []
+    >>> np.allclose(x, u @ cs @ vdh)
+    True
+
+    """
+
+    if p or q:
+        p = 1 if p is None else int(p)
+        q = 1 if q is None else int(q)
+        X = _asarray_validated(X, check_finite=True)
+        if not np.equal(*X.shape):
+            raise ValueError("Cosine Sine decomposition only supports square"
+                             f" matrices, got {X.shape}")
+        m = X.shape[0]
+        if p >= m or p <= 0:
+            raise ValueError(f"invalid p={p}, 0= m or q <= 0:
+            raise ValueError(f"invalid q={q}, 0 0:
+        raise LinAlgError(f"{method_name} did not converge: {info}")
+
+    if separate:
+        return (u1, u2), theta, (v1h, v2h)
+
+    U = block_diag(u1, u2)
+    VDH = block_diag(v1h, v2h)
+
+    # Construct the middle factor CS
+    c = np.diag(np.cos(theta))
+    s = np.diag(np.sin(theta))
+    r = min(p, q, 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
+    Id = np.eye(np.max([n11, n12, n21, n22, r]), dtype=theta.dtype)
+    CS = np.zeros((m, m), dtype=theta.dtype)
+
+    CS[:n11, :n11] = Id[:n11, :n11]
+
+    xs = n11 + r
+    xe = n11 + r + n12
+    ys = n11 + n21 + n22 + 2 * r
+    ye = n11 + n21 + n22 + 2 * r + n12
+    CS[xs: xe, ys:ye] = Id[:n12, :n12] if swap_sign else -Id[:n12, :n12]
+
+    xs = p + n22 + r
+    xe = p + n22 + r + + n21
+    ys = n11 + r
+    ye = n11 + r + n21
+    CS[xs:xe, ys:ye] = -Id[:n21, :n21] if swap_sign else Id[:n21, :n21]
+
+    CS[p:p + n22, q:q + n22] = Id[:n22, :n22]
+    CS[n11:n11 + r, n11:n11 + r] = c
+    CS[p + n22:p + n22 + r, n11 + r + n21 + n22:2 * r + n11 + n21 + n22] = c
+
+    xs = n11
+    xe = n11 + r
+    ys = n11 + n21 + n22 + r
+    ye = n11 + n21 + n22 + 2 * r
+    CS[xs:xe, ys:ye] = s if swap_sign else -s
+
+    CS[p + n22:p + n22 + r, n11:n11 + r] = -s if swap_sign else s
+
+    return U, CS, VDH
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..336df1d5fb416f635c91afe3cc2cfb3c340239fc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py
@@ -0,0 +1,353 @@
+from warnings import warn
+
+import numpy as np
+from numpy import (atleast_2d, arange, zeros_like, imag, diag,
+                   iscomplexobj, tril, triu, argsort, empty_like)
+from scipy._lib._util import ComplexWarning
+from ._decomp import _asarray_validated
+from .lapack import get_lapack_funcs, _compute_lwork
+
+__all__ = ['ldl']
+
+
+def ldl(A, lower=True, hermitian=True, overwrite_a=False, check_finite=True):
+    """ Computes the LDLt or Bunch-Kaufman factorization of a symmetric/
+    hermitian matrix.
+
+    This function returns a block diagonal matrix D consisting blocks of size
+    at most 2x2 and also a possibly permuted unit lower triangular matrix
+    ``L`` such that the factorization ``A = L D L^H`` or ``A = L D L^T``
+    holds. If `lower` is False then (again possibly permuted) upper
+    triangular matrices are returned as outer factors.
+
+    The permutation array can be used to triangularize the outer factors
+    simply by a row shuffle, i.e., ``lu[perm, :]`` is an upper/lower
+    triangular matrix. This is also equivalent to multiplication with a
+    permutation matrix ``P.dot(lu)``, where ``P`` is a column-permuted
+    identity matrix ``I[:, perm]``.
+
+    Depending on the value of the boolean `lower`, only upper or lower
+    triangular part of the input array is referenced. Hence, a triangular
+    matrix on entry would give the same result as if the full matrix is
+    supplied.
+
+    Parameters
+    ----------
+    A : array_like
+        Square input array
+    lower : bool, optional
+        This switches between the lower and upper triangular outer factors of
+        the factorization. Lower triangular (``lower=True``) is the default.
+    hermitian : bool, optional
+        For complex-valued arrays, this defines whether ``A = A.conj().T`` or
+        ``A = A.T`` is assumed. For real-valued arrays, this switch has no
+        effect.
+    overwrite_a : bool, optional
+        Allow overwriting data in `A` (may enhance performance). The default
+        is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    lu : ndarray
+        The (possibly) permuted upper/lower triangular outer factor of the
+        factorization.
+    d : ndarray
+        The block diagonal multiplier of the factorization.
+    perm : ndarray
+        The row-permutation index array that brings lu into triangular form.
+
+    Raises
+    ------
+    ValueError
+        If input array is not square.
+    ComplexWarning
+        If a complex-valued array with nonzero imaginary parts on the
+        diagonal is given and hermitian is set to True.
+
+    See Also
+    --------
+    cholesky, lu
+
+    Notes
+    -----
+    This function uses ``?SYTRF`` routines for symmetric matrices and
+    ``?HETRF`` routines for Hermitian matrices from LAPACK. See [1]_ for
+    the algorithm details.
+
+    Depending on the `lower` keyword value, only lower or upper triangular
+    part of the input array is referenced. Moreover, this keyword also defines
+    the structure of the outer factors of the factorization.
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] J.R. Bunch, L. Kaufman, Some stable methods for calculating
+       inertia and solving symmetric linear systems, Math. Comput. Vol.31,
+       1977. :doi:`10.2307/2005787`
+
+    Examples
+    --------
+    Given an upper triangular array ``a`` that represents the full symmetric
+    array with its entries, obtain ``l``, 'd' and the permutation vector `perm`:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import ldl
+    >>> a = np.array([[2, -1, 3], [0, 2, 0], [0, 0, 1]])
+    >>> lu, d, perm = ldl(a, lower=0) # Use the upper part
+    >>> lu
+    array([[ 0. ,  0. ,  1. ],
+           [ 0. ,  1. , -0.5],
+           [ 1. ,  1. ,  1.5]])
+    >>> d
+    array([[-5. ,  0. ,  0. ],
+           [ 0. ,  1.5,  0. ],
+           [ 0. ,  0. ,  2. ]])
+    >>> perm
+    array([2, 1, 0])
+    >>> lu[perm, :]
+    array([[ 1. ,  1. ,  1.5],
+           [ 0. ,  1. , -0.5],
+           [ 0. ,  0. ,  1. ]])
+    >>> lu.dot(d).dot(lu.T)
+    array([[ 2., -1.,  3.],
+           [-1.,  2.,  0.],
+           [ 3.,  0.,  1.]])
+
+    """
+    a = atleast_2d(_asarray_validated(A, check_finite=check_finite))
+    if a.shape[0] != a.shape[1]:
+        raise ValueError('The input array "a" should be square.')
+    # Return empty arrays for empty square input
+    if a.size == 0:
+        return empty_like(a), empty_like(a), np.array([], dtype=int)
+
+    n = a.shape[0]
+    r_or_c = complex if iscomplexobj(a) else float
+
+    # Get the LAPACK routine
+    if r_or_c is complex and hermitian:
+        s, sl = 'hetrf', 'hetrf_lwork'
+        if np.any(imag(diag(a))):
+            warn('scipy.linalg.ldl():\nThe imaginary parts of the diagonal'
+                 'are ignored. Use "hermitian=False" for factorization of'
+                 'complex symmetric arrays.', ComplexWarning, stacklevel=2)
+    else:
+        s, sl = 'sytrf', 'sytrf_lwork'
+
+    solver, solver_lwork = get_lapack_funcs((s, sl), (a,))
+    lwork = _compute_lwork(solver_lwork, n, lower=lower)
+    ldu, piv, info = solver(a, lwork=lwork, lower=lower,
+                            overwrite_a=overwrite_a)
+    if info < 0:
+        raise ValueError(f'{s.upper()} exited with the internal error "illegal value '
+                         f'in argument number {-info}". See LAPACK documentation '
+                         'for the error codes.')
+
+    swap_arr, pivot_arr = _ldl_sanitize_ipiv(piv, lower=lower)
+    d, lu = _ldl_get_d_and_l(ldu, pivot_arr, lower=lower, hermitian=hermitian)
+    lu, perm = _ldl_construct_tri_factor(lu, swap_arr, pivot_arr, lower=lower)
+
+    return lu, d, perm
+
+
+def _ldl_sanitize_ipiv(a, lower=True):
+    """
+    This helper function takes the rather strangely encoded permutation array
+    returned by the LAPACK routines ?(HE/SY)TRF and converts it into
+    regularized permutation and diagonal pivot size format.
+
+    Since FORTRAN uses 1-indexing and LAPACK uses different start points for
+    upper and lower formats there are certain offsets in the indices used
+    below.
+
+    Let's assume a result where the matrix is 6x6 and there are two 2x2
+    and two 1x1 blocks reported by the routine. To ease the coding efforts,
+    we still populate a 6-sized array and fill zeros as the following ::
+
+        pivots = [2, 0, 2, 0, 1, 1]
+
+    This denotes a diagonal matrix of the form ::
+
+        [x x        ]
+        [x x        ]
+        [    x x    ]
+        [    x x    ]
+        [        x  ]
+        [          x]
+
+    In other words, we write 2 when the 2x2 block is first encountered and
+    automatically write 0 to the next entry and skip the next spin of the
+    loop. Thus, a separate counter or array appends to keep track of block
+    sizes are avoided. If needed, zeros can be filtered out later without
+    losing the block structure.
+
+    Parameters
+    ----------
+    a : ndarray
+        The permutation array ipiv returned by LAPACK
+    lower : bool, optional
+        The switch to select whether upper or lower triangle is chosen in
+        the LAPACK call.
+
+    Returns
+    -------
+    swap_ : ndarray
+        The array that defines the row/column swap operations. For example,
+        if row two is swapped with row four, the result is [0, 3, 2, 3].
+    pivots : ndarray
+        The array that defines the block diagonal structure as given above.
+
+    """
+    n = a.size
+    swap_ = arange(n)
+    pivots = zeros_like(swap_, dtype=int)
+    skip_2x2 = False
+
+    # Some upper/lower dependent offset values
+    # range (s)tart, r(e)nd, r(i)ncrement
+    x, y, rs, re, ri = (1, 0, 0, n, 1) if lower else (-1, -1, n-1, -1, -1)
+
+    for ind in range(rs, re, ri):
+        # If previous spin belonged already to a 2x2 block
+        if skip_2x2:
+            skip_2x2 = False
+            continue
+
+        cur_val = a[ind]
+        # do we have a 1x1 block or not?
+        if cur_val > 0:
+            if cur_val != ind+1:
+                # Index value != array value --> permutation required
+                swap_[ind] = swap_[cur_val-1]
+            pivots[ind] = 1
+        # Not.
+        elif cur_val < 0 and cur_val == a[ind+x]:
+            # first neg entry of 2x2 block identifier
+            if -cur_val != ind+2:
+                # Index value != array value --> permutation required
+                swap_[ind+x] = swap_[-cur_val-1]
+            pivots[ind+y] = 2
+            skip_2x2 = True
+        else:  # Doesn't make sense, give up
+            raise ValueError('While parsing the permutation array '
+                             'in "scipy.linalg.ldl", invalid entries '
+                             'found. The array syntax is invalid.')
+    return swap_, pivots
+
+
+def _ldl_get_d_and_l(ldu, pivs, lower=True, hermitian=True):
+    """
+    Helper function to extract the diagonal and triangular matrices for
+    LDL.T factorization.
+
+    Parameters
+    ----------
+    ldu : ndarray
+        The compact output returned by the LAPACK routing
+    pivs : ndarray
+        The sanitized array of {0, 1, 2} denoting the sizes of the pivots. For
+        every 2 there is a succeeding 0.
+    lower : bool, optional
+        If set to False, upper triangular part is considered.
+    hermitian : bool, optional
+        If set to False a symmetric complex array is assumed.
+
+    Returns
+    -------
+    d : ndarray
+        The block diagonal matrix.
+    lu : ndarray
+        The upper/lower triangular matrix
+    """
+    is_c = iscomplexobj(ldu)
+    d = diag(diag(ldu))
+    n = d.shape[0]
+    blk_i = 0  # block index
+
+    # row/column offsets for selecting sub-, super-diagonal
+    x, y = (1, 0) if lower else (0, 1)
+
+    lu = tril(ldu, -1) if lower else triu(ldu, 1)
+    diag_inds = arange(n)
+    lu[diag_inds, diag_inds] = 1
+
+    for blk in pivs[pivs != 0]:
+        # increment the block index and check for 2s
+        # if 2 then copy the off diagonals depending on uplo
+        inc = blk_i + blk
+
+        if blk == 2:
+            d[blk_i+x, blk_i+y] = ldu[blk_i+x, blk_i+y]
+            # If Hermitian matrix is factorized, the cross-offdiagonal element
+            # should be conjugated.
+            if is_c and hermitian:
+                d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y].conj()
+            else:
+                d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y]
+
+            lu[blk_i+x, blk_i+y] = 0.
+        blk_i = inc
+
+    return d, lu
+
+
+def _ldl_construct_tri_factor(lu, swap_vec, pivs, lower=True):
+    """
+    Helper function to construct explicit outer factors of LDL factorization.
+
+    If lower is True the permuted factors are multiplied as L(1)*L(2)*...*L(k).
+    Otherwise, the permuted factors are multiplied as L(k)*...*L(2)*L(1). See
+    LAPACK documentation for more details.
+
+    Parameters
+    ----------
+    lu : ndarray
+        The triangular array that is extracted from LAPACK routine call with
+        ones on the diagonals.
+    swap_vec : ndarray
+        The array that defines the row swapping indices. If the kth entry is m
+        then rows k,m are swapped. Notice that the mth entry is not necessarily
+        k to avoid undoing the swapping.
+    pivs : ndarray
+        The array that defines the block diagonal structure returned by
+        _ldl_sanitize_ipiv().
+    lower : bool, optional
+        The boolean to switch between lower and upper triangular structure.
+
+    Returns
+    -------
+    lu : ndarray
+        The square outer factor which satisfies the L * D * L.T = A
+    perm : ndarray
+        The permutation vector that brings the lu to the triangular form
+
+    Notes
+    -----
+    Note that the original argument "lu" is overwritten.
+
+    """
+    n = lu.shape[0]
+    perm = arange(n)
+    # Setup the reading order of the permutation matrix for upper/lower
+    rs, re, ri = (n-1, -1, -1) if lower else (0, n, 1)
+
+    for ind in range(rs, re, ri):
+        s_ind = swap_vec[ind]
+        if s_ind != ind:
+            # Column start and end positions
+            col_s = ind if lower else 0
+            col_e = n if lower else ind+1
+
+            # If we stumble upon a 2x2 block include both cols in the perm.
+            if pivs[ind] == (0 if lower else 2):
+                col_s += -1 if lower else 0
+                col_e += 0 if lower else 1
+            lu[[s_ind, ind], col_s:col_e] = lu[[ind, s_ind], col_s:col_e]
+            perm[[s_ind, ind]] = perm[[ind, s_ind]]
+
+    return lu, argsort(perm)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..06562a4a490a4328c08d4de45a5463427e33562b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
@@ -0,0 +1,389 @@
+"""LU decomposition functions."""
+
+from warnings import warn
+
+from numpy import asarray, asarray_chkfinite
+import numpy as np
+from itertools import product
+
+# Local imports
+from ._misc import _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs
+from ._decomp_lu_cython import lu_dispatcher
+
+lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+__all__ = ['lu', 'lu_solve', 'lu_factor']
+
+
+def lu_factor(a, overwrite_a=False, check_finite=True):
+    """
+    Compute pivoted LU decomposition of a matrix.
+
+    The decomposition is::
+
+        A = P L U
+
+    where P is a permutation matrix, L lower triangular with unit
+    diagonal elements, and U upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose
+    overwrite_a : bool, optional
+        Whether to overwrite data in A (may increase performance)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    lu : (M, N) ndarray
+        Matrix containing U in its upper triangle, and L in its lower triangle.
+        The unit diagonal elements of L are not stored.
+    piv : (K,) ndarray
+        Pivot indices representing the permutation matrix P:
+        row i of matrix was interchanged with row piv[i].
+        Of shape ``(K,)``, with ``K = min(M, N)``.
+
+    See Also
+    --------
+    lu : gives lu factorization in more user-friendly format
+    lu_solve : solve an equation system using the LU factorization of a matrix
+
+    Notes
+    -----
+    This is a wrapper to the ``*GETRF`` routines from LAPACK. Unlike
+    :func:`lu`, it outputs the L and U factors into a single array
+    and returns pivot indices instead of a permutation matrix.
+
+    While the underlying ``*GETRF`` routines return 1-based pivot indices, the
+    ``piv`` array returned by ``lu_factor`` contains 0-based indices.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lu_factor
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> lu, piv = lu_factor(A)
+    >>> piv
+    array([2, 2, 3, 3], dtype=int32)
+
+    Convert LAPACK's ``piv`` array to NumPy index and test the permutation
+
+    >>> def pivot_to_permutation(piv):
+    ...     perm = np.arange(len(piv))
+    ...     for i in range(len(piv)):
+    ...         perm[i], perm[piv[i]] = perm[piv[i]], perm[i]
+    ...     return perm
+    ...
+    >>> p_inv = pivot_to_permutation(piv)
+    >>> p_inv
+    array([2, 0, 3, 1])
+    >>> L, U = np.tril(lu, k=-1) + np.eye(4), np.triu(lu)
+    >>> np.allclose(A[p_inv] - L @ U, np.zeros((4, 4)))
+    True
+
+    The P matrix in P L U is defined by the inverse permutation and
+    can be recovered using argsort:
+
+    >>> p = np.argsort(p_inv)
+    >>> p
+    array([1, 3, 0, 2])
+    >>> np.allclose(A - L[p] @ U, np.zeros((4, 4)))
+    True
+
+    or alternatively:
+
+    >>> P = np.eye(4)[p]
+    >>> np.allclose(A - P @ L @ U, np.zeros((4, 4)))
+    True
+    """
+    if check_finite:
+        a1 = asarray_chkfinite(a)
+    else:
+        a1 = asarray(a)
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        lu = np.empty_like(a1)
+        piv = np.arange(0, dtype=np.int32)
+        return lu, piv
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    getrf, = get_lapack_funcs(('getrf',), (a1,))
+    lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of '
+                         'internal getrf (lu_factor)' % -info)
+    if info > 0:
+        warn("Diagonal number %d is exactly zero. Singular matrix." % info,
+             LinAlgWarning, stacklevel=2)
+    return lu, piv
+
+
+def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
+    """Solve an equation system, a x = b, given the LU factorization of a
+
+    Parameters
+    ----------
+    (lu, piv)
+        Factorization of the coefficient matrix a, as given by lu_factor.
+        In particular piv are 0-indexed pivot indices.
+    b : array
+        Right-hand side
+    trans : {0, 1, 2}, optional
+        Type of system to solve:
+
+        =====  =========
+        trans  system
+        =====  =========
+        0      a x   = b
+        1      a^T x = b
+        2      a^H x = b
+        =====  =========
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may increase performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        Solution to the system
+
+    See Also
+    --------
+    lu_factor : LU factorize a matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lu_factor, lu_solve
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> b = np.array([1, 1, 1, 1])
+    >>> lu, piv = lu_factor(A)
+    >>> x = lu_solve((lu, piv), b)
+    >>> np.allclose(A @ x - b, np.zeros((4,)))
+    True
+
+    """
+    (lu, piv) = lu_and_piv
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+    else:
+        b1 = asarray(b)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if lu.shape[0] != b1.shape[0]:
+        raise ValueError(f"Shapes of lu {lu.shape} and b {b1.shape} are incompatible")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        m = lu_solve((np.eye(2, dtype=lu.dtype), [0, 1]), np.ones(2, dtype=b.dtype))
+        return np.empty_like(b1, dtype=m.dtype)
+
+    getrs, = get_lapack_funcs(('getrs',), (lu, b1))
+    x, info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b)
+    if info == 0:
+        return x
+    raise ValueError('illegal value in %dth argument of internal gesv|posv'
+                     % -info)
+
+
+def lu(a, permute_l=False, overwrite_a=False, check_finite=True,
+       p_indices=False):
+    """
+    Compute LU decomposition of a matrix with partial pivoting.
+
+    The decomposition satisfies::
+
+        A = P @ L @ U
+
+    where ``P`` is a permutation matrix, ``L`` lower triangular with unit
+    diagonal elements, and ``U`` upper triangular. If `permute_l` is set to
+    ``True`` then ``L`` is returned already permuted and hence satisfying
+    ``A = L @ U``.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Array to decompose
+    permute_l : bool, optional
+        Perform the multiplication P*L (Default: do not permute)
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    p_indices : bool, optional
+        If ``True`` the permutation information is returned as row indices.
+        The default is ``False`` for backwards-compatibility reasons.
+
+    Returns
+    -------
+    **(If `permute_l` is ``False``)**
+
+    p : (..., M, M) ndarray
+        Permutation arrays or vectors depending on `p_indices`
+    l : (..., M, K) ndarray
+        Lower triangular or trapezoidal array with unit diagonal.
+        ``K = min(M, N)``
+    u : (..., K, N) ndarray
+        Upper triangular or trapezoidal array
+
+    **(If `permute_l` is ``True``)**
+
+    pl : (..., M, K) ndarray
+        Permuted L matrix.
+        ``K = min(M, N)``
+    u : (..., K, N) ndarray
+        Upper triangular or trapezoidal array
+
+    Notes
+    -----
+    Permutation matrices are costly since they are nothing but row reorder of
+    ``L`` and hence indices are strongly recommended to be used instead if the
+    permutation is required. The relation in the 2D case then becomes simply
+    ``A = L[P, :] @ U``. In higher dimensions, it is better to use `permute_l`
+    to avoid complicated indexing tricks.
+
+    In 2D case, if one has the indices however, for some reason, the
+    permutation matrix is still needed then it can be constructed by
+    ``np.eye(M)[P, :]``.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.linalg import lu
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> p, l, u = lu(A)
+    >>> np.allclose(A, p @ l @ u)
+    True
+    >>> p  # Permutation matrix
+    array([[0., 1., 0., 0.],  # Row index 1
+           [0., 0., 0., 1.],  # Row index 3
+           [1., 0., 0., 0.],  # Row index 0
+           [0., 0., 1., 0.]]) # Row index 2
+    >>> p, _, _ = lu(A, p_indices=True)
+    >>> p
+    array([1, 3, 0, 2], dtype=int32)  # as given by row indices above
+    >>> np.allclose(A, l[p, :] @ u)
+    True
+
+    We can also use nd-arrays, for example, a demonstration with 4D array:
+
+    >>> rng = np.random.default_rng()
+    >>> A = rng.uniform(low=-4, high=4, size=[3, 2, 4, 8])
+    >>> p, l, u = lu(A)
+    >>> p.shape, l.shape, u.shape
+    ((3, 2, 4, 4), (3, 2, 4, 4), (3, 2, 4, 8))
+    >>> np.allclose(A, p @ l @ u)
+    True
+    >>> PL, U = lu(A, permute_l=True)
+    >>> np.allclose(A, PL @ U)
+    True
+
+    """
+    a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+
+    # Also check if dtype is LAPACK compatible
+    if a1.dtype.char not in 'fdFD':
+        dtype_char = lapack_cast_dict[a1.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype {a1.dtype} cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a1 = a1.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+
+    *nd, m, n = a1.shape
+    k = min(m, n)
+    real_dchar = 'f' if a1.dtype.char in 'fF' else 'd'
+
+    # Empty input
+    if min(*a1.shape) == 0:
+        if permute_l:
+            PL = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
+            U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
+            return PL, U
+        else:
+            P = (np.empty([*nd, 0], dtype=np.int32) if p_indices else
+                 np.empty([*nd, 0, 0], dtype=real_dchar))
+            L = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
+            U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
+            return P, L, U
+
+    # Scalar case
+    if a1.shape[-2:] == (1, 1):
+        if permute_l:
+            return np.ones_like(a1), (a1 if overwrite_a else a1.copy())
+        else:
+            P = (np.zeros(shape=[*nd, m], dtype=int) if p_indices
+                 else np.ones_like(a1))
+            return P, np.ones_like(a1), (a1 if overwrite_a else a1.copy())
+
+    # Then check overwrite permission
+    if not _datacopied(a1, a):  # "a"  still alive through "a1"
+        if not overwrite_a:
+            # Data belongs to "a" so make a copy
+            a1 = a1.copy(order='C')
+        #  else: Do nothing we'll use "a" if possible
+    # else:  a1 has its own data thus free to scratch
+
+    # Then layout checks, might happen that overwrite is allowed but original
+    # array was read-only or non-contiguous.
+
+    if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
+        a1 = a1.copy(order='C')
+
+    if not nd:  # 2D array
+
+        p = np.empty(m, dtype=np.int32)
+        u = np.zeros([k, k], dtype=a1.dtype)
+        lu_dispatcher(a1, u, p, permute_l)
+        P, L, U = (p, a1, u) if m > n else (p, u, a1)
+
+    else:  # Stacked array
+
+        # Prepare the contiguous data holders
+        P = np.empty([*nd, m], dtype=np.int32)  # perm vecs
+
+        if m > n:  # Tall arrays, U will be created
+            U = np.zeros([*nd, k, k], dtype=a1.dtype)
+            for ind in product(*[range(x) for x in a1.shape[:-2]]):
+                lu_dispatcher(a1[ind], U[ind], P[ind], permute_l)
+            L = a1
+
+        else:  # Fat arrays, L will be created
+            L = np.zeros([*nd, k, k], dtype=a1.dtype)
+            for ind in product(*[range(x) for x in a1.shape[:-2]]):
+                lu_dispatcher(a1[ind], L[ind], P[ind], permute_l)
+            U = a1
+
+    # Convert permutation vecs to permutation arrays
+    # permute_l=False needed to enter here to avoid wasted efforts
+    if (not p_indices) and (not permute_l):
+        if nd:
+            Pa = np.zeros([*nd, m, m], dtype=real_dchar)
+            # An unreadable index hack - One-hot encoding for perm matrices
+            nd_ix = np.ix_(*([np.arange(x) for x in nd]+[np.arange(m)]))
+            Pa[(*nd_ix, P)] = 1
+            P = Pa
+        else:  # 2D case
+            Pa = np.zeros([m, m], dtype=real_dchar)
+            Pa[np.arange(m), P] = 1
+            P = Pa
+
+    return (L, U) if permute_l else (P, L, U)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0a175b1de32806102318cf69f7c5b4c3deddb03c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
@@ -0,0 +1,6 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def lu_decompose(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ...  # noqa: E501
+
+def lu_dispatcher(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ...  # noqa: E501
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fc3652899bed607ab1dd5e3f1663345010e93c1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
@@ -0,0 +1,111 @@
+import numpy as np
+from scipy.linalg import svd
+
+
+__all__ = ['polar']
+
+
+def polar(a, side="right"):
+    """
+    Compute the polar decomposition.
+
+    Returns the factors of the polar decomposition [1]_ `u` and `p` such
+    that ``a = up`` (if `side` is "right") or ``a = pu`` (if `side` is
+    "left"), where `p` is positive semidefinite. Depending on the shape
+    of `a`, either the rows or columns of `u` are orthonormal. When `a`
+    is a square array, `u` is a square unitary array. When `a` is not
+    square, the "canonical polar decomposition" [2]_ is computed.
+
+    Parameters
+    ----------
+    a : (m, n) array_like
+        The array to be factored.
+    side : {'left', 'right'}, optional
+        Determines whether a right or left polar decomposition is computed.
+        If `side` is "right", then ``a = up``.  If `side` is "left",  then
+        ``a = pu``.  The default is "right".
+
+    Returns
+    -------
+    u : (m, n) ndarray
+        If `a` is square, then `u` is unitary. If m > n, then the columns
+        of `a` are orthonormal, and if m < n, then the rows of `u` are
+        orthonormal.
+    p : ndarray
+        `p` is Hermitian positive semidefinite. If `a` is nonsingular, `p`
+        is positive definite. The shape of `p` is (n, n) or (m, m), depending
+        on whether `side` is "right" or "left", respectively.
+
+    References
+    ----------
+    .. [1] R. A. Horn and C. R. Johnson, "Matrix Analysis", Cambridge
+           University Press, 1985.
+    .. [2] N. J. Higham, "Functions of Matrices: Theory and Computation",
+           SIAM, 2008.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import polar
+    >>> a = np.array([[1, -1], [2, 4]])
+    >>> u, p = polar(a)
+    >>> u
+    array([[ 0.85749293, -0.51449576],
+           [ 0.51449576,  0.85749293]])
+    >>> p
+    array([[ 1.88648444,  1.2004901 ],
+           [ 1.2004901 ,  3.94446746]])
+
+    A non-square example, with m < n:
+
+    >>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]])
+    >>> u, p = polar(b)
+    >>> u
+    array([[-0.21196618, -0.42393237,  0.88054056],
+           [ 0.39378971,  0.78757942,  0.4739708 ]])
+    >>> p
+    array([[ 0.48470147,  0.96940295,  1.15122648],
+           [ 0.96940295,  1.9388059 ,  2.30245295],
+           [ 1.15122648,  2.30245295,  3.65696431]])
+    >>> u.dot(p)   # Verify the decomposition.
+    array([[ 0.5,  1. ,  2. ],
+           [ 1.5,  3. ,  4. ]])
+    >>> u.dot(u.T)   # The rows of u are orthonormal.
+    array([[  1.00000000e+00,  -2.07353665e-17],
+           [ -2.07353665e-17,   1.00000000e+00]])
+
+    Another non-square example, with m > n:
+
+    >>> c = b.T
+    >>> u, p = polar(c)
+    >>> u
+    array([[-0.21196618,  0.39378971],
+           [-0.42393237,  0.78757942],
+           [ 0.88054056,  0.4739708 ]])
+    >>> p
+    array([[ 1.23116567,  1.93241587],
+           [ 1.93241587,  4.84930602]])
+    >>> u.dot(p)   # Verify the decomposition.
+    array([[ 0.5,  1.5],
+           [ 1. ,  3. ],
+           [ 2. ,  4. ]])
+    >>> u.T.dot(u)  # The columns of u are orthonormal.
+    array([[  1.00000000e+00,  -1.26363763e-16],
+           [ -1.26363763e-16,   1.00000000e+00]])
+
+    """
+    if side not in ['right', 'left']:
+        raise ValueError("`side` must be either 'right' or 'left'")
+    a = np.asarray(a)
+    if a.ndim != 2:
+        raise ValueError("`a` must be a 2-D array.")
+
+    w, s, vh = svd(a, full_matrices=False)
+    u = w.dot(vh)
+    if side == 'right':
+        # a = up
+        p = (vh.T.conj() * s).dot(vh)
+    else:
+        # a = pu
+        p = (w * s).dot(w.T.conj())
+    return u, p
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..a41ad90770e3d53c741d85e6f46d4040bf203e7a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
@@ -0,0 +1,490 @@
+"""QR decomposition functions."""
+import numpy as np
+
+# Local imports
+from .lapack import get_lapack_funcs
+from ._misc import _datacopied
+
+__all__ = ['qr', 'qr_multiply', 'rq']
+
+
+def safecall(f, name, *args, **kwargs):
+    """Call a LAPACK routine, determining lwork automatically and handling
+    error return values"""
+    lwork = kwargs.get("lwork", None)
+    if lwork in (None, -1):
+        kwargs['lwork'] = -1
+        ret = f(*args, **kwargs)
+        kwargs['lwork'] = ret[-2][0].real.astype(np.int_)
+    ret = f(*args, **kwargs)
+    if ret[-1] < 0:
+        raise ValueError("illegal value in %dth argument of internal %s"
+                         % (-ret[-1], name))
+    return ret[:-2]
+
+
+def qr(a, overwrite_a=False, lwork=None, mode='full', pivoting=False,
+       check_finite=True):
+    """
+    Compute QR decomposition of a matrix.
+
+    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
+    and R upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be decomposed
+    overwrite_a : bool, optional
+        Whether data in `a` is overwritten (may improve performance if
+        `overwrite_a` is set to True by reusing the existing input data
+        structure rather than creating a new one.)
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+    mode : {'full', 'r', 'economic', 'raw'}, optional
+        Determines what information is to be returned: either both Q and R
+        ('full', default), only R ('r') or both Q and R but computed in
+        economy-size ('economic', see Notes). The final option 'raw'
+        (added in SciPy 0.11) makes the function return two matrices
+        (Q, TAU) in the internal format used by LAPACK.
+    pivoting : bool, optional
+        Whether or not factorization should include pivoting for rank-revealing
+        qr decomposition. If pivoting, compute the decomposition
+        ``A[:, P] = Q @ R`` as above, but where P is chosen such that the
+        diagonal of R is non-increasing. Equivalently, albeit less efficiently,
+        an explicit P matrix may be formed explicitly by permuting the rows or columns
+        (depending on the side of the equation on which it is to be used) of
+        an identity matrix. See Examples.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    Q : float or complex ndarray
+        Of shape (M, M), or (M, K) for ``mode='economic'``. Not returned
+        if ``mode='r'``. Replaced by tuple ``(Q, TAU)`` if ``mode='raw'``.
+    R : float or complex ndarray
+        Of shape (M, N), or (K, N) for ``mode in ['economic', 'raw']``.
+        ``K = min(M, N)``.
+    P : int ndarray
+        Of shape (N,) for ``pivoting=True``. Not returned if
+        ``pivoting=False``.
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines dgeqrf, zgeqrf,
+    dorgqr, zungqr, dgeqp3, and zgeqp3.
+
+    If ``mode=economic``, the shapes of Q and R are (M, K) and (K, N) instead
+    of (M,M) and (M,N), with ``K=min(M,N)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((9, 6))
+
+    >>> q, r = linalg.qr(a)
+    >>> np.allclose(a, np.dot(q, r))
+    True
+    >>> q.shape, r.shape
+    ((9, 9), (9, 6))
+
+    >>> r2 = linalg.qr(a, mode='r')
+    >>> np.allclose(r, r2)
+    True
+
+    >>> q3, r3 = linalg.qr(a, mode='economic')
+    >>> q3.shape, r3.shape
+    ((9, 6), (6, 6))
+
+    >>> q4, r4, p4 = linalg.qr(a, pivoting=True)
+    >>> d = np.abs(np.diag(r4))
+    >>> np.all(d[1:] <= d[:-1])
+    True
+    >>> np.allclose(a[:, p4], np.dot(q4, r4))
+    True
+    >>> P = np.eye(p4.size)[p4]
+    >>> np.allclose(a, np.dot(q4, r4) @ P)
+    True
+    >>> np.allclose(a @ P.T, np.dot(q4, r4))
+    True
+    >>> q4.shape, r4.shape, p4.shape
+    ((9, 9), (9, 6), (6,))
+
+    >>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True)
+    >>> q5.shape, r5.shape, p5.shape
+    ((9, 6), (6, 6), (6,))
+    >>> P = np.eye(6)[:, p5]
+    >>> np.allclose(a @ P, np.dot(q5, r5))
+    True
+
+    """
+    # 'qr' was the old default, equivalent to 'full'. Neither 'full' nor
+    # 'qr' are used below.
+    # 'raw' is used internally by qr_multiply
+    if mode not in ['full', 'qr', 'r', 'economic', 'raw']:
+        raise ValueError("Mode argument should be one of ['full', 'r', "
+                         "'economic', 'raw']")
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+    if len(a1.shape) != 2:
+        raise ValueError("expected a 2-D array")
+
+    M, N = a1.shape
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+
+        if mode not in ['economic', 'raw']:
+            Q = np.empty_like(a1, shape=(M, M))
+            Q[...] = np.identity(M)
+            R = np.empty_like(a1)
+        else:
+            Q = np.empty_like(a1, shape=(M, K))
+            R = np.empty_like(a1, shape=(K, N))
+
+        if pivoting:
+            Rj = R, np.arange(N, dtype=np.int32)
+        else:
+            Rj = R,
+
+        if mode == 'r':
+            return Rj
+        elif mode == 'raw':
+            qr = np.empty_like(a1, shape=(M, N))
+            tau = np.zeros_like(a1, shape=(K,))
+            return ((qr, tau),) + Rj
+        return (Q,) + Rj
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if pivoting:
+        geqp3, = get_lapack_funcs(('geqp3',), (a1,))
+        qr, jpvt, tau = safecall(geqp3, "geqp3", a1, overwrite_a=overwrite_a)
+        jpvt -= 1  # geqp3 returns a 1-based index array, so subtract 1
+    else:
+        geqrf, = get_lapack_funcs(('geqrf',), (a1,))
+        qr, tau = safecall(geqrf, "geqrf", a1, lwork=lwork,
+                           overwrite_a=overwrite_a)
+
+    if mode not in ['economic', 'raw'] or M < N:
+        R = np.triu(qr)
+    else:
+        R = np.triu(qr[:N, :])
+
+    if pivoting:
+        Rj = R, jpvt
+    else:
+        Rj = R,
+
+    if mode == 'r':
+        return Rj
+    elif mode == 'raw':
+        return ((qr, tau),) + Rj
+
+    gor_un_gqr, = get_lapack_funcs(('orgqr',), (qr,))
+
+    if M < N:
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr[:, :M], tau,
+                      lwork=lwork, overwrite_a=1)
+    elif mode == 'economic':
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr, tau, lwork=lwork,
+                      overwrite_a=1)
+    else:
+        t = qr.dtype.char
+        qqr = np.empty((M, M), dtype=t)
+        qqr[:, :N] = qr
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qqr, tau, lwork=lwork,
+                      overwrite_a=1)
+
+    return (Q,) + Rj
+
+
+def qr_multiply(a, c, mode='right', pivoting=False, conjugate=False,
+                overwrite_a=False, overwrite_c=False):
+    """
+    Calculate the QR decomposition and multiply Q with a matrix.
+
+    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
+    and R upper triangular. Multiply Q with a vector or a matrix c.
+
+    Parameters
+    ----------
+    a : (M, N), array_like
+        Input array
+    c : array_like
+        Input array to be multiplied by ``q``.
+    mode : {'left', 'right'}, optional
+        ``Q @ c`` is returned if mode is 'left', ``c @ Q`` is returned if
+        mode is 'right'.
+        The shape of c must be appropriate for the matrix multiplications,
+        if mode is 'left', ``min(a.shape) == c.shape[0]``,
+        if mode is 'right', ``a.shape[0] == c.shape[1]``.
+    pivoting : bool, optional
+        Whether or not factorization should include pivoting for rank-revealing
+        qr decomposition, see the documentation of qr.
+    conjugate : bool, optional
+        Whether Q should be complex-conjugated. This might be faster
+        than explicit conjugation.
+    overwrite_a : bool, optional
+        Whether data in a is overwritten (may improve performance)
+    overwrite_c : bool, optional
+        Whether data in c is overwritten (may improve performance).
+        If this is used, c must be big enough to keep the result,
+        i.e. ``c.shape[0]`` = ``a.shape[0]`` if mode is 'left'.
+
+    Returns
+    -------
+    CQ : ndarray
+        The product of ``Q`` and ``c``.
+    R : (K, N), ndarray
+        R array of the resulting QR factorization where ``K = min(M, N)``.
+    P : (N,) ndarray
+        Integer pivot array. Only returned when ``pivoting=True``.
+
+    Raises
+    ------
+    LinAlgError
+        Raised if QR decomposition fails.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines ``?GEQRF``, ``?ORMQR``,
+    ``?UNMQR``, and ``?GEQP3``.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import qr_multiply, qr
+    >>> A = np.array([[1, 3, 3], [2, 3, 2], [2, 3, 3], [1, 3, 2]])
+    >>> qc, r1, piv1 = qr_multiply(A, 2*np.eye(4), pivoting=1)
+    >>> qc
+    array([[-1.,  1., -1.],
+           [-1., -1.,  1.],
+           [-1., -1., -1.],
+           [-1.,  1.,  1.]])
+    >>> r1
+    array([[-6., -3., -5.            ],
+           [ 0., -1., -1.11022302e-16],
+           [ 0.,  0., -1.            ]])
+    >>> piv1
+    array([1, 0, 2], dtype=int32)
+    >>> q2, r2, piv2 = qr(A, mode='economic', pivoting=1)
+    >>> np.allclose(2*q2 - qc, np.zeros((4, 3)))
+    True
+
+    """
+    if mode not in ['left', 'right']:
+        raise ValueError("Mode argument can only be 'left' or 'right' but "
+                         f"not '{mode}'")
+    c = np.asarray_chkfinite(c)
+    if c.ndim < 2:
+        onedim = True
+        c = np.atleast_2d(c)
+        if mode == "left":
+            c = c.T
+    else:
+        onedim = False
+
+    a = np.atleast_2d(np.asarray(a))  # chkfinite done in qr
+    M, N = a.shape
+
+    if mode == 'left':
+        if c.shape[0] != min(M, N + overwrite_c*(M-N)):
+            raise ValueError('Array shapes are not compatible for Q @ c'
+                             f' operation: {a.shape} vs {c.shape}')
+    else:
+        if M != c.shape[1]:
+            raise ValueError('Array shapes are not compatible for c @ Q'
+                             f' operation: {c.shape} vs {a.shape}')
+
+    raw = qr(a, overwrite_a, None, "raw", pivoting)
+    Q, tau = raw[0]
+
+    # accommodate empty arrays
+    if c.size == 0:
+        return (np.empty_like(c),) + raw[1:]
+
+    gor_un_mqr, = get_lapack_funcs(('ormqr',), (Q,))
+    if gor_un_mqr.typecode in ('s', 'd'):
+        trans = "T"
+    else:
+        trans = "C"
+
+    Q = Q[:, :min(M, N)]
+    if M > N and mode == "left" and not overwrite_c:
+        if conjugate:
+            cc = np.zeros((c.shape[1], M), dtype=c.dtype, order="F")
+            cc[:, :N] = c.T
+        else:
+            cc = np.zeros((M, c.shape[1]), dtype=c.dtype, order="F")
+            cc[:N, :] = c
+            trans = "N"
+        if conjugate:
+            lr = "R"
+        else:
+            lr = "L"
+        overwrite_c = True
+    elif c.flags["C_CONTIGUOUS"] and trans == "T" or conjugate:
+        cc = c.T
+        if mode == "left":
+            lr = "R"
+        else:
+            lr = "L"
+    else:
+        trans = "N"
+        cc = c
+        if mode == "left":
+            lr = "L"
+        else:
+            lr = "R"
+    cQ, = safecall(gor_un_mqr, "gormqr/gunmqr", lr, trans, Q, tau, cc,
+                   overwrite_c=overwrite_c)
+    if trans != "N":
+        cQ = cQ.T
+    if mode == "right":
+        cQ = cQ[:, :min(M, N)]
+    if onedim:
+        cQ = cQ.ravel()
+
+    return (cQ,) + raw[1:]
+
+
+def rq(a, overwrite_a=False, lwork=None, mode='full', check_finite=True):
+    """
+    Compute RQ decomposition of a matrix.
+
+    Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal
+    and R upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be decomposed
+    overwrite_a : bool, optional
+        Whether data in a is overwritten (may improve performance)
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+    mode : {'full', 'r', 'economic'}, optional
+        Determines what information is to be returned: either both Q and R
+        ('full', default), only R ('r') or both Q and R but computed in
+        economy-size ('economic', see Notes).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    R : float or complex ndarray
+        Of shape (M, N) or (M, K) for ``mode='economic'``. ``K = min(M, N)``.
+    Q : float or complex ndarray
+        Of shape (N, N) or (K, N) for ``mode='economic'``. Not returned
+        if ``mode='r'``.
+
+    Raises
+    ------
+    LinAlgError
+        If decomposition fails.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf,
+    sorgrq, dorgrq, cungrq and zungrq.
+
+    If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead
+    of (N,N) and (M,N), with ``K=min(M,N)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((6, 9))
+    >>> r, q = linalg.rq(a)
+    >>> np.allclose(a, r @ q)
+    True
+    >>> r.shape, q.shape
+    ((6, 9), (9, 9))
+    >>> r2 = linalg.rq(a, mode='r')
+    >>> np.allclose(r, r2)
+    True
+    >>> r3, q3 = linalg.rq(a, mode='economic')
+    >>> r3.shape, q3.shape
+    ((6, 6), (6, 9))
+
+    """
+    if mode not in ['full', 'r', 'economic']:
+        raise ValueError(
+                 "Mode argument should be one of ['full', 'r', 'economic']")
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+    if len(a1.shape) != 2:
+        raise ValueError('expected matrix')
+
+    M, N = a1.shape
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+
+        if not mode == 'economic':
+            R = np.empty_like(a1)
+            Q = np.empty_like(a1, shape=(N, N))
+            Q[...] = np.identity(N)
+        else:
+            R = np.empty_like(a1, shape=(M, K))
+            Q = np.empty_like(a1, shape=(K, N))
+
+        if mode == 'r':
+            return R
+        return R, Q
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    gerqf, = get_lapack_funcs(('gerqf',), (a1,))
+    rq, tau = safecall(gerqf, 'gerqf', a1, lwork=lwork,
+                       overwrite_a=overwrite_a)
+    if not mode == 'economic' or N < M:
+        R = np.triu(rq, N-M)
+    else:
+        R = np.triu(rq[-M:, -M:])
+
+    if mode == 'r':
+        return R
+
+    gor_un_grq, = get_lapack_funcs(('orgrq',), (rq,))
+
+    if N < M:
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq[-N:], tau, lwork=lwork,
+                      overwrite_a=1)
+    elif mode == 'economic':
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq, tau, lwork=lwork,
+                      overwrite_a=1)
+    else:
+        rq1 = np.empty((N, N), dtype=rq.dtype)
+        rq1[-M:] = rq
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq1, tau, lwork=lwork,
+                      overwrite_a=1)
+
+    return R, Q
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
new file mode 100644
index 0000000000000000000000000000000000000000..39361f172df7f1985c7ed0fbc4d919b5c4545725
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
@@ -0,0 +1,449 @@
+import warnings
+
+import numpy as np
+from numpy import asarray_chkfinite
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs
+
+
+__all__ = ['qz', 'ordqz']
+
+_double_precision = ['i', 'l', 'd']
+
+
+def _select_function(sort):
+    if callable(sort):
+        # assume the user knows what they're doing
+        sfunction = sort
+    elif sort == 'lhp':
+        sfunction = _lhp
+    elif sort == 'rhp':
+        sfunction = _rhp
+    elif sort == 'iuc':
+        sfunction = _iuc
+    elif sort == 'ouc':
+        sfunction = _ouc
+    else:
+        raise ValueError("sort parameter must be None, a callable, or "
+                         "one of ('lhp','rhp','iuc','ouc')")
+
+    return sfunction
+
+
+def _lhp(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (np.real(x[nonzero]/y[nonzero]) < 0.0)
+    return out
+
+
+def _rhp(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (np.real(x[nonzero]/y[nonzero]) > 0.0)
+    return out
+
+
+def _iuc(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (abs(x[nonzero]/y[nonzero]) < 1.0)
+    return out
+
+
+def _ouc(x, y):
+    out = np.empty_like(x, dtype=bool)
+    xzero = (x == 0)
+    yzero = (y == 0)
+    out[xzero & yzero] = False
+    out[~xzero & yzero] = True
+    out[~yzero] = (abs(x[~yzero]/y[~yzero]) > 1.0)
+    return out
+
+
+def _qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
+        overwrite_b=False, check_finite=True):
+    if sort is not None:
+        # Disabled due to segfaults on win32, see ticket 1717.
+        raise ValueError("The 'sort' input of qz() has to be None and will be "
+                         "removed in a future release. Use ordqz instead.")
+
+    if output not in ['real', 'complex', 'r', 'c']:
+        raise ValueError("argument must be 'real', or 'complex'")
+
+    if check_finite:
+        a1 = asarray_chkfinite(A)
+        b1 = asarray_chkfinite(B)
+    else:
+        a1 = np.asarray(A)
+        b1 = np.asarray(B)
+
+    a_m, a_n = a1.shape
+    b_m, b_n = b1.shape
+    if not (a_m == a_n == b_m == b_n):
+        raise ValueError("Array dimensions must be square and agree")
+
+    typa = a1.dtype.char
+    if output in ['complex', 'c'] and typa not in ['F', 'D']:
+        if typa in _double_precision:
+            a1 = a1.astype('D')
+            typa = 'D'
+        else:
+            a1 = a1.astype('F')
+            typa = 'F'
+    typb = b1.dtype.char
+    if output in ['complex', 'c'] and typb not in ['F', 'D']:
+        if typb in _double_precision:
+            b1 = b1.astype('D')
+            typb = 'D'
+        else:
+            b1 = b1.astype('F')
+            typb = 'F'
+
+    overwrite_a = overwrite_a or (_datacopied(a1, A))
+    overwrite_b = overwrite_b or (_datacopied(b1, B))
+
+    gges, = get_lapack_funcs(('gges',), (a1, b1))
+
+    if lwork is None or lwork == -1:
+        # get optimal work array size
+        result = gges(lambda x: None, a1, b1, lwork=-1)
+        lwork = result[-2][0].real.astype(int)
+
+    def sfunction(x):
+        return None
+    result = gges(sfunction, a1, b1, lwork=lwork, overwrite_a=overwrite_a,
+                  overwrite_b=overwrite_b, sort_t=0)
+
+    info = result[-1]
+    if info < 0:
+        raise ValueError(f"Illegal value in argument {-info} of gges")
+    elif info > 0 and info <= a_n:
+        warnings.warn("The QZ iteration failed. (a,b) are not in Schur "
+                      "form, but ALPHAR(j), ALPHAI(j), and BETA(j) should be "
+                      f"correct for J={info-1},...,N", LinAlgWarning,
+                      stacklevel=3)
+    elif info == a_n+1:
+        raise LinAlgError("Something other than QZ iteration failed")
+    elif info == a_n+2:
+        raise LinAlgError("After reordering, roundoff changed values of some "
+                          "complex eigenvalues so that leading eigenvalues "
+                          "in the Generalized Schur form no longer satisfy "
+                          "sort=True. This could also be due to scaling.")
+    elif info == a_n+3:
+        raise LinAlgError("Reordering failed in tgsen")
+
+    return result, gges.typecode
+
+
+def qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
+       overwrite_b=False, check_finite=True):
+    """
+    QZ decomposition for generalized eigenvalues of a pair of matrices.
+
+    The QZ, or generalized Schur, decomposition for a pair of n-by-n
+    matrices (A,B) is::
+
+        (A,B) = (Q @ AA @ Z*, Q @ BB @ Z*)
+
+    where AA, BB is in generalized Schur form if BB is upper-triangular
+    with non-negative diagonal and AA is upper-triangular, or for real QZ
+    decomposition (``output='real'``) block upper triangular with 1x1
+    and 2x2 blocks. In this case, the 1x1 blocks correspond to real
+    generalized eigenvalues and 2x2 blocks are 'standardized' by making
+    the corresponding elements of BB have the form::
+
+        [ a 0 ]
+        [ 0 b ]
+
+    and the pair of corresponding 2x2 blocks in AA and BB will have a complex
+    conjugate pair of generalized eigenvalues. If (``output='complex'``) or
+    A and B are complex matrices, Z' denotes the conjugate-transpose of Z.
+    Q and Z are unitary matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        2-D array to decompose
+    B : (N, N) array_like
+        2-D array to decompose
+    output : {'real', 'complex'}, optional
+        Construct the real or complex QZ decomposition for real matrices.
+        Default is 'real'.
+    lwork : int, optional
+        Work array size. If None or -1, it is automatically computed.
+    sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        NOTE: THIS INPUT IS DISABLED FOR NOW. Use ordqz instead.
+
+        Specifies whether the upper eigenvalues should be sorted. A callable
+        may be passed that, given a eigenvalue, returns a boolean denoting
+        whether the eigenvalue should be sorted to the top-left (True). For
+        real matrix pairs, the sort function takes three real arguments
+        (alphar, alphai, beta). The eigenvalue
+        ``x = (alphar + alphai*1j)/beta``. For complex matrix pairs or
+        output='complex', the sort function takes two complex arguments
+        (alpha, beta). The eigenvalue ``x = (alpha/beta)``.  Alternatively,
+        string parameters may be used:
+
+            - 'lhp'   Left-hand plane (x.real < 0.0)
+            - 'rhp'   Right-hand plane (x.real > 0.0)
+            - 'iuc'   Inside the unit circle (x*x.conjugate() < 1.0)
+            - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)
+
+        Defaults to None (no sorting).
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+    check_finite : bool, optional
+        If true checks the elements of `A` and `B` are finite numbers. If
+        false does no checking and passes matrix through to
+        underlying algorithm.
+
+    Returns
+    -------
+    AA : (N, N) ndarray
+        Generalized Schur form of A.
+    BB : (N, N) ndarray
+        Generalized Schur form of B.
+    Q : (N, N) ndarray
+        The left Schur vectors.
+    Z : (N, N) ndarray
+        The right Schur vectors.
+
+    See Also
+    --------
+    ordqz
+
+    Notes
+    -----
+    Q is transposed versus the equivalent function in Matlab.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import qz
+
+    >>> A = np.array([[1, 2, -1], [5, 5, 5], [2, 4, -8]])
+    >>> B = np.array([[1, 1, -3], [3, 1, -1], [5, 6, -2]])
+
+    Compute the decomposition.  The QZ decomposition is not unique, so
+    depending on the underlying library that is used, there may be
+    differences in the signs of coefficients in the following output.
+
+    >>> AA, BB, Q, Z = qz(A, B)
+    >>> AA
+    array([[-1.36949157, -4.05459025,  7.44389431],
+           [ 0.        ,  7.65653432,  5.13476017],
+           [ 0.        , -0.65978437,  2.4186015 ]])  # may vary
+    >>> BB
+    array([[ 1.71890633, -1.64723705, -0.72696385],
+           [ 0.        ,  8.6965692 , -0.        ],
+           [ 0.        ,  0.        ,  2.27446233]])  # may vary
+    >>> Q
+    array([[-0.37048362,  0.1903278 ,  0.90912992],
+           [-0.90073232,  0.16534124, -0.40167593],
+           [ 0.22676676,  0.96769706, -0.11017818]])  # may vary
+    >>> Z
+    array([[-0.67660785,  0.63528924, -0.37230283],
+           [ 0.70243299,  0.70853819, -0.06753907],
+           [ 0.22088393, -0.30721526, -0.92565062]])  # may vary
+
+    Verify the QZ decomposition.  With real output, we only need the
+    transpose of ``Z`` in the following expressions.
+
+    >>> Q @ AA @ Z.T  # Should be A
+    array([[ 1.,  2., -1.],
+           [ 5.,  5.,  5.],
+           [ 2.,  4., -8.]])
+    >>> Q @ BB @ Z.T  # Should be B
+    array([[ 1.,  1., -3.],
+           [ 3.,  1., -1.],
+           [ 5.,  6., -2.]])
+
+    Repeat the decomposition, but with ``output='complex'``.
+
+    >>> AA, BB, Q, Z = qz(A, B, output='complex')
+
+    For conciseness in the output, we use ``np.set_printoptions()`` to set
+    the output precision of NumPy arrays to 3 and display tiny values as 0.
+
+    >>> np.set_printoptions(precision=3, suppress=True)
+    >>> AA
+    array([[-1.369+0.j   ,  2.248+4.237j,  4.861-5.022j],
+           [ 0.   +0.j   ,  7.037+2.922j,  0.794+4.932j],
+           [ 0.   +0.j   ,  0.   +0.j   ,  2.655-1.103j]])  # may vary
+    >>> BB
+    array([[ 1.719+0.j   , -1.115+1.j   , -0.763-0.646j],
+           [ 0.   +0.j   ,  7.24 +0.j   , -3.144+3.322j],
+           [ 0.   +0.j   ,  0.   +0.j   ,  2.732+0.j   ]])  # may vary
+    >>> Q
+    array([[ 0.326+0.175j, -0.273-0.029j, -0.886-0.052j],
+           [ 0.794+0.426j, -0.093+0.134j,  0.402-0.02j ],
+           [-0.2  -0.107j, -0.816+0.482j,  0.151-0.167j]])  # may vary
+    >>> Z
+    array([[ 0.596+0.32j , -0.31 +0.414j,  0.393-0.347j],
+           [-0.619-0.332j, -0.479+0.314j,  0.154-0.393j],
+           [-0.195-0.104j,  0.576+0.27j ,  0.715+0.187j]])  # may vary
+
+    With complex arrays, we must use ``Z.conj().T`` in the following
+    expressions to verify the decomposition.
+
+    >>> Q @ AA @ Z.conj().T  # Should be A
+    array([[ 1.-0.j,  2.-0.j, -1.-0.j],
+           [ 5.+0.j,  5.+0.j,  5.-0.j],
+           [ 2.+0.j,  4.+0.j, -8.+0.j]])
+    >>> Q @ BB @ Z.conj().T  # Should be B
+    array([[ 1.+0.j,  1.+0.j, -3.+0.j],
+           [ 3.-0.j,  1.-0.j, -1.+0.j],
+           [ 5.+0.j,  6.+0.j, -2.+0.j]])
+
+    """
+    # output for real
+    # AA, BB, sdim, alphar, alphai, beta, vsl, vsr, work, info
+    # output for complex
+    # AA, BB, sdim, alpha, beta, vsl, vsr, work, info
+    result, _ = _qz(A, B, output=output, lwork=lwork, sort=sort,
+                    overwrite_a=overwrite_a, overwrite_b=overwrite_b,
+                    check_finite=check_finite)
+    return result[0], result[1], result[-4], result[-3]
+
+
+def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
+          overwrite_b=False, check_finite=True):
+    """QZ decomposition for a pair of matrices with reordering.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        2-D array to decompose
+    B : (N, N) array_like
+        2-D array to decompose
+    sort : {callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        Specifies whether the upper eigenvalues should be sorted. A
+        callable may be passed that, given an ordered pair ``(alpha,
+        beta)`` representing the eigenvalue ``x = (alpha/beta)``,
+        returns a boolean denoting whether the eigenvalue should be
+        sorted to the top-left (True). For the real matrix pairs
+        ``beta`` is real while ``alpha`` can be complex, and for
+        complex matrix pairs both ``alpha`` and ``beta`` can be
+        complex. The callable must be able to accept a NumPy
+        array. Alternatively, string parameters may be used:
+
+            - 'lhp'   Left-hand plane (x.real < 0.0)
+            - 'rhp'   Right-hand plane (x.real > 0.0)
+            - 'iuc'   Inside the unit circle (x*x.conjugate() < 1.0)
+            - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)
+
+        With the predefined sorting functions, an infinite eigenvalue
+        (i.e., ``alpha != 0`` and ``beta = 0``) is considered to lie in
+        neither the left-hand nor the right-hand plane, but it is
+        considered to lie outside the unit circle. For the eigenvalue
+        ``(alpha, beta) = (0, 0)``, the predefined sorting functions
+        all return `False`.
+    output : str {'real','complex'}, optional
+        Construct the real or complex QZ decomposition for real matrices.
+        Default is 'real'.
+    overwrite_a : bool, optional
+        If True, the contents of A are overwritten.
+    overwrite_b : bool, optional
+        If True, the contents of B are overwritten.
+    check_finite : bool, optional
+        If true checks the elements of `A` and `B` are finite numbers. If
+        false does no checking and passes matrix through to
+        underlying algorithm.
+
+    Returns
+    -------
+    AA : (N, N) ndarray
+        Generalized Schur form of A.
+    BB : (N, N) ndarray
+        Generalized Schur form of B.
+    alpha : (N,) ndarray
+        alpha = alphar + alphai * 1j. See notes.
+    beta : (N,) ndarray
+        See notes.
+    Q : (N, N) ndarray
+        The left Schur vectors.
+    Z : (N, N) ndarray
+        The right Schur vectors.
+
+    See Also
+    --------
+    qz
+
+    Notes
+    -----
+    On exit, ``(ALPHAR(j) + ALPHAI(j)*i)/BETA(j), j=1,...,N``, will be the
+    generalized eigenvalues.  ``ALPHAR(j) + ALPHAI(j)*i`` and
+    ``BETA(j),j=1,...,N`` are the diagonals of the complex Schur form (S,T)
+    that would result if the 2-by-2 diagonal blocks of the real generalized
+    Schur form of (A,B) were further reduced to triangular form using complex
+    unitary transformations. If ALPHAI(j) is zero, then the jth eigenvalue is
+    real; if positive, then the ``j``\\ th and ``(j+1)``\\ st eigenvalues are a
+    complex conjugate pair, with ``ALPHAI(j+1)`` negative.
+
+    .. versionadded:: 0.17.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import ordqz
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> B = np.array([[0, 6, 0, 0], [5, 0, 2, 1], [5, 2, 6, 6], [4, 7, 7, 7]])
+    >>> AA, BB, alpha, beta, Q, Z = ordqz(A, B, sort='lhp')
+
+    Since we have sorted for left half plane eigenvalues, negatives come first
+
+    >>> (alpha/beta).real < 0
+    array([ True,  True, False, False], dtype=bool)
+
+    """
+    (AA, BB, _, *ab, Q, Z, _, _), typ = _qz(A, B, output=output, sort=None,
+                                            overwrite_a=overwrite_a,
+                                            overwrite_b=overwrite_b,
+                                            check_finite=check_finite)
+
+    if typ == 's':
+        alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
+    elif typ == 'd':
+        alpha, beta = ab[0] + ab[1]*1.j, ab[2]
+    else:
+        alpha, beta = ab
+
+    sfunction = _select_function(sort)
+    select = sfunction(alpha, beta)
+
+    tgsen = get_lapack_funcs('tgsen', (AA, BB))
+    # the real case needs 4n + 16 lwork
+    lwork = 4*AA.shape[0] + 16 if typ in 'sd' else 1
+    AAA, BBB, *ab, QQ, ZZ, _, _, _, _, info = tgsen(select, AA, BB, Q, Z,
+                                                    ijob=0,
+                                                    lwork=lwork, liwork=1)
+
+    # Once more for tgsen output
+    if typ == 's':
+        alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
+    elif typ == 'd':
+        alpha, beta = ab[0] + ab[1]*1.j, ab[2]
+    else:
+        alpha, beta = ab
+
+    if info < 0:
+        raise ValueError(f"Illegal value in argument {-info} of tgsen")
+    elif info == 1:
+        raise ValueError("Reordering of (A, B) failed because the transformed"
+                         " matrix pair (A, B) would be too far from "
+                         "generalized Schur form; the problem is very "
+                         "ill-conditioned. (A, B) may have been partially "
+                         "reordered.")
+
+    return AAA, BBB, alpha, beta, QQ, ZZ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..8609a175e16d663938386c6b45d190cd0e5dafd8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
@@ -0,0 +1,334 @@
+"""Schur decomposition functions."""
+import numpy as np
+from numpy import asarray_chkfinite, single, asarray, array
+from numpy.linalg import norm
+
+
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs
+from ._decomp import eigvals
+
+__all__ = ['schur', 'rsf2csf']
+
+_double_precision = ['i', 'l', 'd']
+
+
+def schur(a, output='real', lwork=None, overwrite_a=False, sort=None,
+          check_finite=True):
+    """
+    Compute Schur decomposition of a matrix.
+
+    The Schur decomposition is::
+
+        A = Z T Z^H
+
+    where Z is unitary and T is either upper-triangular, or for real
+    Schur decomposition (output='real'), quasi-upper triangular. In
+    the quasi-triangular form, 2x2 blocks describing complex-valued
+    eigenvalue pairs may extrude from the diagonal.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to decompose
+    output : {'real', 'complex'}, optional
+        When the dtype of `a` is real, this specifies whether to compute
+        the real or complex Schur decomposition.
+        When the dtype of `a` is complex, this argument is ignored, and the
+        complex Schur decomposition is computed.
+    lwork : int, optional
+        Work array size. If None or -1, it is automatically computed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance).
+    sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        Specifies whether the upper eigenvalues should be sorted. A callable
+        may be passed that, given an eigenvalue, returns a boolean denoting
+        whether the eigenvalue should be sorted to the top-left (True).
+
+        - If ``output='complex'`` OR the dtype of `a` is complex, the callable
+          should have one argument: the eigenvalue expressed as a complex number.
+        - If ``output='real'`` AND the dtype of `a` is real, the callable should have
+          two arguments: the real and imaginary parts of the eigenvalue, respectively.
+
+        Alternatively, string parameters may be used::
+
+            'lhp'   Left-hand plane (real(eigenvalue) < 0.0)
+            'rhp'   Right-hand plane (real(eigenvalue) >= 0.0)
+            'iuc'   Inside the unit circle (abs(eigenvalue) <= 1.0)
+            'ouc'   Outside the unit circle (abs(eigenvalue) > 1.0)
+
+        Defaults to None (no sorting).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    T : (M, M) ndarray
+        Schur form of A. It is real-valued for the real Schur decomposition.
+    Z : (M, M) ndarray
+        An unitary Schur transformation matrix for A.
+        It is real-valued for the real Schur decomposition.
+    sdim : int
+        If and only if sorting was requested, a third return value will
+        contain the number of eigenvalues satisfying the sort condition.
+        Note that complex conjugate pairs for which the condition is true
+        for either eigenvalue count as 2.
+
+    Raises
+    ------
+    LinAlgError
+        Error raised under three conditions:
+
+        1. The algorithm failed due to a failure of the QR algorithm to
+           compute all eigenvalues.
+        2. If eigenvalue sorting was requested, the eigenvalues could not be
+           reordered due to a failure to separate eigenvalues, usually because
+           of poor conditioning.
+        3. If eigenvalue sorting was requested, roundoff errors caused the
+           leading eigenvalues to no longer satisfy the sorting condition.
+
+    See Also
+    --------
+    rsf2csf : Convert real Schur form to complex Schur form
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import schur, eigvals
+    >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
+    >>> T, Z = schur(A)
+    >>> T
+    array([[ 2.65896708,  1.42440458, -1.92933439],
+           [ 0.        , -0.32948354, -0.49063704],
+           [ 0.        ,  1.31178921, -0.32948354]])
+    >>> Z
+    array([[0.72711591, -0.60156188, 0.33079564],
+           [0.52839428, 0.79801892, 0.28976765],
+           [0.43829436, 0.03590414, -0.89811411]])
+
+    >>> T2, Z2 = schur(A, output='complex')
+    >>> T2
+    array([[ 2.65896708, -1.22839825+1.32378589j,  0.42590089+1.51937378j], # may vary
+           [ 0.        , -0.32948354+0.80225456j, -0.59877807+0.56192146j],
+           [ 0.        ,  0.                    , -0.32948354-0.80225456j]])
+    >>> eigvals(T2)
+    array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j])   # may vary
+
+    A custom eigenvalue-sorting condition that sorts by positive imaginary part
+    is satisfied by only one eigenvalue.
+
+    >>> _, _, sdim = schur(A, output='complex', sort=lambda x: x.imag > 1e-15)
+    >>> sdim
+    1
+
+    When ``output='real'`` and the array `a` is real, the `sort` callable must accept
+    the real and imaginary parts as separate arguments. Note that now the complex
+    eigenvalues ``-0.32948354+0.80225456j`` and ``-0.32948354-0.80225456j`` will be
+    treated as a complex conjugate pair, and according to the `sdim` documentation,
+    complex conjugate pairs for which the condition is True for *either* eigenvalue
+    increase `sdim` by *two*.
+
+    >>> _, _, sdim = schur(A, output='real', sort=lambda x, y: y > 1e-15)
+    >>> sdim
+    2
+
+    """
+    if output not in ['real', 'complex', 'r', 'c']:
+        raise ValueError("argument must be 'real', or 'complex'")
+    if check_finite:
+        a1 = asarray_chkfinite(a)
+    else:
+        a1 = asarray(a)
+    if np.issubdtype(a1.dtype, np.integer):
+        a1 = asarray(a, dtype=np.dtype("long"))
+    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
+        raise ValueError('expected square matrix')
+
+    typ = a1.dtype.char
+    if output in ['complex', 'c'] and typ not in ['F', 'D']:
+        if typ in _double_precision:
+            a1 = a1.astype('D')
+        else:
+            a1 = a1.astype('F')
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        t0, z0 = schur(np.eye(2, dtype=a1.dtype))
+        if sort is None:
+            return (np.empty_like(a1, dtype=t0.dtype),
+                    np.empty_like(a1, dtype=z0.dtype))
+        else:
+            return (np.empty_like(a1, dtype=t0.dtype),
+                    np.empty_like(a1, dtype=z0.dtype), 0)
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    gees, = get_lapack_funcs(('gees',), (a1,))
+    if lwork is None or lwork == -1:
+        # get optimal work array
+        result = gees(lambda x: None, a1, lwork=-1)
+        lwork = result[-2][0].real.astype(np.int_)
+
+    if sort is None:
+        sort_t = 0
+        def sfunction(x, y=None):
+            return None
+    else:
+        sort_t = 1
+        if callable(sort):
+            sfunction = sort
+        elif sort == 'lhp':
+            def sfunction(x, y=None):
+                return x.real < 0.0
+        elif sort == 'rhp':
+            def sfunction(x, y=None):
+                return x.real >= 0.0
+        elif sort == 'iuc':
+            def sfunction(x, y=None):
+                z = x if y is None else x + y*1j
+                return abs(z) <= 1.0
+        elif sort == 'ouc':
+            def sfunction(x, y=None):
+                z = x if y is None else x + y*1j
+                return abs(z) > 1.0
+        else:
+            raise ValueError("'sort' parameter must either be 'None', or a "
+                             "callable, or one of ('lhp','rhp','iuc','ouc')")
+
+    result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a,
+                  sort_t=sort_t)
+
+    info = result[-1]
+    if info < 0:
+        raise ValueError(f'illegal value in {-info}-th argument of internal gees')
+    elif info == a1.shape[0] + 1:
+        raise LinAlgError('Eigenvalues could not be separated for reordering.')
+    elif info == a1.shape[0] + 2:
+        raise LinAlgError('Leading eigenvalues do not satisfy sort condition.')
+    elif info > 0:
+        raise LinAlgError("Schur form not found. Possibly ill-conditioned.")
+
+    if sort is None:
+        return result[0], result[-3]
+    else:
+        return result[0], result[-3], result[1]
+
+
+eps = np.finfo(float).eps
+feps = np.finfo(single).eps
+
+_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0,
+               'f': 0, 'd': 0, 'F': 1, 'D': 1}
+_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
+_array_type = [['f', 'd'], ['F', 'D']]
+
+
+def _commonType(*arrays):
+    kind = 0
+    precision = 0
+    for a in arrays:
+        t = a.dtype.char
+        kind = max(kind, _array_kind[t])
+        precision = max(precision, _array_precision[t])
+    return _array_type[kind][precision]
+
+
+def _castCopy(type, *arrays):
+    cast_arrays = ()
+    for a in arrays:
+        if a.dtype.char == type:
+            cast_arrays = cast_arrays + (a.copy(),)
+        else:
+            cast_arrays = cast_arrays + (a.astype(type),)
+    if len(cast_arrays) == 1:
+        return cast_arrays[0]
+    else:
+        return cast_arrays
+
+
+def rsf2csf(T, Z, check_finite=True):
+    """
+    Convert real Schur form to complex Schur form.
+
+    Convert a quasi-diagonal real-valued Schur form to the upper-triangular
+    complex-valued Schur form.
+
+    Parameters
+    ----------
+    T : (M, M) array_like
+        Real Schur form of the original array
+    Z : (M, M) array_like
+        Schur transformation matrix
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    T : (M, M) ndarray
+        Complex Schur form of the original array
+    Z : (M, M) ndarray
+        Schur transformation matrix corresponding to the complex form
+
+    See Also
+    --------
+    schur : Schur decomposition of an array
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import schur, rsf2csf
+    >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
+    >>> T, Z = schur(A)
+    >>> T
+    array([[ 2.65896708,  1.42440458, -1.92933439],
+           [ 0.        , -0.32948354, -0.49063704],
+           [ 0.        ,  1.31178921, -0.32948354]])
+    >>> Z
+    array([[0.72711591, -0.60156188, 0.33079564],
+           [0.52839428, 0.79801892, 0.28976765],
+           [0.43829436, 0.03590414, -0.89811411]])
+    >>> T2 , Z2 = rsf2csf(T, Z)
+    >>> T2
+    array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j],
+           [0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j],
+           [0.+0.j , 0.+0.j, -0.32948354-0.802254558j]])
+    >>> Z2
+    array([[0.72711591+0.j,  0.28220393-0.31385693j,  0.51319638-0.17258824j],
+           [0.52839428+0.j,  0.24720268+0.41635578j, -0.68079517-0.15118243j],
+           [0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]])
+
+    """
+    if check_finite:
+        Z, T = map(asarray_chkfinite, (Z, T))
+    else:
+        Z, T = map(asarray, (Z, T))
+
+    for ind, X in enumerate([Z, T]):
+        if X.ndim != 2 or X.shape[0] != X.shape[1]:
+            raise ValueError(f"Input '{'ZT'[ind]}' must be square.")
+
+    if T.shape[0] != Z.shape[0]:
+        message = f"Input array shapes must match: Z: {Z.shape} vs. T: {T.shape}"
+        raise ValueError(message)
+    N = T.shape[0]
+    t = _commonType(Z, T, array([3.0], 'F'))
+    Z, T = _castCopy(t, Z, T)
+
+    for m in range(N-1, 0, -1):
+        if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])):
+            mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m]
+            r = norm([mu[0], T[m, m-1]])
+            c = mu[0] / r
+            s = T[m, m-1] / r
+            G = array([[c.conj(), s], [-s, c]], dtype=t)
+
+            T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:])
+            T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T)
+            Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T)
+
+        T[m, m-1] = 0.0
+    return T, Z
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..98425f6c11e727d582102dce72baeb9cbdb6c40b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
@@ -0,0 +1,534 @@
+"""SVD decomposition functions."""
+import numpy as np
+from numpy import zeros, r_, diag, dot, arccos, arcsin, where, clip
+
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs, _compute_lwork
+from ._decomp import _asarray_validated
+
+__all__ = ['svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space']
+
+
+def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False,
+        check_finite=True, lapack_driver='gesdd'):
+    """
+    Singular Value Decomposition.
+
+    Factorizes the matrix `a` into two unitary matrices ``U`` and ``Vh``, and
+    a 1-D array ``s`` of singular values (real, non-negative) such that
+    ``a == U @ S @ Vh``, where ``S`` is a suitably shaped matrix of zeros with
+    main diagonal ``s``.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose.
+    full_matrices : bool, optional
+        If True (default), `U` and `Vh` are of shape ``(M, M)``, ``(N, N)``.
+        If False, the shapes are ``(M, K)`` and ``(K, N)``, where
+        ``K = min(M, N)``.
+    compute_uv : bool, optional
+        Whether to compute also ``U`` and ``Vh`` in addition to ``s``.
+        Default is True.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : {'gesdd', 'gesvd'}, optional
+        Whether to use the more efficient divide-and-conquer approach
+        (``'gesdd'``) or general rectangular approach (``'gesvd'``)
+        to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
+        Default is ``'gesdd'``.
+
+    Returns
+    -------
+    U : ndarray
+        Unitary matrix having left singular vectors as columns.
+        Of shape ``(M, M)`` or ``(M, K)``, depending on `full_matrices`.
+    s : ndarray
+        The singular values, sorted in non-increasing order.
+        Of shape (K,), with ``K = min(M, N)``.
+    Vh : ndarray
+        Unitary matrix having right singular vectors as rows.
+        Of shape ``(N, N)`` or ``(K, N)`` depending on `full_matrices`.
+
+    For ``compute_uv=False``, only ``s`` is returned.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    svdvals : Compute singular values of a matrix.
+    diagsvd : Construct the Sigma matrix, given the vector s.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> m, n = 9, 6
+    >>> a = rng.standard_normal((m, n)) + 1.j*rng.standard_normal((m, n))
+    >>> U, s, Vh = linalg.svd(a)
+    >>> U.shape,  s.shape, Vh.shape
+    ((9, 9), (6,), (6, 6))
+
+    Reconstruct the original matrix from the decomposition:
+
+    >>> sigma = np.zeros((m, n))
+    >>> for i in range(min(m, n)):
+    ...     sigma[i, i] = s[i]
+    >>> a1 = np.dot(U, np.dot(sigma, Vh))
+    >>> np.allclose(a, a1)
+    True
+
+    Alternatively, use ``full_matrices=False`` (notice that the shape of
+    ``U`` is then ``(m, n)`` instead of ``(m, m)``):
+
+    >>> U, s, Vh = linalg.svd(a, full_matrices=False)
+    >>> U.shape, s.shape, Vh.shape
+    ((9, 6), (6,), (6, 6))
+    >>> S = np.diag(s)
+    >>> np.allclose(a, np.dot(U, np.dot(S, Vh)))
+    True
+
+    >>> s2 = linalg.svd(a, compute_uv=False)
+    >>> np.allclose(s, s2)
+    True
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2:
+        raise ValueError('expected matrix')
+    m, n = a1.shape
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        u0, s0, v0 = svd(np.eye(2, dtype=a1.dtype))
+
+        s = np.empty_like(a1, shape=(0,), dtype=s0.dtype)
+        if full_matrices:
+            u = np.empty_like(a1, shape=(m, m), dtype=u0.dtype)
+            u[...] = np.identity(m)
+            v = np.empty_like(a1, shape=(n, n), dtype=v0.dtype)
+            v[...] = np.identity(n)
+        else:
+            u = np.empty_like(a1, shape=(m, 0), dtype=u0.dtype)
+            v = np.empty_like(a1, shape=(0, n), dtype=v0.dtype)
+        if compute_uv:
+            return u, s, v
+        else:
+            return s
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if not isinstance(lapack_driver, str):
+        raise TypeError('lapack_driver must be a string')
+    if lapack_driver not in ('gesdd', 'gesvd'):
+        message = f'lapack_driver must be "gesdd" or "gesvd", not "{lapack_driver}"'
+        raise ValueError(message)
+
+    if compute_uv:
+        # XXX: revisit int32 when ILP64 lapack becomes a thing
+        max_mn, min_mn = (m, n) if m > n else (n, m)
+        if full_matrices:
+            if max_mn*max_mn > np.iinfo(np.int32).max:
+                raise ValueError(f"Indexing a matrix size {max_mn} x {max_mn} "
+                                  "would incur integer overflow in LAPACK. "
+                                  "Try using numpy.linalg.svd instead.")
+        else:
+            sz = max(m * min_mn, n * min_mn)
+            if max(m * min_mn, n * min_mn) > np.iinfo(np.int32).max:
+                raise ValueError(f"Indexing a matrix of {sz} elements would "
+                                  "incur an in integer overflow in LAPACK. "
+                                  "Try using numpy.linalg.svd instead.")
+
+    funcs = (lapack_driver, lapack_driver + '_lwork')
+    # XXX: As of 1.14.1 it isn't possible to build SciPy with ILP64,
+    # so the following line always yields a LP64 (32-bit pointer size) variant
+    gesXd, gesXd_lwork = get_lapack_funcs(funcs, (a1,), ilp64="preferred")
+
+    # compute optimal lwork
+    lwork = _compute_lwork(gesXd_lwork, a1.shape[0], a1.shape[1],
+                           compute_uv=compute_uv, full_matrices=full_matrices)
+
+    # perform decomposition
+    u, s, v, info = gesXd(a1, compute_uv=compute_uv, lwork=lwork,
+                          full_matrices=full_matrices, overwrite_a=overwrite_a)
+
+    if info > 0:
+        raise LinAlgError("SVD did not converge")
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal gesdd'
+                         % -info)
+    if compute_uv:
+        return u, s, v
+    else:
+        return s
+
+
+def svdvals(a, overwrite_a=False, check_finite=True):
+    """
+    Compute singular values of a matrix.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    s : (min(M, N),) ndarray
+        The singular values, sorted in decreasing order.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    svd : Compute the full singular value decomposition of a matrix.
+    diagsvd : Construct the Sigma matrix, given the vector s.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import svdvals
+    >>> m = np.array([[1.0, 0.0],
+    ...               [2.0, 3.0],
+    ...               [1.0, 1.0],
+    ...               [0.0, 2.0],
+    ...               [1.0, 0.0]])
+    >>> svdvals(m)
+    array([ 4.28091555,  1.63516424])
+
+    We can verify the maximum singular value of `m` by computing the maximum
+    length of `m.dot(u)` over all the unit vectors `u` in the (x,y) plane.
+    We approximate "all" the unit vectors with a large sample. Because
+    of linearity, we only need the unit vectors with angles in [0, pi].
+
+    >>> t = np.linspace(0, np.pi, 2000)
+    >>> u = np.array([np.cos(t), np.sin(t)])
+    >>> np.linalg.norm(m.dot(u), axis=0).max()
+    4.2809152422538475
+
+    `p` is a projection matrix with rank 1. With exact arithmetic,
+    its singular values would be [1, 0, 0, 0].
+
+    >>> v = np.array([0.1, 0.3, 0.9, 0.3])
+    >>> p = np.outer(v, v)
+    >>> svdvals(p)
+    array([  1.00000000e+00,   2.02021698e-17,   1.56692500e-17,
+             8.15115104e-34])
+
+    The singular values of an orthogonal matrix are all 1. Here, we
+    create a random orthogonal matrix by using the `rvs()` method of
+    `scipy.stats.ortho_group`.
+
+    >>> from scipy.stats import ortho_group
+    >>> orth = ortho_group.rvs(4)
+    >>> svdvals(orth)
+    array([ 1.,  1.,  1.,  1.])
+
+    """
+    return svd(a, compute_uv=0, overwrite_a=overwrite_a,
+               check_finite=check_finite)
+
+
+def diagsvd(s, M, N):
+    """
+    Construct the sigma matrix in SVD from singular values and size M, N.
+
+    Parameters
+    ----------
+    s : (M,) or (N,) array_like
+        Singular values
+    M : int
+        Size of the matrix whose singular values are `s`.
+    N : int
+        Size of the matrix whose singular values are `s`.
+
+    Returns
+    -------
+    S : (M, N) ndarray
+        The S-matrix in the singular value decomposition
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    svdvals : Compute singular values of a matrix.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import diagsvd
+    >>> vals = np.array([1, 2, 3])  # The array representing the computed svd
+    >>> diagsvd(vals, 3, 4)
+    array([[1, 0, 0, 0],
+           [0, 2, 0, 0],
+           [0, 0, 3, 0]])
+    >>> diagsvd(vals, 4, 3)
+    array([[1, 0, 0],
+           [0, 2, 0],
+           [0, 0, 3],
+           [0, 0, 0]])
+
+    """
+    part = diag(s)
+    typ = part.dtype.char
+    MorN = len(s)
+    if MorN == M:
+        return np.hstack((part, zeros((M, N - M), dtype=typ)))
+    elif MorN == N:
+        return r_[part, zeros((M - N, N), dtype=typ)]
+    else:
+        raise ValueError("Length of s must be M or N.")
+
+
+# Orthonormal decomposition
+
+def orth(A, rcond=None):
+    """
+    Construct an orthonormal basis for the range of A using SVD
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Input array
+    rcond : float, optional
+        Relative condition number. Singular values ``s`` smaller than
+        ``rcond * max(s)`` are considered zero.
+        Default: floating point eps * max(M,N).
+
+    Returns
+    -------
+    Q : (M, K) ndarray
+        Orthonormal basis for the range of A.
+        K = effective rank of A, as determined by rcond
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    null_space : Matrix null space
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import orth
+    >>> A = np.array([[2, 0, 0], [0, 5, 0]])  # rank 2 array
+    >>> orth(A)
+    array([[0., 1.],
+           [1., 0.]])
+    >>> orth(A.T)
+    array([[0., 1.],
+           [1., 0.],
+           [0., 0.]])
+
+    """
+    u, s, vh = svd(A, full_matrices=False)
+    M, N = u.shape[0], vh.shape[1]
+    if rcond is None:
+        rcond = np.finfo(s.dtype).eps * max(M, N)
+    tol = np.amax(s, initial=0.) * rcond
+    num = np.sum(s > tol, dtype=int)
+    Q = u[:, :num]
+    return Q
+
+
+def null_space(A, rcond=None, *, overwrite_a=False, check_finite=True,
+               lapack_driver='gesdd'):
+    """
+    Construct an orthonormal basis for the null space of A using SVD
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Input array
+    rcond : float, optional
+        Relative condition number. Singular values ``s`` smaller than
+        ``rcond * max(s)`` are considered zero.
+        Default: floating point eps * max(M,N).
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : {'gesdd', 'gesvd'}, optional
+        Whether to use the more efficient divide-and-conquer approach
+        (``'gesdd'``) or general rectangular approach (``'gesvd'``)
+        to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
+        Default is ``'gesdd'``.
+
+    Returns
+    -------
+    Z : (N, K) ndarray
+        Orthonormal basis for the null space of A.
+        K = dimension of effective null space, as determined by rcond
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    orth : Matrix range
+
+    Examples
+    --------
+    1-D null space:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import null_space
+    >>> A = np.array([[1, 1], [1, 1]])
+    >>> ns = null_space(A)
+    >>> ns * np.copysign(1, ns[0,0])  # Remove the sign ambiguity of the vector
+    array([[ 0.70710678],
+           [-0.70710678]])
+
+    2-D null space:
+
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> B = rng.random((3, 5))
+    >>> Z = null_space(B)
+    >>> Z.shape
+    (5, 2)
+    >>> np.allclose(B.dot(Z), 0)
+    True
+
+    The basis vectors are orthonormal (up to rounding error):
+
+    >>> Z.T.dot(Z)
+    array([[  1.00000000e+00,   6.92087741e-17],
+           [  6.92087741e-17,   1.00000000e+00]])
+
+    """
+    u, s, vh = svd(A, full_matrices=True, overwrite_a=overwrite_a,
+                   check_finite=check_finite, lapack_driver=lapack_driver)
+    M, N = u.shape[0], vh.shape[1]
+    if rcond is None:
+        rcond = np.finfo(s.dtype).eps * max(M, N)
+    tol = np.amax(s, initial=0.) * rcond
+    num = np.sum(s > tol, dtype=int)
+    Q = vh[num:,:].T.conj()
+    return Q
+
+
+def subspace_angles(A, B):
+    r"""
+    Compute the subspace angles between two matrices.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        The first input array.
+    B : (M, K) array_like
+        The second input array.
+
+    Returns
+    -------
+    angles : ndarray, shape (min(N, K),)
+        The subspace angles between the column spaces of `A` and `B` in
+        descending order.
+
+    See Also
+    --------
+    orth
+    svd
+
+    Notes
+    -----
+    This computes the subspace angles according to the formula
+    provided in [1]_. For equivalence with MATLAB and Octave behavior,
+    use ``angles[0]``.
+
+    .. versionadded:: 1.0
+
+    References
+    ----------
+    .. [1] Knyazev A, Argentati M (2002) Principal Angles between Subspaces
+           in an A-Based Scalar Product: Algorithms and Perturbation
+           Estimates. SIAM J. Sci. Comput. 23:2008-2040.
+
+    Examples
+    --------
+    An Hadamard matrix, which has orthogonal columns, so we expect that
+    the suspace angle to be :math:`\frac{\pi}{2}`:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import hadamard, subspace_angles
+    >>> rng = np.random.default_rng()
+    >>> H = hadamard(4)
+    >>> print(H)
+    [[ 1  1  1  1]
+     [ 1 -1  1 -1]
+     [ 1  1 -1 -1]
+     [ 1 -1 -1  1]]
+    >>> np.rad2deg(subspace_angles(H[:, :2], H[:, 2:]))
+    array([ 90.,  90.])
+
+    And the subspace angle of a matrix to itself should be zero:
+
+    >>> subspace_angles(H[:, :2], H[:, :2]) <= 2 * np.finfo(float).eps
+    array([ True,  True], dtype=bool)
+
+    The angles between non-orthogonal subspaces are in between these extremes:
+
+    >>> x = rng.standard_normal((4, 3))
+    >>> np.rad2deg(subspace_angles(x[:, :2], x[:, [2]]))
+    array([ 55.832])  # random
+    """
+    # Steps here omit the U and V calculation steps from the paper
+
+    # 1. Compute orthonormal bases of column-spaces
+    A = _asarray_validated(A, check_finite=True)
+    if len(A.shape) != 2:
+        raise ValueError(f'expected 2D array, got shape {A.shape}')
+    QA = orth(A)
+    del A
+
+    B = _asarray_validated(B, check_finite=True)
+    if len(B.shape) != 2:
+        raise ValueError(f'expected 2D array, got shape {B.shape}')
+    if len(B) != len(QA):
+        raise ValueError('A and B must have the same number of rows, got '
+                         f'{QA.shape[0]} and {B.shape[0]}')
+    QB = orth(B)
+    del B
+
+    # 2. Compute SVD for cosine
+    QA_H_QB = dot(QA.T.conj(), QB)
+    sigma = svdvals(QA_H_QB)
+
+    # 3. Compute matrix B
+    if QA.shape[1] >= QB.shape[1]:
+        B = QB - dot(QA, QA_H_QB)
+    else:
+        B = QA - dot(QB, QA_H_QB.T.conj())
+    del QA, QB, QA_H_QB
+
+    # 4. Compute SVD for sine
+    mask = sigma ** 2 >= 0.5
+    if mask.any():
+        mu_arcsin = arcsin(clip(svdvals(B, overwrite_a=True), -1., 1.))
+    else:
+        mu_arcsin = 0.
+
+    # 5. Compute the principal angles
+    # with reverse ordering of sigma because smallest sigma belongs to largest
+    # angle theta
+    theta = where(mask, mu_arcsin, arccos(clip(sigma[::-1], -1., 1.)))
+    return theta
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py b/venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py
new file mode 100644
index 0000000000000000000000000000000000000000..56ddbc45c3bc47f6beb122e2acadd274ebd9be95
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py
@@ -0,0 +1,413 @@
+"""Frechet derivative of the matrix exponential."""
+import numpy as np
+import scipy.linalg
+
+__all__ = ['expm_frechet', 'expm_cond']
+
+
+def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True):
+    """
+    Frechet derivative of the matrix exponential of A in the direction E.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix of which to take the matrix exponential.
+    E : (N, N) array_like
+        Matrix direction in which to take the Frechet derivative.
+    method : str, optional
+        Choice of algorithm. Should be one of
+
+        - `SPS` (default)
+        - `blockEnlarge`
+
+    compute_expm : bool, optional
+        Whether to compute also `expm_A` in addition to `expm_frechet_AE`.
+        Default is True.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    expm_A : ndarray
+        Matrix exponential of A.
+    expm_frechet_AE : ndarray
+        Frechet derivative of the matrix exponential of A in the direction E.
+    For ``compute_expm = False``, only `expm_frechet_AE` is returned.
+
+    See Also
+    --------
+    expm : Compute the exponential of a matrix.
+
+    Notes
+    -----
+    This section describes the available implementations that can be selected
+    by the `method` parameter. The default method is *SPS*.
+
+    Method *blockEnlarge* is a naive algorithm.
+
+    Method *SPS* is Scaling-Pade-Squaring [1]_.
+    It is a sophisticated implementation which should take
+    only about 3/8 as much time as the naive implementation.
+    The asymptotics are the same.
+
+    .. versionadded:: 0.13.0
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
+           Computing the Frechet Derivative of the Matrix Exponential,
+           with an application to Condition Number Estimation.
+           SIAM Journal On Matrix Analysis and Applications.,
+           30 (4). pp. 1639-1657. ISSN 1095-7162
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+
+    >>> A = rng.standard_normal((3, 3))
+    >>> E = rng.standard_normal((3, 3))
+    >>> expm_A, expm_frechet_AE = linalg.expm_frechet(A, E)
+    >>> expm_A.shape, expm_frechet_AE.shape
+    ((3, 3), (3, 3))
+
+    Create a 6x6 matrix containing [[A, E], [0, A]]:
+
+    >>> M = np.zeros((6, 6))
+    >>> M[:3, :3] = A
+    >>> M[:3, 3:] = E
+    >>> M[3:, 3:] = A
+
+    >>> expm_M = linalg.expm(M)
+    >>> np.allclose(expm_A, expm_M[:3, :3])
+    True
+    >>> np.allclose(expm_frechet_AE, expm_M[:3, 3:])
+    True
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+        E = np.asarray_chkfinite(E)
+    else:
+        A = np.asarray(A)
+        E = np.asarray(E)
+    if A.ndim != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be a square matrix')
+    if E.ndim != 2 or E.shape[0] != E.shape[1]:
+        raise ValueError('expected E to be a square matrix')
+    if A.shape != E.shape:
+        raise ValueError('expected A and E to be the same shape')
+    if method is None:
+        method = 'SPS'
+    if method == 'SPS':
+        expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)
+    elif method == 'blockEnlarge':
+        expm_A, expm_frechet_AE = expm_frechet_block_enlarge(A, E)
+    else:
+        raise ValueError(f'Unknown implementation {method}')
+    if compute_expm:
+        return expm_A, expm_frechet_AE
+    else:
+        return expm_frechet_AE
+
+
+def expm_frechet_block_enlarge(A, E):
+    """
+    This is a helper function, mostly for testing and profiling.
+    Return expm(A), frechet(A, E)
+    """
+    n = A.shape[0]
+    M = np.vstack([
+        np.hstack([A, E]),
+        np.hstack([np.zeros_like(A), A])])
+    expm_M = scipy.linalg.expm(M)
+    return expm_M[:n, :n], expm_M[:n, n:]
+
+
+"""
+Maximal values ell_m of ||2**-s A|| such that the backward error bound
+does not exceed 2**-53.
+"""
+ell_table_61 = (
+        None,
+        # 1
+        2.11e-8,
+        3.56e-4,
+        1.08e-2,
+        6.49e-2,
+        2.00e-1,
+        4.37e-1,
+        7.83e-1,
+        1.23e0,
+        1.78e0,
+        2.42e0,
+        # 11
+        3.13e0,
+        3.90e0,
+        4.74e0,
+        5.63e0,
+        6.56e0,
+        7.52e0,
+        8.53e0,
+        9.56e0,
+        1.06e1,
+        1.17e1,
+        )
+
+
+# The b vectors and U and V are copypasted
+# from scipy.sparse.linalg.matfuncs.py.
+# M, Lu, Lv follow (6.11), (6.12), (6.13), (3.3)
+
+def _diff_pade3(A, E, ident):
+    b = (120., 60., 12., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    U = A.dot(b[3]*A2 + b[1]*ident)
+    V = b[2]*A2 + b[0]*ident
+    Lu = A.dot(b[3]*M2) + E.dot(b[3]*A2 + b[1]*ident)
+    Lv = b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade5(A, E, ident):
+    b = (30240., 15120., 3360., 420., 30., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    U = A.dot(b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[5]*M4 + b[3]*M2) +
+            E.dot(b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade7(A, E, ident):
+    b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    A6 = np.dot(A2, A4)
+    M6 = np.dot(A4, M2) + np.dot(M4, A2)
+    U = A.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[7]*M6 + b[5]*M4 + b[3]*M2) +
+            E.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[6]*M6 + b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade9(A, E, ident):
+    b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
+            2162160., 110880., 3960., 90., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    A6 = np.dot(A2, A4)
+    M6 = np.dot(A4, M2) + np.dot(M4, A2)
+    A8 = np.dot(A4, A4)
+    M8 = np.dot(A4, M4) + np.dot(M4, A4)
+    U = A.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[8]*A8 + b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[9]*M8 + b[7]*M6 + b[5]*M4 + b[3]*M2) +
+            E.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[8]*M8 + b[6]*M6 + b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def expm_frechet_algo_64(A, E):
+    n = A.shape[0]
+    s = None
+    ident = np.identity(n)
+    A_norm_1 = scipy.linalg.norm(A, 1)
+    m_pade_pairs = (
+            (3, _diff_pade3),
+            (5, _diff_pade5),
+            (7, _diff_pade7),
+            (9, _diff_pade9))
+    for m, pade in m_pade_pairs:
+        if A_norm_1 <= ell_table_61[m]:
+            U, V, Lu, Lv = pade(A, E, ident)
+            s = 0
+            break
+    if s is None:
+        # scaling
+        s = max(0, int(np.ceil(np.log2(A_norm_1 / ell_table_61[13]))))
+        A = A * 2.0**-s
+        E = E * 2.0**-s
+        # pade order 13
+        A2 = np.dot(A, A)
+        M2 = np.dot(A, E) + np.dot(E, A)
+        A4 = np.dot(A2, A2)
+        M4 = np.dot(A2, M2) + np.dot(M2, A2)
+        A6 = np.dot(A2, A4)
+        M6 = np.dot(A4, M2) + np.dot(M4, A2)
+        b = (64764752532480000., 32382376266240000., 7771770303897600.,
+                1187353796428800., 129060195264000., 10559470521600.,
+                670442572800., 33522128640., 1323241920., 40840800., 960960.,
+                16380., 182., 1.)
+        W1 = b[13]*A6 + b[11]*A4 + b[9]*A2
+        W2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident
+        Z1 = b[12]*A6 + b[10]*A4 + b[8]*A2
+        Z2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+        W = np.dot(A6, W1) + W2
+        U = np.dot(A, W)
+        V = np.dot(A6, Z1) + Z2
+        Lw1 = b[13]*M6 + b[11]*M4 + b[9]*M2
+        Lw2 = b[7]*M6 + b[5]*M4 + b[3]*M2
+        Lz1 = b[12]*M6 + b[10]*M4 + b[8]*M2
+        Lz2 = b[6]*M6 + b[4]*M4 + b[2]*M2
+        Lw = np.dot(A6, Lw1) + np.dot(M6, W1) + Lw2
+        Lu = np.dot(A, Lw) + np.dot(E, W)
+        Lv = np.dot(A6, Lz1) + np.dot(M6, Z1) + Lz2
+    # factor once and solve twice
+    lu_piv = scipy.linalg.lu_factor(-U + V)
+    R = scipy.linalg.lu_solve(lu_piv, U + V)
+    L = scipy.linalg.lu_solve(lu_piv, Lu + Lv + np.dot((Lu - Lv), R))
+    # squaring
+    for k in range(s):
+        L = np.dot(R, L) + np.dot(L, R)
+        R = np.dot(R, R)
+    return R, L
+
+
+def vec(M):
+    """
+    Stack columns of M to construct a single vector.
+
+    This is somewhat standard notation in linear algebra.
+
+    Parameters
+    ----------
+    M : 2-D array_like
+        Input matrix
+
+    Returns
+    -------
+    v : 1-D ndarray
+        Output vector
+
+    """
+    return M.T.ravel()
+
+
+def expm_frechet_kronform(A, method=None, check_finite=True):
+    """
+    Construct the Kronecker form of the Frechet derivative of expm.
+
+    Parameters
+    ----------
+    A : array_like with shape (N, N)
+        Matrix to be expm'd.
+    method : str, optional
+        Extra keyword to be passed to expm_frechet.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    K : 2-D ndarray with shape (N*N, N*N)
+        Kronecker form of the Frechet derivative of the matrix exponential.
+
+    Notes
+    -----
+    This function is used to help compute the condition number
+    of the matrix exponential.
+
+    See Also
+    --------
+    expm : Compute a matrix exponential.
+    expm_frechet : Compute the Frechet derivative of the matrix exponential.
+    expm_cond : Compute the relative condition number of the matrix exponential
+                in the Frobenius norm.
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+    else:
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    n = A.shape[0]
+    ident = np.identity(n)
+    cols = []
+    for i in range(n):
+        for j in range(n):
+            E = np.outer(ident[i], ident[j])
+            F = expm_frechet(A, E,
+                    method=method, compute_expm=False, check_finite=False)
+            cols.append(vec(F))
+    return np.vstack(cols).T
+
+
+def expm_cond(A, check_finite=True):
+    """
+    Relative condition number of the matrix exponential in the Frobenius norm.
+
+    Parameters
+    ----------
+    A : 2-D array_like
+        Square input matrix with shape (N, N).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    kappa : float
+        The relative condition number of the matrix exponential
+        in the Frobenius norm
+
+    See Also
+    --------
+    expm : Compute the exponential of a matrix.
+    expm_frechet : Compute the Frechet derivative of the matrix exponential.
+
+    Notes
+    -----
+    A faster estimate for the condition number in the 1-norm
+    has been published but is not yet implemented in SciPy.
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm_cond
+    >>> A = np.array([[-0.3, 0.2, 0.6], [0.6, 0.3, -0.1], [-0.7, 1.2, 0.9]])
+    >>> k = expm_cond(A)
+    >>> k
+    1.7787805864469866
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+    else:
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    X = scipy.linalg.expm(A)
+    K = expm_frechet_kronform(A, check_finite=False)
+
+    # The following norm choices are deliberate.
+    # The norms of A and X are Frobenius norms,
+    # and the norm of K is the induced 2-norm.
+    A_norm = scipy.linalg.norm(A, 'fro')
+    X_norm = scipy.linalg.norm(X, 'fro')
+    K_norm = scipy.linalg.norm(K, 2)
+
+    kappa = (K_norm * A_norm) / X_norm
+    return kappa
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h b/venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..676658205e41bcde69e3899e8e065c90738af246
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
@@ -0,0 +1,1521 @@
+/*
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+*/
+
+#include "npy_cblas.h"
+#include "fortran_defs.h"
+
+typedef int (*_cselect1)(npy_complex64*);
+typedef int (*_cselect2)(npy_complex64*, npy_complex64*);
+typedef int (*_dselect2)(double*, double*);
+typedef int (*_dselect3)(double*, double*, double*);
+typedef int (*_sselect2)(float*, float*);
+typedef int (*_sselect3)(float*, float*, float*);
+typedef int (*_zselect1)(npy_complex128*);
+typedef int (*_zselect2)(npy_complex128*, npy_complex128*);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void BLAS_FUNC(cbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *rwork, int *lrwork, int *info);
+void BLAS_FUNC(cbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, float *rwork, int *info);
+void BLAS_FUNC(cgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbequ)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgbequb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(cgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(cgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, npy_complex64 *v, int *ldv, int *info);
+void BLAS_FUNC(cgebal)(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, float *scale, int *info);
+void BLAS_FUNC(cgebd2)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgebrd)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgecon)(char *norm, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgeequ)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgeequb)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgees)(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cgeesx)(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cgeev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgehd2)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgehrd)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgelq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgelqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgels)(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgelsd)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(cgelss)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgelsy)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeql2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqlf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqp3)(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgeqr2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqr2p)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqrf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqrfp)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqrt)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqrt2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(cgeqrt3)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(cgerfs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgerq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgerqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgesc2)(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, float *scale);
+void BLAS_FUNC(cgesdd)(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(cgesv)(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgetc2)(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(cgetf2)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(cgetrf)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(cgetri)(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgetrs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, npy_complex64 *v, int *ldv, int *info);
+void BLAS_FUNC(cggbal)(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info);
+void BLAS_FUNC(cgges)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cggesx)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(cggev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(cggglm)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info);
+void BLAS_FUNC(cgglse)(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cggqrf)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cggrqf)(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgtcon)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgtrfs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgtsv)(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgttrf)(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info);
+void BLAS_FUNC(cgttrs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgtts2)(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(chbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info);
+void BLAS_FUNC(checon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cheequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info);
+void BLAS_FUNC(cheev)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cheevd)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chegs2)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chegst)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(chegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(cherfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chesv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cheswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(chetd2)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, int *info);
+void BLAS_FUNC(chetf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(chetrd)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(chetri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info);
+void BLAS_FUNC(chetrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chetrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(chfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c);
+void BLAS_FUNC(chgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *info);
+char BLAS_FUNC(chla_transtype)(int *trans);
+void BLAS_FUNC(chpcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(chpev)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpevd)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chpgst)(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info);
+void BLAS_FUNC(chpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chptrd)(char *uplo, int *n, npy_complex64 *ap, float *d, float *e, npy_complex64 *tau, int *info);
+void BLAS_FUNC(chptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info);
+void BLAS_FUNC(chptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(chptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(chseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(clabrd)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy);
+void BLAS_FUNC(clacgv)(int *n, npy_complex64 *x, int *incx);
+void BLAS_FUNC(clacn2)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase, int *isave);
+void BLAS_FUNC(clacon)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase);
+void BLAS_FUNC(clacp2)(char *uplo, int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clacpy)(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clacrm)(int *m, int *n, npy_complex64 *a, int *lda, float *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork);
+void BLAS_FUNC(clacrt)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s);
+void F_FUNC(cladivwrp,CLADIVWRP)(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y);
+void BLAS_FUNC(claed0)(int *qsiz, int *n, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(claed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, npy_complex64 *q, int *ldq, float *rho, int *indxq, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, npy_complex64 *work, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(claed8)(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, float *d, float *rho, int *cutpnt, float *z, float *dlamda, npy_complex64 *q2, int *ldq2, float *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, float *givnum, int *info);
+void BLAS_FUNC(claein)(int *rightv, int *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, float *rwork, float *eps3, float *smlnum, int *info);
+void BLAS_FUNC(claesy)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1);
+void BLAS_FUNC(claev2)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, float *rt1, float *rt2, float *cs1, npy_complex64 *sn1);
+void BLAS_FUNC(clag2z)(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(clags2)(int *upper, float *a1, npy_complex64 *a2, float *a3, float *b1, npy_complex64 *b2, float *b3, float *csu, npy_complex64 *snu, float *csv, npy_complex64 *snv, float *csq, npy_complex64 *snq);
+void BLAS_FUNC(clagtm)(char *trans, int *n, int *nrhs, float *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, float *beta, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clahef)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info);
+void BLAS_FUNC(clahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info);
+void BLAS_FUNC(clahr2)(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy);
+void BLAS_FUNC(claic1)(int *job, int *j, npy_complex64 *x, float *sest, npy_complex64 *w, npy_complex64 *gamma, float *sestpr, npy_complex64 *s, npy_complex64 *c);
+void BLAS_FUNC(clals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *rwork, int *info);
+void BLAS_FUNC(clalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(clalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, npy_complex64 *b, int *ldb, float *rcond, int *rank, npy_complex64 *work, float *rwork, int *iwork, int *info);
+float BLAS_FUNC(clangb)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clange)(char *norm, int *m, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clangt)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du);
+float BLAS_FUNC(clanhb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clanhe)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, float *work);
+float BLAS_FUNC(clanhp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clanhs)(char *norm, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clanht)(char *norm, int *n, float *d, npy_complex64 *e);
+float BLAS_FUNC(clansb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clansp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clansy)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clantp)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, float *work);
+void BLAS_FUNC(clapll)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *ssmin);
+void BLAS_FUNC(clapmr)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k);
+void BLAS_FUNC(clapmt)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k);
+void BLAS_FUNC(claqgb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(claqge)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(claqhb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqhe)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqhp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqp2)(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *work);
+void BLAS_FUNC(claqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf);
+void BLAS_FUNC(claqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(claqr1)(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v);
+void BLAS_FUNC(claqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork);
+void BLAS_FUNC(claqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork);
+void BLAS_FUNC(claqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(claqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh);
+void BLAS_FUNC(claqsb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqsp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqsy)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(clar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, npy_complex64 *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work);
+void BLAS_FUNC(clar2v)(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, float *c, npy_complex64 *s, int *incc);
+void BLAS_FUNC(clarcm)(int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork);
+void BLAS_FUNC(clarf)(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(clarfg)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau);
+void BLAS_FUNC(clarfgp)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau);
+void BLAS_FUNC(clarft)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt);
+void BLAS_FUNC(clarfx)(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clargv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, int *incc);
+void BLAS_FUNC(clarnv)(int *idist, int *iseed, int *n, npy_complex64 *x);
+void BLAS_FUNC(clarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *iwork, int *info);
+void BLAS_FUNC(clartg)(npy_complex64 *f, npy_complex64 *g, float *cs, npy_complex64 *sn, npy_complex64 *r);
+void BLAS_FUNC(clartv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, npy_complex64 *s, int *incc);
+void BLAS_FUNC(clarz)(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(clarzt)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt);
+void BLAS_FUNC(clascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(claset)(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda);
+void BLAS_FUNC(clasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, npy_complex64 *a, int *lda);
+void BLAS_FUNC(classq)(int *n, npy_complex64 *x, int *incx, float *scale, float *sumsq);
+void BLAS_FUNC(claswp)(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(clasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info);
+void BLAS_FUNC(clatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatdf)(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(clatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatrd)(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, float *e, npy_complex64 *tau, npy_complex64 *w, int *ldw);
+void BLAS_FUNC(clatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatrz)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work);
+void BLAS_FUNC(clauu2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(clauum)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpbcon)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbequ)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbstf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbtf2)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbtrf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpftrf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(cpftri)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(cpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpocon)(char *uplo, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpoequ)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpoequb)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cporfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cposv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpotf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cppcon)(char *uplo, int *n, npy_complex64 *ap, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cppequ)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cppsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpptrf)(char *uplo, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(cpptri)(char *uplo, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(cpptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpstf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(cpstrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(cptcon)(int *n, float *d, npy_complex64 *e, float *anorm, float *rcond, float *rwork, int *info);
+void BLAS_FUNC(cpteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(cptrfs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cptsv)(int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cptsvx)(char *fact, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpttrf)(int *n, float *d, npy_complex64 *e, int *info);
+void BLAS_FUNC(cpttrs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cptts2)(int *iuplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(crot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, npy_complex64 *s);
+void BLAS_FUNC(cspcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cspmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cspr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
+void BLAS_FUNC(csprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cspsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(csptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info);
+void BLAS_FUNC(csptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(csrscl)(int *n, float *sa, npy_complex64 *sx, int *incx);
+void BLAS_FUNC(cstedc)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(cstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(csteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(csycon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(csyconv)(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csyequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info);
+void BLAS_FUNC(csymv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(csyr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
+void BLAS_FUNC(csyrfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(csysv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(csyswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(csytf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(csytrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csytri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csytri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csytri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info);
+void BLAS_FUNC(csytrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(csytrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctftri)(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(ctfttp)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctfttr)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctgevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctgex2)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info);
+void BLAS_FUNC(ctgexc)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ctgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, float *pl, float *pr, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ctgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info);
+void BLAS_FUNC(ctgsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ctgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *info);
+void BLAS_FUNC(ctgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ctpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctpqrt)(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctpqrt2)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(ctprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(ctprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctptri)(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctpttf)(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info);
+void BLAS_FUNC(ctpttr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrexc)(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ctrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrsen)(char *job, char *compq, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, float *s, float *sep, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(ctrsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, float *rwork, int *info);
+void BLAS_FUNC(ctrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *scale, int *info);
+void BLAS_FUNC(ctrti2)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrtri)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctrttf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info);
+void BLAS_FUNC(ctrttp)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctzrzf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, float *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *info);
+void BLAS_FUNC(cung2l)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cung2r)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cungbr)(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunghr)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungl2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunglq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungql)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungqr)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungr2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cungrq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungtr)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cupgtr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info);
+void BLAS_FUNC(cupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(dbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *work, int *lwork, int *info);
+void BLAS_FUNC(dbdsdc)(char *uplo, char *compq, int *n, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, double *q, int *iq, double *work, int *iwork, int *info);
+void BLAS_FUNC(dbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(ddisna)(char *job, int *m, int *n, double *d, double *sep, int *info);
+void BLAS_FUNC(dgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *pt, int *ldpt, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dgbcon)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbequ)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgbequb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbsv)(int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbtf2)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(dgbtrf)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(dgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, double *v, int *ldv, int *info);
+void BLAS_FUNC(dgebal)(char *job, int *n, double *a, int *lda, int *ilo, int *ihi, double *scale, int *info);
+void BLAS_FUNC(dgebd2)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *info);
+void BLAS_FUNC(dgebrd)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgecon)(char *norm, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgeequ)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgeequb)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgees)(char *jobvs, char *sort, _dselect2 *select, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(dgeesx)(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(dgeev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgehd2)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgehrd)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, double *a, int *lda, double *sva, double *u, int *ldu, double *v, int *ldv, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgelq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgelqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgels)(char *trans, int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgelsd)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgelss)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgelsy)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *jpvt, double *rcond, int *rank, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dgeql2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqlf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqp3)(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqr2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqr2p)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqrf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqrfp)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqrt)(int *m, int *n, int *nb, double *a, int *lda, double *t, int *ldt, double *work, int *info);
+void BLAS_FUNC(dgeqrt2)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info);
+void BLAS_FUNC(dgeqrt3)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info);
+void BLAS_FUNC(dgerfs)(char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgerq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgerqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesc2)(int *n, double *a, int *lda, double *rhs, int *ipiv, int *jpiv, double *scale);
+void BLAS_FUNC(dgesdd)(char *jobz, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgesvd)(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, double *a, int *lda, double *sva, int *mv, double *v, int *ldv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesvx)(char *fact, char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgetc2)(int *n, double *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(dgetf2)(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dgetrf)(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dgetri)(int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgetrs)(char *trans, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, double *v, int *ldv, int *info);
+void BLAS_FUNC(dggbal)(char *job, int *n, double *a, int *lda, double *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info);
+void BLAS_FUNC(dgges)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(dggesx)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(dggev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(dggglm)(int *n, int *m, int *p, double *a, int *lda, double *b, int *ldb, double *d, double *x, double *y, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *info);
+void BLAS_FUNC(dgglse)(int *m, int *n, int *p, double *a, int *lda, double *b, int *ldb, double *c, double *d, double *x, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggqrf)(int *n, int *m, int *p, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggrqf)(int *m, int *p, int *n, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgsvj0)(char *jobv, int *m, int *n, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgsvj1)(char *jobv, int *m, int *n, int *n1, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgtcon)(char *norm, int *n, double *dl, double *d, double *du, double *du2, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgtrfs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgtsv)(int *n, int *nrhs, double *dl, double *d, double *du, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgtsvx)(char *fact, char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgttrf)(int *n, double *dl, double *d, double *du, double *du2, int *ipiv, int *info);
+void BLAS_FUNC(dgttrs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgtts2)(int *itrans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb);
+void BLAS_FUNC(dhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *t, int *ldt, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, double *h, int *ldh, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(dhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, double *z, int *ldz, double *work, int *lwork, int *info);
+int BLAS_FUNC(disnan)(double *din);
+void BLAS_FUNC(dlabad)(double *small, double *large);
+void BLAS_FUNC(dlabrd)(int *m, int *n, int *nb, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *x, int *ldx, double *y, int *ldy);
+void BLAS_FUNC(dlacn2)(int *n, double *v, double *x, int *isgn, double *est, int *kase, int *isave);
+void BLAS_FUNC(dlacon)(int *n, double *v, double *x, int *isgn, double *est, int *kase);
+void BLAS_FUNC(dlacpy)(char *uplo, int *m, int *n, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dladiv)(double *a, double *b, double *c, double *d, double *p, double *q);
+void BLAS_FUNC(dlae2)(double *a, double *b, double *c, double *rt1, double *rt2);
+void BLAS_FUNC(dlaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, double *abstol, double *reltol, double *pivmin, double *d, double *e, double *e2, int *nval, double *ab, double *c, int *mout, int *nab, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed0)(int *icompq, int *qsiz, int *n, double *d, double *e, double *q, int *ldq, double *qstore, int *ldqs, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed1)(int *n, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed2)(int *k, int *n, int *n1, double *d, double *q, int *ldq, int *indxq, double *rho, double *z, double *dlamda, double *w, double *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info);
+void BLAS_FUNC(dlaed3)(int *k, int *n, int *n1, double *d, double *q, int *ldq, double *rho, double *dlamda, double *q2, int *indx, int *ctot, double *w, double *s, int *info);
+void BLAS_FUNC(dlaed4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *dlam, int *info);
+void BLAS_FUNC(dlaed5)(int *i, double *d, double *z, double *delta, double *rho, double *dlam);
+void BLAS_FUNC(dlaed6)(int *kniter, int *orgati, double *rho, double *d, double *z, double *finit, double *tau, int *info);
+void BLAS_FUNC(dlaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed8)(int *icompq, int *k, int *n, int *qsiz, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *z, double *dlamda, double *q2, int *ldq2, double *w, int *perm, int *givptr, int *givcol, double *givnum, int *indxp, int *indx, int *info);
+void BLAS_FUNC(dlaed9)(int *k, int *kstart, int *kstop, int *n, double *d, double *q, int *ldq, double *rho, double *dlamda, double *w, double *s, int *lds, int *info);
+void BLAS_FUNC(dlaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *q, int *qptr, double *z, double *ztemp, int *info);
+void BLAS_FUNC(dlaein)(int *rightv, int *noinit, int *n, double *h, int *ldh, double *wr, double *wi, double *vr, double *vi, double *b, int *ldb, double *work, double *eps3, double *smlnum, double *bignum, int *info);
+void BLAS_FUNC(dlaev2)(double *a, double *b, double *c, double *rt1, double *rt2, double *cs1, double *sn1);
+void BLAS_FUNC(dlaexc)(int *wantq, int *n, double *t, int *ldt, double *q, int *ldq, int *j1, int *n1, int *n2, double *work, int *info);
+void BLAS_FUNC(dlag2)(double *a, int *lda, double *b, int *ldb, double *safmin, double *scale1, double *scale2, double *wr1, double *wr2, double *wi);
+void BLAS_FUNC(dlag2s)(int *m, int *n, double *a, int *lda, float *sa, int *ldsa, int *info);
+void BLAS_FUNC(dlags2)(int *upper, double *a1, double *a2, double *a3, double *b1, double *b2, double *b3, double *csu, double *snu, double *csv, double *snv, double *csq, double *snq);
+void BLAS_FUNC(dlagtf)(int *n, double *a, double *lambda_, double *b, double *c, double *tol, double *d, int *in_, int *info);
+void BLAS_FUNC(dlagtm)(char *trans, int *n, int *nrhs, double *alpha, double *dl, double *d, double *du, double *x, int *ldx, double *beta, double *b, int *ldb);
+void BLAS_FUNC(dlagts)(int *job, int *n, double *a, double *b, double *c, double *d, int *in_, double *y, double *tol, int *info);
+void BLAS_FUNC(dlagv2)(double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *csl, double *snl, double *csr, double *snr);
+void BLAS_FUNC(dlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, int *info);
+void BLAS_FUNC(dlahr2)(int *n, int *k, int *nb, double *a, int *lda, double *tau, double *t, int *ldt, double *y, int *ldy);
+void BLAS_FUNC(dlaic1)(int *job, int *j, double *x, double *sest, double *w, double *gamma, double *sestpr, double *s, double *c);
+void BLAS_FUNC(dlaln2)(int *ltrans, int *na, int *nw, double *smin, double *ca, double *a, int *lda, double *d1, double *d2, double *b, int *ldb, double *wr, double *wi, double *x, int *ldx, double *scale, double *xnorm, int *info);
+void BLAS_FUNC(dlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *info);
+void BLAS_FUNC(dlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, double *b, int *ldb, double *rcond, int *rank, double *work, int *iwork, int *info);
+double BLAS_FUNC(dlamch)(char *cmach);
+void BLAS_FUNC(dlamrg)(int *n1, int *n2, double *a, int *dtrd1, int *dtrd2, int *index_bn);
+int BLAS_FUNC(dlaneg)(int *n, double *d, double *lld, double *sigma, double *pivmin, int *r);
+double BLAS_FUNC(dlangb)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlange)(char *norm, int *m, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlangt)(char *norm, int *n, double *dl, double *d_, double *du);
+double BLAS_FUNC(dlanhs)(char *norm, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlansb)(char *norm, char *uplo, int *n, int *k, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlansf)(char *norm, char *transr, char *uplo, int *n, double *a, double *work);
+double BLAS_FUNC(dlansp)(char *norm, char *uplo, int *n, double *ap, double *work);
+double BLAS_FUNC(dlanst)(char *norm, int *n, double *d_, double *e);
+double BLAS_FUNC(dlansy)(char *norm, char *uplo, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlantb)(char *norm, char *uplo, char *diag, int *n, int *k, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlantp)(char *norm, char *uplo, char *diag, int *n, double *ap, double *work);
+double BLAS_FUNC(dlantr)(char *norm, char *uplo, char *diag, int *m, int *n, double *a, int *lda, double *work);
+void BLAS_FUNC(dlanv2)(double *a, double *b, double *c, double *d, double *rt1r, double *rt1i, double *rt2r, double *rt2i, double *cs, double *sn);
+void BLAS_FUNC(dlapll)(int *n, double *x, int *incx, double *y, int *incy, double *ssmin);
+void BLAS_FUNC(dlapmr)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k);
+void BLAS_FUNC(dlapmt)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k);
+double BLAS_FUNC(dlapy2)(double *x, double *y);
+double BLAS_FUNC(dlapy3)(double *x, double *y, double *z);
+void BLAS_FUNC(dlaqgb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(dlaqge)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(dlaqp2)(int *m, int *n, int *offset, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *work);
+void BLAS_FUNC(dlaqps)(int *m, int *n, int *offset, int *nb, int *kb, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *auxv, double *f, int *ldf);
+void BLAS_FUNC(dlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dlaqr1)(int *n, double *h, int *ldh, double *sr1, double *si1, double *sr2, double *si2, double *v);
+void BLAS_FUNC(dlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork);
+void BLAS_FUNC(dlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork);
+void BLAS_FUNC(dlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, double *sr, double *si, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, double *v, int *ldv, double *u, int *ldu, int *nv, double *wv, int *ldwv, int *nh, double *wh, int *ldwh);
+void BLAS_FUNC(dlaqsb)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqsp)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqsy)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqtr)(int *ltran, int *lreal, int *n, double *t, int *ldt, double *b, double *w, double *scale, double *x, double *work, int *info);
+void BLAS_FUNC(dlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, double *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work);
+void BLAS_FUNC(dlar2v)(int *n, double *x, double *y, double *z, int *incx, double *c, double *s, int *incc);
+void BLAS_FUNC(dlarf)(char *side, int *m, int *n, double *v, int *incv, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork);
+void BLAS_FUNC(dlarfg)(int *n, double *alpha, double *x, int *incx, double *tau);
+void BLAS_FUNC(dlarfgp)(int *n, double *alpha, double *x, int *incx, double *tau);
+void BLAS_FUNC(dlarft)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt);
+void BLAS_FUNC(dlarfx)(char *side, int *m, int *n, double *v, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlargv)(int *n, double *x, int *incx, double *y, int *incy, double *c, int *incc);
+void BLAS_FUNC(dlarnv)(int *idist, int *iseed, int *n, double *x);
+void BLAS_FUNC(dlarra)(int *n, double *d, double *e, double *e2, double *spltol, double *tnrm, int *nsplit, int *isplit, int *info);
+void BLAS_FUNC(dlarrb)(int *n, double *d, double *lld, int *ifirst, int *ilast, double *rtol1, double *rtol2, int *offset, double *w, double *wgap, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *twist, int *info);
+void BLAS_FUNC(dlarrc)(char *jobt, int *n, double *vl, double *vu, double *d, double *e, double *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info);
+void BLAS_FUNC(dlarrd)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *gers, double *reltol, double *d, double *e, double *e2, double *pivmin, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wl, double *wu, int *iblock, int *indexw, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlarre)(char *range, int *n, double *vl, double *vu, int *il, int *iu, double *d, double *e, double *e2, double *rtol1, double *rtol2, double *spltol, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *pivmin, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlarrf)(int *n, double *d, double *l, double *ld, int *clstrt, int *clend, double *w, double *wgap, double *werr, double *spdiam, double *clgapl, double *clgapr, double *pivmin, double *sigma, double *dplus, double *lplus, double *work, int *info);
+void BLAS_FUNC(dlarrj)(int *n, double *d, double *e2, int *ifirst, int *ilast, double *rtol, int *offset, double *w, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *info);
+void BLAS_FUNC(dlarrk)(int *n, int *iw, double *gl, double *gu, double *d, double *e2, double *pivmin, double *reltol, double *w, double *werr, int *info);
+void BLAS_FUNC(dlarrr)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *z, int *ldz, int *isuppz, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlartg)(double *f, double *g, double *cs, double *sn, double *r);
+void BLAS_FUNC(dlartgp)(double *f, double *g, double *cs, double *sn, double *r);
+void BLAS_FUNC(dlartgs)(double *x, double *y, double *sigma, double *cs, double *sn);
+void BLAS_FUNC(dlartv)(int *n, double *x, int *incx, double *y, int *incy, double *c, double *s, int *incc);
+void BLAS_FUNC(dlaruv)(int *iseed, int *n, double *x);
+void BLAS_FUNC(dlarz)(char *side, int *m, int *n, int *l, double *v, int *incv, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork);
+void BLAS_FUNC(dlarzt)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt);
+void BLAS_FUNC(dlas2)(double *f, double *g, double *h, double *ssmin, double *ssmax);
+void BLAS_FUNC(dlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dlasd0)(int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, int *smlsiz, int *iwork, double *work, int *info);
+void BLAS_FUNC(dlasd1)(int *nl, int *nr, int *sqre, double *d, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, int *idxq, int *iwork, double *work, int *info);
+void BLAS_FUNC(dlasd2)(int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, double *dsigma, double *u2, int *ldu2, double *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info);
+void BLAS_FUNC(dlasd3)(int *nl, int *nr, int *sqre, int *k, double *d, double *q, int *ldq, double *dsigma, double *u, int *ldu, double *u2, int *ldu2, double *vt, int *ldvt, double *vt2, int *ldvt2, int *idxc, int *ctot, double *z, int *info);
+void BLAS_FUNC(dlasd4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *sigma, double *work, int *info);
+void BLAS_FUNC(dlasd5)(int *i, double *d, double *z, double *delta, double *rho, double *dsigma, double *work);
+void BLAS_FUNC(dlasd6)(int *icompq, int *nl, int *nr, int *sqre, double *d, double *vf, double *vl, double *alpha, double *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *zw, double *vf, double *vfw, double *vl, double *vlw, double *alpha, double *beta, double *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *c, double *s, int *info);
+void BLAS_FUNC(dlasd8)(int *icompq, int *k, double *d, double *z, double *vf, double *vl, double *difl, double *difr, int *lddifr, double *dsigma, double *work, int *info);
+void BLAS_FUNC(dlasda)(int *icompq, int *smlsiz, int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dlasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub);
+void BLAS_FUNC(dlaset)(char *uplo, int *m, int *n, double *alpha, double *beta, double *a, int *lda);
+void BLAS_FUNC(dlasq1)(int *n, double *d, double *e, double *work, int *info);
+void BLAS_FUNC(dlasq2)(int *n, double *z, int *info);
+void BLAS_FUNC(dlasq3)(int *i0, int *n0, double *z, int *pp, double *dmin, double *sigma, double *desig, double *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *g, double *tau);
+void BLAS_FUNC(dlasq4)(int *i0, int *n0, double *z, int *pp, int *n0in, double *dmin, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *tau, int *ttype, double *g);
+void BLAS_FUNC(dlasq6)(int *i0, int *n0, double *z, int *pp, double *dmin, double *dmin1, double *dmin2, double *dn, double *dnm1, double *dnm2);
+void BLAS_FUNC(dlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, double *a, int *lda);
+void BLAS_FUNC(dlasrt)(char *id, int *n, double *d, int *info);
+void BLAS_FUNC(dlassq)(int *n, double *x, int *incx, double *scale, double *sumsq);
+void BLAS_FUNC(dlasv2)(double *f, double *g, double *h, double *ssmin, double *ssmax, double *snr, double *csr, double *snl, double *csl);
+void BLAS_FUNC(dlaswp)(int *n, double *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(dlasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, double *tl, int *ldtl, double *tr, int *ldtr, double *b, int *ldb, double *scale, double *x, int *ldx, double *xnorm, int *info);
+void BLAS_FUNC(dlasyf)(char *uplo, int *n, int *nb, int *kb, double *a, int *lda, int *ipiv, double *w, int *ldw, int *info);
+void BLAS_FUNC(dlat2s)(char *uplo, int *n, double *a, int *lda, float *sa, int *ldsa, int *info);
+void BLAS_FUNC(dlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, double *ab, int *ldab, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatdf)(int *ijob, int *n, double *z, int *ldz, double *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(dlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, double *ap, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatrd)(char *uplo, int *n, int *nb, double *a, int *lda, double *e, double *tau, double *w, int *ldw);
+void BLAS_FUNC(dlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, double *a, int *lda, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatrz)(int *m, int *n, int *l, double *a, int *lda, double *tau, double *work);
+void BLAS_FUNC(dlauu2)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dlauum)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dopgtr)(char *uplo, int *n, double *ap, double *tau, double *q, int *ldq, double *work, int *info);
+void BLAS_FUNC(dopmtr)(char *side, char *uplo, char *trans, int *m, int *n, double *ap, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dorbdb)(char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *phi, double *taup1, double *taup2, double *tauq1, double *tauq2, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dorg2l)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorg2r)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorgbr)(char *vect, int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorghr)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgl2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorglq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgql)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgqr)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgr2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorgrq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgtr)(char *uplo, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorm2l)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dorm2r)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorml2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormlq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormql)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormqr)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormr2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormrq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormtr)(char *side, char *uplo, char *trans, int *m, int *n, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dpbcon)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbequ)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpbrfs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbstf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbsv)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbtf2)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbtrf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbtrs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpftrf)(char *transr, char *uplo, int *n, double *a, int *info);
+void BLAS_FUNC(dpftri)(char *transr, char *uplo, int *n, double *a, int *info);
+void BLAS_FUNC(dpftrs)(char *transr, char *uplo, int *n, int *nrhs, double *a, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpocon)(char *uplo, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpoequ)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpoequb)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dporfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dposvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpotf2)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotrf)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotri)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dppcon)(char *uplo, int *n, double *ap, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dppequ)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dppsv)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dppsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpptrf)(char *uplo, int *n, double *ap, int *info);
+void BLAS_FUNC(dpptri)(char *uplo, int *n, double *ap, int *info);
+void BLAS_FUNC(dpptrs)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpstf2)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(dpstrf)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(dptcon)(int *n, double *d, double *e, double *anorm, double *rcond, double *work, int *info);
+void BLAS_FUNC(dpteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dptrfs)(int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *info);
+void BLAS_FUNC(dptsv)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info);
+void BLAS_FUNC(dptsvx)(char *fact, int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *info);
+void BLAS_FUNC(dpttrf)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dpttrs)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info);
+void BLAS_FUNC(dptts2)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb);
+void BLAS_FUNC(drscl)(int *n, double *sa, double *sx, int *incx);
+void BLAS_FUNC(dsbev)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsbevd)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, double *ab, int *ldab, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *x, int *ldx, double *work, int *info);
+void BLAS_FUNC(dsbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsbtrd)(char *vect, char *uplo, int *n, int *kd, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *work, int *info);
+void BLAS_FUNC(dsfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c);
+void BLAS_FUNC(dsgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info);
+void BLAS_FUNC(dspcon)(char *uplo, int *n, double *ap, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dspev)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dspevd)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dspevx)(char *jobz, char *range, char *uplo, int *n, double *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dspgst)(int *itype, char *uplo, int *n, double *ap, double *bp, int *info);
+void BLAS_FUNC(dspgv)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dspgvd)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *ap, double *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info);
+void BLAS_FUNC(dsprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dspsv)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dspsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsptrd)(char *uplo, int *n, double *ap, double *d, double *e, double *tau, int *info);
+void BLAS_FUNC(dsptrf)(char *uplo, int *n, double *ap, int *ipiv, int *info);
+void BLAS_FUNC(dsptri)(char *uplo, int *n, double *ap, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsptrs)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dstebz)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *abstol, double *d, double *e, int *m, int *nsplit, double *w, int *iblock, int *isplit, double *work, int *iwork, int *info);
+void BLAS_FUNC(dstedc)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, double *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsterf)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dstev)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dstevd)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstevr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstevx)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsycon)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsyconv)(char *uplo, char *way, int *n, double *a, int *lda, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsyequb)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, double *work, int *info);
+void BLAS_FUNC(dsyev)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsyevd)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsyevr)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsyevx)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsygs2)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsygst)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsygv)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsygvd)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsyrfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsysv)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsysvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dsyswapr)(char *uplo, int *n, double *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(dsytd2)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, int *info);
+void BLAS_FUNC(dsytf2)(char *uplo, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dsytrd)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytrf)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytri)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsytri2)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytri2x)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *nb, int *info);
+void BLAS_FUNC(dsytrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsytrs2)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *info);
+void BLAS_FUNC(dtbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, double *ab, int *ldab, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *a, double *b, int *ldb);
+void BLAS_FUNC(dtftri)(char *transr, char *uplo, char *diag, int *n, double *a, int *info);
+void BLAS_FUNC(dtfttp)(char *transr, char *uplo, int *n, double *arf, double *ap, int *info);
+void BLAS_FUNC(dtfttr)(char *transr, char *uplo, int *n, double *arf, double *a, int *lda, int *info);
+void BLAS_FUNC(dtgevc)(char *side, char *howmny, int *select, int *n, double *s, int *lds, double *p, int *ldp, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info);
+void BLAS_FUNC(dtgex2)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *j1, int *n1, int *n2, double *work, int *lwork, int *info);
+void BLAS_FUNC(dtgexc)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *ifst, int *ilst, double *work, int *lwork, int *info);
+void BLAS_FUNC(dtgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, int *m, double *pl, double *pr, double *dif, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dtgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, double *a, int *lda, double *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, double *u, int *ldu, double *v, int *ldv, double *q, int *ldq, double *work, int *ncycle, int *info);
+void BLAS_FUNC(dtgsna)(char *job, char *howmny, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *dif, int *mm, int *m, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dtgsy2)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *iwork, int *pq, int *info);
+void BLAS_FUNC(dtgsyl)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *dif, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dtpcon)(char *norm, char *uplo, char *diag, int *n, double *ap, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *info);
+void BLAS_FUNC(dtpqrt)(int *m, int *n, int *l, int *nb, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, double *work, int *info);
+void BLAS_FUNC(dtpqrt2)(int *m, int *n, int *l, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, int *info);
+void BLAS_FUNC(dtprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *ldwork);
+void BLAS_FUNC(dtprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtptri)(char *uplo, char *diag, int *n, double *ap, int *info);
+void BLAS_FUNC(dtptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtpttf)(char *transr, char *uplo, int *n, double *ap, double *arf, int *info);
+void BLAS_FUNC(dtpttr)(char *uplo, int *n, double *ap, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrcon)(char *norm, char *uplo, char *diag, int *n, double *a, int *lda, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtrevc)(char *side, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info);
+void BLAS_FUNC(dtrexc)(char *compq, int *n, double *t, int *ldt, double *q, int *ldq, int *ifst, int *ilst, double *work, int *info);
+void BLAS_FUNC(dtrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtrsen)(char *job, char *compq, int *select, int *n, double *t, int *ldt, double *q, int *ldq, double *wr, double *wi, int *m, double *s, double *sep, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dtrsna)(char *job, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *sep, int *mm, int *m, double *work, int *ldwork, int *iwork, int *info);
+void BLAS_FUNC(dtrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *scale, int *info);
+void BLAS_FUNC(dtrti2)(char *uplo, char *diag, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrtri)(char *uplo, char *diag, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtrttf)(char *transr, char *uplo, int *n, double *a, int *lda, double *arf, int *info);
+void BLAS_FUNC(dtrttp)(char *uplo, int *n, double *a, int *lda, double *ap, int *info);
+void BLAS_FUNC(dtzrzf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+double BLAS_FUNC(dzsum1)(int *n, npy_complex128 *cx, int *incx);
+int BLAS_FUNC(icmax1)(int *n, npy_complex64 *cx, int *incx);
+int BLAS_FUNC(ieeeck)(int *ispec, float *zero, float *one);
+int BLAS_FUNC(ilaclc)(int *m, int *n, npy_complex64 *a, int *lda);
+int BLAS_FUNC(ilaclr)(int *m, int *n, npy_complex64 *a, int *lda);
+int BLAS_FUNC(iladiag)(char *diag);
+int BLAS_FUNC(iladlc)(int *m, int *n, double *a, int *lda);
+int BLAS_FUNC(iladlr)(int *m, int *n, double *a, int *lda);
+int BLAS_FUNC(ilaprec)(char *prec);
+int BLAS_FUNC(ilaslc)(int *m, int *n, float *a, int *lda);
+int BLAS_FUNC(ilaslr)(int *m, int *n, float *a, int *lda);
+int BLAS_FUNC(ilatrans)(char *trans);
+int BLAS_FUNC(ilauplo)(char *uplo);
+void BLAS_FUNC(ilaver)(int *vers_major, int *vers_minor, int *vers_patch);
+int BLAS_FUNC(ilazlc)(int *m, int *n, npy_complex128 *a, int *lda);
+int BLAS_FUNC(ilazlr)(int *m, int *n, npy_complex128 *a, int *lda);
+int BLAS_FUNC(izmax1)(int *n, npy_complex128 *cx, int *incx);
+void BLAS_FUNC(sbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *work, int *lwork, int *info);
+void BLAS_FUNC(sbdsdc)(char *uplo, char *compq, int *n, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, float *q, int *iq, float *work, int *iwork, int *info);
+void BLAS_FUNC(sbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info);
+float BLAS_FUNC(scsum1)(int *n, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(sdisna)(char *job, int *m, int *n, float *d, float *sep, int *info);
+void BLAS_FUNC(sgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *pt, int *ldpt, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sgbcon)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbequ)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgbequb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbsv)(int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbtf2)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(sgbtrf)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(sgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, float *v, int *ldv, int *info);
+void BLAS_FUNC(sgebal)(char *job, int *n, float *a, int *lda, int *ilo, int *ihi, float *scale, int *info);
+void BLAS_FUNC(sgebd2)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *info);
+void BLAS_FUNC(sgebrd)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgecon)(char *norm, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgeequ)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgeequb)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgees)(char *jobvs, char *sort, _sselect2 *select, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(sgeesx)(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(sgeev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgehd2)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgehrd)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, float *a, int *lda, float *sva, float *u, int *ldu, float *v, int *ldv, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgelq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgelqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgels)(char *trans, int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgelsd)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgelss)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgelsy)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *jpvt, float *rcond, int *rank, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sgeql2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqlf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqp3)(int *m, int *n, float *a, int *lda, int *jpvt, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqr2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqr2p)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqrf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqrfp)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqrt)(int *m, int *n, int *nb, float *a, int *lda, float *t, int *ldt, float *work, int *info);
+void BLAS_FUNC(sgeqrt2)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info);
+void BLAS_FUNC(sgeqrt3)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info);
+void BLAS_FUNC(sgerfs)(char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgerq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgerqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesc2)(int *n, float *a, int *lda, float *rhs, int *ipiv, int *jpiv, float *scale);
+void BLAS_FUNC(sgesdd)(char *jobz, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgesv)(int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgesvd)(char *jobu, char *jobvt, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, float *a, int *lda, float *sva, int *mv, float *v, int *ldv, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesvx)(char *fact, char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgetc2)(int *n, float *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(sgetf2)(int *m, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(sgetrf)(int *m, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(sgetri)(int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgetrs)(char *trans, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, float *v, int *ldv, int *info);
+void BLAS_FUNC(sggbal)(char *job, int *n, float *a, int *lda, float *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info);
+void BLAS_FUNC(sgges)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(sggesx)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(sggev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(sggglm)(int *n, int *m, int *p, float *a, int *lda, float *b, int *ldb, float *d, float *x, float *y, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *info);
+void BLAS_FUNC(sgglse)(int *m, int *n, int *p, float *a, int *lda, float *b, int *ldb, float *c, float *d, float *x, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggqrf)(int *n, int *m, int *p, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggrqf)(int *m, int *p, int *n, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgsvj0)(char *jobv, int *m, int *n, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgsvj1)(char *jobv, int *m, int *n, int *n1, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgtcon)(char *norm, int *n, float *dl, float *d, float *du, float *du2, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgtrfs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgtsv)(int *n, int *nrhs, float *dl, float *d, float *du, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgtsvx)(char *fact, char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgttrf)(int *n, float *dl, float *d, float *du, float *du2, int *ipiv, int *info);
+void BLAS_FUNC(sgttrs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgtts2)(int *itrans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb);
+void BLAS_FUNC(shgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *t, int *ldt, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(shsein)(char *side, char *eigsrc, char *initv, int *select, int *n, float *h, int *ldh, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(shseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slabad)(float *small, float *large);
+void BLAS_FUNC(slabrd)(int *m, int *n, int *nb, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *x, int *ldx, float *y, int *ldy);
+void BLAS_FUNC(slacn2)(int *n, float *v, float *x, int *isgn, float *est, int *kase, int *isave);
+void BLAS_FUNC(slacon)(int *n, float *v, float *x, int *isgn, float *est, int *kase);
+void BLAS_FUNC(slacpy)(char *uplo, int *m, int *n, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(sladiv)(float *a, float *b, float *c, float *d, float *p, float *q);
+void BLAS_FUNC(slae2)(float *a, float *b, float *c, float *rt1, float *rt2);
+void BLAS_FUNC(slaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, float *abstol, float *reltol, float *pivmin, float *d, float *e, float *e2, int *nval, float *ab, float *c, int *mout, int *nab, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed0)(int *icompq, int *qsiz, int *n, float *d, float *e, float *q, int *ldq, float *qstore, int *ldqs, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed1)(int *n, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed2)(int *k, int *n, int *n1, float *d, float *q, int *ldq, int *indxq, float *rho, float *z, float *dlamda, float *w, float *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info);
+void BLAS_FUNC(slaed3)(int *k, int *n, int *n1, float *d, float *q, int *ldq, float *rho, float *dlamda, float *q2, int *indx, int *ctot, float *w, float *s, int *info);
+void BLAS_FUNC(slaed4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *dlam, int *info);
+void BLAS_FUNC(slaed5)(int *i, float *d, float *z, float *delta, float *rho, float *dlam);
+void BLAS_FUNC(slaed6)(int *kniter, int *orgati, float *rho, float *d, float *z, float *finit, float *tau, int *info);
+void BLAS_FUNC(slaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed8)(int *icompq, int *k, int *n, int *qsiz, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *z, float *dlamda, float *q2, int *ldq2, float *w, int *perm, int *givptr, int *givcol, float *givnum, int *indxp, int *indx, int *info);
+void BLAS_FUNC(slaed9)(int *k, int *kstart, int *kstop, int *n, float *d, float *q, int *ldq, float *rho, float *dlamda, float *w, float *s, int *lds, int *info);
+void BLAS_FUNC(slaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *q, int *qptr, float *z, float *ztemp, int *info);
+void BLAS_FUNC(slaein)(int *rightv, int *noinit, int *n, float *h, int *ldh, float *wr, float *wi, float *vr, float *vi, float *b, int *ldb, float *work, float *eps3, float *smlnum, float *bignum, int *info);
+void BLAS_FUNC(slaev2)(float *a, float *b, float *c, float *rt1, float *rt2, float *cs1, float *sn1);
+void BLAS_FUNC(slaexc)(int *wantq, int *n, float *t, int *ldt, float *q, int *ldq, int *j1, int *n1, int *n2, float *work, int *info);
+void BLAS_FUNC(slag2)(float *a, int *lda, float *b, int *ldb, float *safmin, float *scale1, float *scale2, float *wr1, float *wr2, float *wi);
+void BLAS_FUNC(slag2d)(int *m, int *n, float *sa, int *ldsa, double *a, int *lda, int *info);
+void BLAS_FUNC(slags2)(int *upper, float *a1, float *a2, float *a3, float *b1, float *b2, float *b3, float *csu, float *snu, float *csv, float *snv, float *csq, float *snq);
+void BLAS_FUNC(slagtf)(int *n, float *a, float *lambda_, float *b, float *c, float *tol, float *d, int *in_, int *info);
+void BLAS_FUNC(slagtm)(char *trans, int *n, int *nrhs, float *alpha, float *dl, float *d, float *du, float *x, int *ldx, float *beta, float *b, int *ldb);
+void BLAS_FUNC(slagts)(int *job, int *n, float *a, float *b, float *c, float *d, int *in_, float *y, float *tol, int *info);
+void BLAS_FUNC(slagv2)(float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *csl, float *snl, float *csr, float *snr);
+void BLAS_FUNC(slahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, int *info);
+void BLAS_FUNC(slahr2)(int *n, int *k, int *nb, float *a, int *lda, float *tau, float *t, int *ldt, float *y, int *ldy);
+void BLAS_FUNC(slaic1)(int *job, int *j, float *x, float *sest, float *w, float *gamma, float *sestpr, float *s, float *c);
+void BLAS_FUNC(slaln2)(int *ltrans, int *na, int *nw, float *smin, float *ca, float *a, int *lda, float *d1, float *d2, float *b, int *ldb, float *wr, float *wi, float *x, int *ldx, float *scale, float *xnorm, int *info);
+void BLAS_FUNC(slals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *info);
+void BLAS_FUNC(slalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, float *b, int *ldb, float *rcond, int *rank, float *work, int *iwork, int *info);
+float BLAS_FUNC(slamch)(char *cmach);
+void BLAS_FUNC(slamrg)(int *n1, int *n2, float *a, int *strd1, int *strd2, int *index_bn);
+float BLAS_FUNC(slangb)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slange)(char *norm, int *m, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slangt)(char *norm, int *n, float *dl, float *d, float *du);
+float BLAS_FUNC(slanhs)(char *norm, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slansb)(char *norm, char *uplo, int *n, int *k, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slansf)(char *norm, char *transr, char *uplo, int *n, float *a, float *work);
+float BLAS_FUNC(slansp)(char *norm, char *uplo, int *n, float *ap, float *work);
+float BLAS_FUNC(slanst)(char *norm, int *n, float *d, float *e);
+float BLAS_FUNC(slansy)(char *norm, char *uplo, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slantb)(char *norm, char *uplo, char *diag, int *n, int *k, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slantp)(char *norm, char *uplo, char *diag, int *n, float *ap, float *work);
+float BLAS_FUNC(slantr)(char *norm, char *uplo, char *diag, int *m, int *n, float *a, int *lda, float *work);
+void BLAS_FUNC(slanv2)(float *a, float *b, float *c, float *d, float *rt1r, float *rt1i, float *rt2r, float *rt2i, float *cs, float *sn);
+void BLAS_FUNC(slapll)(int *n, float *x, int *incx, float *y, int *incy, float *ssmin);
+void BLAS_FUNC(slapmr)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k);
+void BLAS_FUNC(slapmt)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k);
+float BLAS_FUNC(slapy2)(float *x, float *y);
+float BLAS_FUNC(slapy3)(float *x, float *y, float *z);
+void BLAS_FUNC(slaqgb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(slaqge)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(slaqp2)(int *m, int *n, int *offset, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *work);
+void BLAS_FUNC(slaqps)(int *m, int *n, int *offset, int *nb, int *kb, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *auxv, float *f, int *ldf);
+void BLAS_FUNC(slaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slaqr1)(int *n, float *h, int *ldh, float *sr1, float *si1, float *sr2, float *si2, float *v);
+void BLAS_FUNC(slaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork);
+void BLAS_FUNC(slaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork);
+void BLAS_FUNC(slaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, float *sr, float *si, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, float *v, int *ldv, float *u, int *ldu, int *nv, float *wv, int *ldwv, int *nh, float *wh, int *ldwh);
+void BLAS_FUNC(slaqsb)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqsp)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqsy)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqtr)(int *ltran, int *lreal, int *n, float *t, int *ldt, float *b, float *w, float *scale, float *x, float *work, int *info);
+void BLAS_FUNC(slar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, float *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work);
+void BLAS_FUNC(slar2v)(int *n, float *x, float *y, float *z, int *incx, float *c, float *s, int *incc);
+void BLAS_FUNC(slarf)(char *side, int *m, int *n, float *v, int *incv, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork);
+void BLAS_FUNC(slarfg)(int *n, float *alpha, float *x, int *incx, float *tau);
+void BLAS_FUNC(slarfgp)(int *n, float *alpha, float *x, int *incx, float *tau);
+void BLAS_FUNC(slarft)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt);
+void BLAS_FUNC(slarfx)(char *side, int *m, int *n, float *v, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slargv)(int *n, float *x, int *incx, float *y, int *incy, float *c, int *incc);
+void BLAS_FUNC(slarnv)(int *idist, int *iseed, int *n, float *x);
+void BLAS_FUNC(slarra)(int *n, float *d, float *e, float *e2, float *spltol, float *tnrm, int *nsplit, int *isplit, int *info);
+void BLAS_FUNC(slarrb)(int *n, float *d, float *lld, int *ifirst, int *ilast, float *rtol1, float *rtol2, int *offset, float *w, float *wgap, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *twist, int *info);
+void BLAS_FUNC(slarrc)(char *jobt, int *n, float *vl, float *vu, float *d, float *e, float *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info);
+void BLAS_FUNC(slarrd)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *gers, float *reltol, float *d, float *e, float *e2, float *pivmin, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wl, float *wu, int *iblock, int *indexw, float *work, int *iwork, int *info);
+void BLAS_FUNC(slarre)(char *range, int *n, float *vl, float *vu, int *il, int *iu, float *d, float *e, float *e2, float *rtol1, float *rtol2, float *spltol, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *pivmin, float *work, int *iwork, int *info);
+void BLAS_FUNC(slarrf)(int *n, float *d, float *l, float *ld, int *clstrt, int *clend, float *w, float *wgap, float *werr, float *spdiam, float *clgapl, float *clgapr, float *pivmin, float *sigma, float *dplus, float *lplus, float *work, int *info);
+void BLAS_FUNC(slarrj)(int *n, float *d, float *e2, int *ifirst, int *ilast, float *rtol, int *offset, float *w, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *info);
+void BLAS_FUNC(slarrk)(int *n, int *iw, float *gl, float *gu, float *d, float *e2, float *pivmin, float *reltol, float *w, float *werr, int *info);
+void BLAS_FUNC(slarrr)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(slarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *z, int *ldz, int *isuppz, float *work, int *iwork, int *info);
+void BLAS_FUNC(slartg)(float *f, float *g, float *cs, float *sn, float *r);
+void BLAS_FUNC(slartgp)(float *f, float *g, float *cs, float *sn, float *r);
+void BLAS_FUNC(slartgs)(float *x, float *y, float *sigma, float *cs, float *sn);
+void BLAS_FUNC(slartv)(int *n, float *x, int *incx, float *y, int *incy, float *c, float *s, int *incc);
+void BLAS_FUNC(slaruv)(int *iseed, int *n, float *x);
+void BLAS_FUNC(slarz)(char *side, int *m, int *n, int *l, float *v, int *incv, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork);
+void BLAS_FUNC(slarzt)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt);
+void BLAS_FUNC(slas2)(float *f, float *g, float *h, float *ssmin, float *ssmax);
+void BLAS_FUNC(slascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(slasd0)(int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, int *smlsiz, int *iwork, float *work, int *info);
+void BLAS_FUNC(slasd1)(int *nl, int *nr, int *sqre, float *d, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, int *idxq, int *iwork, float *work, int *info);
+void BLAS_FUNC(slasd2)(int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, float *dsigma, float *u2, int *ldu2, float *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info);
+void BLAS_FUNC(slasd3)(int *nl, int *nr, int *sqre, int *k, float *d, float *q, int *ldq, float *dsigma, float *u, int *ldu, float *u2, int *ldu2, float *vt, int *ldvt, float *vt2, int *ldvt2, int *idxc, int *ctot, float *z, int *info);
+void BLAS_FUNC(slasd4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *sigma, float *work, int *info);
+void BLAS_FUNC(slasd5)(int *i, float *d, float *z, float *delta, float *rho, float *dsigma, float *work);
+void BLAS_FUNC(slasd6)(int *icompq, int *nl, int *nr, int *sqre, float *d, float *vf, float *vl, float *alpha, float *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *zw, float *vf, float *vfw, float *vl, float *vlw, float *alpha, float *beta, float *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *c, float *s, int *info);
+void BLAS_FUNC(slasd8)(int *icompq, int *k, float *d, float *z, float *vf, float *vl, float *difl, float *difr, int *lddifr, float *dsigma, float *work, int *info);
+void BLAS_FUNC(slasda)(int *icompq, int *smlsiz, int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(slasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub);
+void BLAS_FUNC(slaset)(char *uplo, int *m, int *n, float *alpha, float *beta, float *a, int *lda);
+void BLAS_FUNC(slasq1)(int *n, float *d, float *e, float *work, int *info);
+void BLAS_FUNC(slasq2)(int *n, float *z, int *info);
+void BLAS_FUNC(slasq3)(int *i0, int *n0, float *z, int *pp, float *dmin, float *sigma, float *desig, float *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *g, float *tau);
+void BLAS_FUNC(slasq4)(int *i0, int *n0, float *z, int *pp, int *n0in, float *dmin, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *tau, int *ttype, float *g);
+void BLAS_FUNC(slasq6)(int *i0, int *n0, float *z, int *pp, float *dmin, float *dmin1, float *dmin2, float *dn, float *dnm1, float *dnm2);
+void BLAS_FUNC(slasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, float *a, int *lda);
+void BLAS_FUNC(slasrt)(char *id, int *n, float *d, int *info);
+void BLAS_FUNC(slassq)(int *n, float *x, int *incx, float *scale, float *sumsq);
+void BLAS_FUNC(slasv2)(float *f, float *g, float *h, float *ssmin, float *ssmax, float *snr, float *csr, float *snl, float *csl);
+void BLAS_FUNC(slaswp)(int *n, float *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(slasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, float *tl, int *ldtl, float *tr, int *ldtr, float *b, int *ldb, float *scale, float *x, int *ldx, float *xnorm, int *info);
+void BLAS_FUNC(slasyf)(char *uplo, int *n, int *nb, int *kb, float *a, int *lda, int *ipiv, float *w, int *ldw, int *info);
+void BLAS_FUNC(slatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, float *ab, int *ldab, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatdf)(int *ijob, int *n, float *z, int *ldz, float *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(slatps)(char *uplo, char *trans, char *diag, char *normin, int *n, float *ap, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatrd)(char *uplo, int *n, int *nb, float *a, int *lda, float *e, float *tau, float *w, int *ldw);
+void BLAS_FUNC(slatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, float *a, int *lda, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatrz)(int *m, int *n, int *l, float *a, int *lda, float *tau, float *work);
+void BLAS_FUNC(slauu2)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(slauum)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(sopgtr)(char *uplo, int *n, float *ap, float *tau, float *q, int *ldq, float *work, int *info);
+void BLAS_FUNC(sopmtr)(char *side, char *uplo, char *trans, int *m, int *n, float *ap, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sorbdb)(char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *phi, float *taup1, float *taup2, float *tauq1, float *tauq2, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sorg2l)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorg2r)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorgbr)(char *vect, int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorghr)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgl2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorglq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgql)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgqr)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgr2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorgrq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgtr)(char *uplo, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorm2l)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sorm2r)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorml2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormlq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormql)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormqr)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormr2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormrq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormtr)(char *side, char *uplo, char *trans, int *m, int *n, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(spbcon)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbequ)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spbrfs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbstf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbsv)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(spbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbtf2)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbtrf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbtrs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(spftrf)(char *transr, char *uplo, int *n, float *a, int *info);
+void BLAS_FUNC(spftri)(char *transr, char *uplo, int *n, float *a, int *info);
+void BLAS_FUNC(spftrs)(char *transr, char *uplo, int *n, int *nrhs, float *a, float *b, int *ldb, int *info);
+void BLAS_FUNC(spocon)(char *uplo, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(spoequ)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spoequb)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(sporfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sposv)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(sposvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spotf2)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotrf)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotri)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(sppcon)(char *uplo, int *n, float *ap, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sppequ)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sppsv)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(sppsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spptrf)(char *uplo, int *n, float *ap, int *info);
+void BLAS_FUNC(spptri)(char *uplo, int *n, float *ap, int *info);
+void BLAS_FUNC(spptrs)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(spstf2)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(spstrf)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(sptcon)(int *n, float *d, float *e, float *anorm, float *rcond, float *work, int *info);
+void BLAS_FUNC(spteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sptrfs)(int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *info);
+void BLAS_FUNC(sptsv)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info);
+void BLAS_FUNC(sptsvx)(char *fact, int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *info);
+void BLAS_FUNC(spttrf)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(spttrs)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info);
+void BLAS_FUNC(sptts2)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb);
+void BLAS_FUNC(srscl)(int *n, float *sa, float *sx, int *incx);
+void BLAS_FUNC(ssbev)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssbevd)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, float *ab, int *ldab, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *x, int *ldx, float *work, int *info);
+void BLAS_FUNC(ssbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssbtrd)(char *vect, char *uplo, int *n, int *kd, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *work, int *info);
+void BLAS_FUNC(ssfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c);
+void BLAS_FUNC(sspcon)(char *uplo, int *n, float *ap, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sspev)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sspevd)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sspevx)(char *jobz, char *range, char *uplo, int *n, float *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(sspgst)(int *itype, char *uplo, int *n, float *ap, float *bp, int *info);
+void BLAS_FUNC(sspgv)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sspgvd)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *ap, float *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sspsv)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sspsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssptrd)(char *uplo, int *n, float *ap, float *d, float *e, float *tau, int *info);
+void BLAS_FUNC(ssptrf)(char *uplo, int *n, float *ap, int *ipiv, int *info);
+void BLAS_FUNC(ssptri)(char *uplo, int *n, float *ap, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssptrs)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sstebz)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *abstol, float *d, float *e, int *m, int *nsplit, float *w, int *iblock, int *isplit, float *work, int *iwork, int *info);
+void BLAS_FUNC(sstedc)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(sstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, float *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssterf)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(sstev)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sstevd)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstevr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstevx)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssycon)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssyconv)(char *uplo, char *way, int *n, float *a, int *lda, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssyequb)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, float *work, int *info);
+void BLAS_FUNC(ssyev)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssyevd)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssyevr)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssyevx)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssygs2)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssygst)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssygv)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssygvd)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssyrfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssysv)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssysvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ssyswapr)(char *uplo, int *n, float *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(ssytd2)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, int *info);
+void BLAS_FUNC(ssytf2)(char *uplo, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(ssytrd)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytrf)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytri)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssytri2)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytri2x)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *nb, int *info);
+void BLAS_FUNC(ssytrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssytrs2)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *info);
+void BLAS_FUNC(stbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, float *ab, int *ldab, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(stbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(stbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(stfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, float *alpha, float *a, float *b, int *ldb);
+void BLAS_FUNC(stftri)(char *transr, char *uplo, char *diag, int *n, float *a, int *info);
+void BLAS_FUNC(stfttp)(char *transr, char *uplo, int *n, float *arf, float *ap, int *info);
+void BLAS_FUNC(stfttr)(char *transr, char *uplo, int *n, float *arf, float *a, int *lda, int *info);
+void BLAS_FUNC(stgevc)(char *side, char *howmny, int *select, int *n, float *s, int *lds, float *p, int *ldp, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info);
+void BLAS_FUNC(stgex2)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *j1, int *n1, int *n2, float *work, int *lwork, int *info);
+void BLAS_FUNC(stgexc)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *ifst, int *ilst, float *work, int *lwork, int *info);
+void BLAS_FUNC(stgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, int *m, float *pl, float *pr, float *dif, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(stgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, float *a, int *lda, float *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, float *u, int *ldu, float *v, int *ldv, float *q, int *ldq, float *work, int *ncycle, int *info);
+void BLAS_FUNC(stgsna)(char *job, char *howmny, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *dif, int *mm, int *m, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(stgsy2)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *iwork, int *pq, int *info);
+void BLAS_FUNC(stgsyl)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *dif, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(stpcon)(char *norm, char *uplo, char *diag, int *n, float *ap, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(stpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *info);
+void BLAS_FUNC(stpqrt)(int *m, int *n, int *l, int *nb, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, float *work, int *info);
+void BLAS_FUNC(stpqrt2)(int *m, int *n, int *l, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, int *info);
+void BLAS_FUNC(stprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *ldwork);
+void BLAS_FUNC(stprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(stptri)(char *uplo, char *diag, int *n, float *ap, int *info);
+void BLAS_FUNC(stptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(stpttf)(char *transr, char *uplo, int *n, float *ap, float *arf, int *info);
+void BLAS_FUNC(stpttr)(char *uplo, int *n, float *ap, float *a, int *lda, int *info);
+void BLAS_FUNC(strcon)(char *norm, char *uplo, char *diag, int *n, float *a, int *lda, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(strevc)(char *side, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info);
+void BLAS_FUNC(strexc)(char *compq, int *n, float *t, int *ldt, float *q, int *ldq, int *ifst, int *ilst, float *work, int *info);
+void BLAS_FUNC(strrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(strsen)(char *job, char *compq, int *select, int *n, float *t, int *ldt, float *q, int *ldq, float *wr, float *wi, int *m, float *s, float *sep, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(strsna)(char *job, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *sep, int *mm, int *m, float *work, int *ldwork, int *iwork, int *info);
+void BLAS_FUNC(strsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *scale, int *info);
+void BLAS_FUNC(strti2)(char *uplo, char *diag, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(strtri)(char *uplo, char *diag, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(strtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(strttf)(char *transr, char *uplo, int *n, float *a, int *lda, float *arf, int *info);
+void BLAS_FUNC(strttp)(char *uplo, int *n, float *a, int *lda, float *ap, int *info);
+void BLAS_FUNC(stzrzf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(xerbla_array)(char *srname_array, int *srname_len, int *info);
+void BLAS_FUNC(zbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *rwork, int *lrwork, int *info);
+void BLAS_FUNC(zbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, double *rwork, int *info);
+void BLAS_FUNC(zcgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info);
+void BLAS_FUNC(zcposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info);
+void BLAS_FUNC(zdrscl)(int *n, double *sa, npy_complex128 *sx, int *incx);
+void BLAS_FUNC(zgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbequ)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgbequb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(zgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(zgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, npy_complex128 *v, int *ldv, int *info);
+void BLAS_FUNC(zgebal)(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, double *scale, int *info);
+void BLAS_FUNC(zgebd2)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgebrd)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgecon)(char *norm, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgeequ)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgeequb)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgees)(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zgeesx)(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zgeev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgehd2)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgehrd)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgelq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgelqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgels)(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgelsd)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zgelss)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgelsy)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeql2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqlf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqp3)(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgeqr2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqr2p)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqrf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqrfp)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqrt)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqrt2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(zgeqrt3)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(zgerfs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgerq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgerqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgesc2)(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, double *scale);
+void BLAS_FUNC(zgesdd)(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgetc2)(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(zgetf2)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zgetrf)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zgetri)(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgetrs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, npy_complex128 *v, int *ldv, int *info);
+void BLAS_FUNC(zggbal)(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info);
+void BLAS_FUNC(zgges)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zggesx)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(zggev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(zggglm)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info);
+void BLAS_FUNC(zgglse)(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zggqrf)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zggrqf)(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgtcon)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgtrfs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgtsv)(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgttrf)(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info);
+void BLAS_FUNC(zgttrs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgtts2)(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zhbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhecon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zheequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info);
+void BLAS_FUNC(zheev)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zheevd)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhegs2)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhegst)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zhegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zherfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhesv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zheswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(zhetd2)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, int *info);
+void BLAS_FUNC(zhetf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zhetrd)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhetri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info);
+void BLAS_FUNC(zhetrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhetrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c);
+void BLAS_FUNC(zhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zhpcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhpev)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpevd)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhpgst)(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info);
+void BLAS_FUNC(zhpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhptrd)(char *uplo, int *n, npy_complex128 *ap, double *d, double *e, npy_complex128 *tau, int *info);
+void BLAS_FUNC(zhptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info);
+void BLAS_FUNC(zhptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(zhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlabrd)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy);
+void BLAS_FUNC(zlacgv)(int *n, npy_complex128 *x, int *incx);
+void BLAS_FUNC(zlacn2)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase, int *isave);
+void BLAS_FUNC(zlacon)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase);
+void BLAS_FUNC(zlacp2)(char *uplo, int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlacpy)(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlacrm)(int *m, int *n, npy_complex128 *a, int *lda, double *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork);
+void BLAS_FUNC(zlacrt)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s);
+void F_FUNC(zladivwrp,ZLADIVWRP)(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y);
+void BLAS_FUNC(zlaed0)(int *qsiz, int *n, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlaed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, npy_complex128 *q, int *ldq, double *rho, int *indxq, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, npy_complex128 *work, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlaed8)(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, double *d, double *rho, int *cutpnt, double *z, double *dlamda, npy_complex128 *q2, int *ldq2, double *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, double *givnum, int *info);
+void BLAS_FUNC(zlaein)(int *rightv, int *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, double *rwork, double *eps3, double *smlnum, int *info);
+void BLAS_FUNC(zlaesy)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1);
+void BLAS_FUNC(zlaev2)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, double *rt1, double *rt2, double *cs1, npy_complex128 *sn1);
+void BLAS_FUNC(zlag2c)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info);
+void BLAS_FUNC(zlags2)(int *upper, double *a1, npy_complex128 *a2, double *a3, double *b1, npy_complex128 *b2, double *b3, double *csu, npy_complex128 *snu, double *csv, npy_complex128 *snv, double *csq, npy_complex128 *snq);
+void BLAS_FUNC(zlagtm)(char *trans, int *n, int *nrhs, double *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, double *beta, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlahef)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info);
+void BLAS_FUNC(zlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info);
+void BLAS_FUNC(zlahr2)(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy);
+void BLAS_FUNC(zlaic1)(int *job, int *j, npy_complex128 *x, double *sest, npy_complex128 *w, npy_complex128 *gamma, double *sestpr, npy_complex128 *s, npy_complex128 *c);
+void BLAS_FUNC(zlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *rwork, int *info);
+void BLAS_FUNC(zlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, npy_complex128 *b, int *ldb, double *rcond, int *rank, npy_complex128 *work, double *rwork, int *iwork, int *info);
+double BLAS_FUNC(zlangb)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlange)(char *norm, int *m, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlangt)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du);
+double BLAS_FUNC(zlanhb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlanhe)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, double *work);
+double BLAS_FUNC(zlanhp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlanhs)(char *norm, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlanht)(char *norm, int *n, double *d_, npy_complex128 *e);
+double BLAS_FUNC(zlansb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlansp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlansy)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlantp)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, double *work);
+void BLAS_FUNC(zlapll)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *ssmin);
+void BLAS_FUNC(zlapmr)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k);
+void BLAS_FUNC(zlapmt)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k);
+void BLAS_FUNC(zlaqgb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(zlaqge)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(zlaqhb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqhe)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqhp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqp2)(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *work);
+void BLAS_FUNC(zlaqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf);
+void BLAS_FUNC(zlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlaqr1)(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v);
+void BLAS_FUNC(zlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork);
+void BLAS_FUNC(zlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork);
+void BLAS_FUNC(zlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh);
+void BLAS_FUNC(zlaqsb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqsp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqsy)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, npy_complex128 *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work);
+void BLAS_FUNC(zlar2v)(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, double *c, npy_complex128 *s, int *incc);
+void BLAS_FUNC(zlarcm)(int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork);
+void BLAS_FUNC(zlarf)(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(zlarfg)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau);
+void BLAS_FUNC(zlarfgp)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau);
+void BLAS_FUNC(zlarft)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt);
+void BLAS_FUNC(zlarfx)(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlargv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, int *incc);
+void BLAS_FUNC(zlarnv)(int *idist, int *iseed, int *n, npy_complex128 *x);
+void BLAS_FUNC(zlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *iwork, int *info);
+void BLAS_FUNC(zlartg)(npy_complex128 *f, npy_complex128 *g, double *cs, npy_complex128 *sn, npy_complex128 *r);
+void BLAS_FUNC(zlartv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, npy_complex128 *s, int *incc);
+void BLAS_FUNC(zlarz)(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(zlarzt)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt);
+void BLAS_FUNC(zlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zlaset)(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zlassq)(int *n, npy_complex128 *x, int *incx, double *scale, double *sumsq);
+void BLAS_FUNC(zlaswp)(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(zlasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info);
+void BLAS_FUNC(zlat2c)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info);
+void BLAS_FUNC(zlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatdf)(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(zlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatrd)(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, double *e, npy_complex128 *tau, npy_complex128 *w, int *ldw);
+void BLAS_FUNC(zlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatrz)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work);
+void BLAS_FUNC(zlauu2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zlauum)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpbcon)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbequ)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbstf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbtf2)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbtrf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpftrf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(zpftri)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(zpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpocon)(char *uplo, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpoequ)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpoequb)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zporfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpotf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zppcon)(char *uplo, int *n, npy_complex128 *ap, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zppequ)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zppsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpptrf)(char *uplo, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(zpptri)(char *uplo, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(zpptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpstf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(zpstrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(zptcon)(int *n, double *d, npy_complex128 *e, double *anorm, double *rcond, double *rwork, int *info);
+void BLAS_FUNC(zpteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(zptrfs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zptsv)(int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zptsvx)(char *fact, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpttrf)(int *n, double *d, npy_complex128 *e, int *info);
+void BLAS_FUNC(zpttrs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zptts2)(int *iuplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, npy_complex128 *s);
+void BLAS_FUNC(zspcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zspmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zspr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
+void BLAS_FUNC(zsprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zspsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zsptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info);
+void BLAS_FUNC(zsptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zstedc)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zsteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(zsycon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsyconv)(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsyequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsymv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zsyr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zsyrfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zsysv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zsyswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(zsytf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zsytrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsytri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsytri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsytri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info);
+void BLAS_FUNC(zsytrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zsytrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztftri)(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(ztfttp)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztfttr)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztgevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztgex2)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info);
+void BLAS_FUNC(ztgexc)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ztgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, double *pl, double *pr, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ztgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info);
+void BLAS_FUNC(ztgsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ztgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *info);
+void BLAS_FUNC(ztgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ztpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztpqrt)(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztpqrt2)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(ztprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(ztprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztptri)(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztpttf)(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info);
+void BLAS_FUNC(ztpttr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrexc)(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ztrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrsen)(char *job, char *compq, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, double *s, double *sep, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(ztrsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, double *rwork, int *info);
+void BLAS_FUNC(ztrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *scale, int *info);
+void BLAS_FUNC(ztrti2)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrtri)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztrttf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info);
+void BLAS_FUNC(ztrttp)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztzrzf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, double *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *info);
+void BLAS_FUNC(zung2l)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zung2r)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zungbr)(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunghr)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungl2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunglq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungql)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungqr)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungr2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zungrq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungtr)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zupgtr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info);
+void BLAS_FUNC(zupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a0ba92af71f3f3188cc73ca441187db9701b052
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
@@ -0,0 +1,867 @@
+#
+# Author: Travis Oliphant, March 2002
+#
+import warnings
+from itertools import product
+
+import numpy as np
+from numpy import (dot, diag, prod, logical_not, ravel, transpose,
+                   conjugate, absolute, amax, sign, isfinite, triu)
+
+# Local imports
+from scipy.linalg import LinAlgError, bandwidth
+from ._misc import norm
+from ._basic import solve, inv
+from ._decomp_svd import svd
+from ._decomp_schur import schur, rsf2csf
+from ._expm_frechet import expm_frechet, expm_cond
+from ._matfuncs_sqrtm import sqrtm
+from ._matfuncs_expm import pick_pade_structure, pade_UV_calc
+from ._linalg_pythran import _funm_loops  # type: ignore[import-not-found]
+
+__all__ = ['expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', 'tanhm', 'logm',
+           'funm', 'signm', 'sqrtm', 'fractional_matrix_power', 'expm_frechet',
+           'expm_cond', 'khatri_rao']
+
+eps = np.finfo('d').eps
+feps = np.finfo('f').eps
+
+_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
+
+
+###############################################################################
+# Utility functions.
+
+
+def _asarray_square(A):
+    """
+    Wraps asarray with the extra requirement that the input be a square matrix.
+
+    The motivation is that the matfuncs module has real functions that have
+    been lifted to square matrix functions.
+
+    Parameters
+    ----------
+    A : array_like
+        A square matrix.
+
+    Returns
+    -------
+    out : ndarray
+        An ndarray copy or view or other representation of A.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected square array_like input')
+    return A
+
+
+def _maybe_real(A, B, tol=None):
+    """
+    Return either B or the real part of B, depending on properties of A and B.
+
+    The motivation is that B has been computed as a complicated function of A,
+    and B may be perturbed by negligible imaginary components.
+    If A is real and B is complex with small imaginary components,
+    then return a real copy of B.  The assumption in that case would be that
+    the imaginary components of B are numerical artifacts.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input array whose type is to be checked as real vs. complex.
+    B : ndarray
+        Array to be returned, possibly without its imaginary part.
+    tol : float
+        Absolute tolerance.
+
+    Returns
+    -------
+    out : real or complex array
+        Either the input array B or only the real part of the input array B.
+
+    """
+    # Note that booleans and integers compare as real.
+    if np.isrealobj(A) and np.iscomplexobj(B):
+        if tol is None:
+            tol = {0: feps*1e3, 1: eps*1e6}[_array_precision[B.dtype.char]]
+        if np.allclose(B.imag, 0.0, atol=tol):
+            B = B.real
+    return B
+
+
+###############################################################################
+# Matrix functions.
+
+
+def fractional_matrix_power(A, t):
+    """
+    Compute the fractional power of a matrix.
+
+    Proceeds according to the discussion in section (6) of [1]_.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose fractional power to evaluate.
+    t : float
+        Fractional power.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import fractional_matrix_power
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> b = fractional_matrix_power(a, 0.5)
+    >>> b
+    array([[ 0.75592895,  1.13389342],
+           [ 0.37796447,  1.88982237]])
+    >>> np.dot(b, b)      # Verify square root
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    # This fixes some issue with imports;
+    # this function calls onenormest which is in scipy.sparse.
+    A = _asarray_square(A)
+    import scipy.linalg._matfuncs_inv_ssq
+    return scipy.linalg._matfuncs_inv_ssq._fractional_matrix_power(A, t)
+
+
+def logm(A, disp=True):
+    """
+    Compute matrix logarithm.
+
+    The matrix logarithm is the inverse of
+    expm: expm(logm(`A`)) == `A`
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose logarithm to evaluate
+    disp : bool, optional
+        Emit warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_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
+
+    .. [2] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    .. [3] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import logm, expm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> b = logm(a)
+    >>> b
+    array([[-1.02571087,  2.05142174],
+           [ 0.68380725,  1.02571087]])
+    >>> expm(b)         # Verify expm(logm(a)) returns a
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    A = np.asarray(A)  # squareness checked in `_logm`
+    # Avoid circular import ... this is OK, right?
+    import scipy.linalg._matfuncs_inv_ssq
+    F = scipy.linalg._matfuncs_inv_ssq._logm(A)
+    F = _maybe_real(A, F)
+    errtol = 1000*eps
+    # TODO use a better error approximation
+    with np.errstate(divide='ignore', invalid='ignore'):
+        errest = norm(expm(F)-A, 1) / np.asarray(norm(A, 1), dtype=A.dtype).real[()]
+    if disp:
+        if not isfinite(errest) or errest >= errtol:
+            message = f"logm result may be inaccurate, approximate err = {errest}"
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+        return F
+    else:
+        return F, errest
+
+
+def expm(A):
+    """Compute the matrix exponential of an array.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input with last two dimensions are square ``(..., n, n)``.
+
+    Returns
+    -------
+    eA : ndarray
+        The resulting matrix exponential with the same shape of ``A``
+
+    Notes
+    -----
+    Implements the algorithm given in [1], which is essentially a Pade
+    approximation with a variable order that is decided based on the array
+    data.
+
+    For input with size ``n``, the memory usage is in the worst case in the
+    order of ``8*(n**2)``. If the input data is not of single and double
+    precision of real and complex dtypes, it is copied to a new array.
+
+    For cases ``n >= 400``, the exact 1-norm computation cost, breaks even with
+    1-norm estimation and from that point on the estimation scheme given in
+    [2] is used to decide on the approximation order.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham, (2009), "A New Scaling
+           and Squaring Algorithm for the Matrix Exponential", SIAM J. Matrix
+           Anal. Appl. 31(3):970-989, :doi:`10.1137/09074721X`
+
+    .. [2] Nicholas J. Higham and Francoise Tisseur (2000), "A Block Algorithm
+           for Matrix 1-Norm Estimation, with an Application to 1-Norm
+           Pseudospectra." SIAM J. Matrix Anal. Appl. 21(4):1185-1201,
+           :doi:`10.1137/S0895479899356080`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Matrix version of the formula exp(0) = 1:
+
+    >>> expm(np.zeros((3, 2, 2)))
+    array([[[1., 0.],
+            [0., 1.]],
+    
+           [[1., 0.],
+            [0., 1.]],
+    
+           [[1., 0.],
+            [0., 1.]]])
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    a = np.asarray(A)
+    if a.size == 1 and a.ndim < 2:
+        return np.array([[np.exp(a.item())]])
+
+    if a.ndim < 2:
+        raise LinAlgError('The input array must be at least two-dimensional')
+    if a.shape[-1] != a.shape[-2]:
+        raise LinAlgError('Last 2 dimensions of the array must be square')
+
+    # Empty array
+    if min(*a.shape) == 0:
+        dtype = expm(np.eye(2, dtype=a.dtype)).dtype
+        return np.empty_like(a, dtype=dtype)
+
+    # Scalar case
+    if a.shape[-2:] == (1, 1):
+        return np.exp(a)
+
+    if not np.issubdtype(a.dtype, np.inexact):
+        a = a.astype(np.float64)
+    elif a.dtype == np.float16:
+        a = a.astype(np.float32)
+
+    # An explicit formula for 2x2 case exists (formula (2.2) in [1]). However, without
+    # Kahan's method, numerical instabilities can occur (See gh-19584). Hence removed
+    # here until we have a more stable implementation.
+
+    n = a.shape[-1]
+    eA = np.empty(a.shape, dtype=a.dtype)
+    # working memory to hold intermediate arrays
+    Am = np.empty((5, n, n), dtype=a.dtype)
+
+    # Main loop to go through the slices of an ndarray and passing to expm
+    for ind in product(*[range(x) for x in a.shape[:-2]]):
+        aw = a[ind]
+
+        lu = bandwidth(aw)
+        if not any(lu):  # a is diagonal?
+            eA[ind] = np.diag(np.exp(np.diag(aw)))
+            continue
+
+        # Generic/triangular case; copy the slice into scratch and send.
+        # Am will be mutated by pick_pade_structure
+        # If s != 0, scaled Am will be returned from pick_pade_structure.
+        Am[0, :, :] = aw
+        m, s = pick_pade_structure(Am)
+        if (m < 0):
+            raise MemoryError("scipy.linalg.expm could not allocate sufficient"
+                              " memory while trying to compute the Pade "
+                              f"structure (error code {m}).")
+        info = pade_UV_calc(Am, m)
+        if info != 0:
+            if info <= -11:
+                # We raise it from failed mallocs; negative LAPACK codes > -7
+                raise MemoryError("scipy.linalg.expm could not allocate "
+                              "sufficient memory while trying to compute the "
+                              f"exponential (error code {info}).")
+            else:
+                # LAPACK wrong argument error or exact singularity.
+                # Neither should happen.
+                raise RuntimeError("scipy.linalg.expm got an internal LAPACK "
+                                   "error during the exponential computation "
+                                   f"(error code {info})")
+        eAw = Am[0]
+
+        if s != 0:  # squaring needed
+
+            if (lu[1] == 0) or (lu[0] == 0):  # lower/upper triangular
+                # This branch implements Code Fragment 2.1 of [1]
+
+                diag_aw = np.diag(aw)
+                # einsum returns a writable view
+                np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2**(-s))
+                # super/sub diagonal
+                sd = np.diag(aw, k=-1 if lu[1] == 0 else 1)
+
+                for i in range(s-1, -1, -1):
+                    eAw = eAw @ eAw
+
+                    # diagonal
+                    np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2.**(-i))
+                    exp_sd = _exp_sinch(diag_aw * (2.**(-i))) * (sd * 2**(-i))
+                    if lu[1] == 0:  # lower
+                        np.einsum('ii->i', eAw[1:, :-1])[:] = exp_sd
+                    else:  # upper
+                        np.einsum('ii->i', eAw[:-1, 1:])[:] = exp_sd
+
+            else:  # generic
+                for _ in range(s):
+                    eAw = eAw @ eAw
+
+        # Zero out the entries from np.empty in case of triangular input
+        if (lu[0] == 0) or (lu[1] == 0):
+            eA[ind] = np.triu(eAw) if lu[0] == 0 else np.tril(eAw)
+        else:
+            eA[ind] = eAw
+
+    return eA
+
+
+def _exp_sinch(x):
+    # Higham's formula (10.42), might overflow, see GH-11839
+    lexp_diff = np.diff(np.exp(x))
+    l_diff = np.diff(x)
+    mask_z = l_diff == 0.
+    lexp_diff[~mask_z] /= l_diff[~mask_z]
+    lexp_diff[mask_z] = np.exp(x[:-1][mask_z])
+    return lexp_diff
+
+
+def cosm(A):
+    """
+    Compute the matrix cosine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array
+
+    Returns
+    -------
+    cosm : (N, N) ndarray
+        Matrix cosine of A
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    A = _asarray_square(A)
+    if np.iscomplexobj(A):
+        return 0.5*(expm(1j*A) + expm(-1j*A))
+    else:
+        return expm(1j*A).real
+
+
+def sinm(A):
+    """
+    Compute the matrix sine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    sinm : (N, N) ndarray
+        Matrix sine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    A = _asarray_square(A)
+    if np.iscomplexobj(A):
+        return -0.5j*(expm(1j*A) - expm(-1j*A))
+    else:
+        return expm(1j*A).imag
+
+
+def tanm(A):
+    """
+    Compute the matrix tangent.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    tanm : (N, N) ndarray
+        Matrix tangent of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanm, sinm, cosm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> t = tanm(a)
+    >>> t
+    array([[ -2.00876993,  -8.41880636],
+           [ -2.80626879, -10.42757629]])
+
+    Verify tanm(a) = sinm(a).dot(inv(cosm(a)))
+
+    >>> s = sinm(a)
+    >>> c = cosm(a)
+    >>> s.dot(np.linalg.inv(c))
+    array([[ -2.00876993,  -8.41880636],
+           [ -2.80626879, -10.42757629]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, solve(cosm(A), sinm(A)))
+
+
+def coshm(A):
+    """
+    Compute the hyperbolic matrix cosine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    coshm : (N, N) ndarray
+        Hyperbolic matrix cosine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> c = coshm(a)
+    >>> c
+    array([[ 11.24592233,  38.76236492],
+           [ 12.92078831,  50.00828725]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> t = tanhm(a)
+    >>> s = sinhm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, 0.5 * (expm(A) + expm(-A)))
+
+
+def sinhm(A):
+    """
+    Compute the hyperbolic matrix sine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    sinhm : (N, N) ndarray
+        Hyperbolic matrix sine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> s = sinhm(a)
+    >>> s
+    array([[ 10.57300653,  39.28826594],
+           [ 13.09608865,  49.86127247]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> t = tanhm(a)
+    >>> c = coshm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, 0.5 * (expm(A) - expm(-A)))
+
+
+def tanhm(A):
+    """
+    Compute the hyperbolic matrix tangent.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array
+
+    Returns
+    -------
+    tanhm : (N, N) ndarray
+        Hyperbolic matrix tangent of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> t = tanhm(a)
+    >>> t
+    array([[ 0.3428582 ,  0.51987926],
+           [ 0.17329309,  0.86273746]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> s = sinhm(a)
+    >>> c = coshm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, solve(coshm(A), sinhm(A)))
+
+
+def funm(A, func, disp=True):
+    """
+    Evaluate a matrix function specified by a callable.
+
+    Returns the value of matrix-valued function ``f`` at `A`. The
+    function ``f`` is an extension of the scalar-valued function `func`
+    to matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix at which to evaluate the function
+    func : callable
+        Callable object that evaluates a scalar function f.
+        Must be vectorized (eg. using vectorize).
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    funm : (N, N) ndarray
+        Value of the matrix function specified by func evaluated at `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    Notes
+    -----
+    This function implements the general algorithm based on Schur decomposition
+    (Algorithm 9.1.1. in [1]_).
+
+    If the input matrix is known to be diagonalizable, then relying on the
+    eigendecomposition is likely to be faster. For example, if your matrix is
+    Hermitian, you can do
+
+    >>> from scipy.linalg import eigh
+    >>> def funm_herm(a, func, check_finite=False):
+    ...     w, v = eigh(a, check_finite=check_finite)
+    ...     ## if you further know that your matrix is positive semidefinite,
+    ...     ## you can optionally guard against precision errors by doing
+    ...     # w = np.maximum(w, 0)
+    ...     w = func(w)
+    ...     return (v * w).dot(v.conj().T)
+
+    References
+    ----------
+    .. [1] Gene H. Golub, Charles F. van Loan, Matrix Computations 4th ed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import funm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> funm(a, lambda x: x*x)
+    array([[  4.,  15.],
+           [  5.,  19.]])
+    >>> a.dot(a)
+    array([[  4.,  15.],
+           [  5.,  19.]])
+
+    """
+    A = _asarray_square(A)
+    # Perform Shur decomposition (lapack ?gees)
+    T, Z = schur(A)
+    T, Z = rsf2csf(T, Z)
+    n, n = T.shape
+    F = diag(func(diag(T)))  # apply function to diagonal elements
+    F = F.astype(T.dtype.char)  # e.g., when F is real but T is complex
+
+    minden = abs(T[0, 0])
+
+    # implement Algorithm 11.1.1 from Golub and Van Loan
+    #                 "matrix Computations."
+    F, minden = _funm_loops(F, T, n, minden)
+
+    F = dot(dot(Z, F), transpose(conjugate(Z)))
+    F = _maybe_real(A, F)
+
+    tol = {0: feps, 1: eps}[_array_precision[F.dtype.char]]
+    if minden == 0.0:
+        minden = tol
+    err = min(1, max(tol, (tol/minden)*norm(triu(T, 1), 1)))
+    if prod(ravel(logical_not(isfinite(F))), axis=0):
+        err = np.inf
+    if disp:
+        if err > 1000*tol:
+            print("funm result may be inaccurate, approximate err =", err)
+        return F
+    else:
+        return F, err
+
+
+def signm(A, disp=True):
+    """
+    Matrix sign function.
+
+    Extension of the scalar sign(x) to matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix at which to evaluate the sign function
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    signm : (N, N) ndarray
+        Value of the sign function at `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    Examples
+    --------
+    >>> from scipy.linalg import signm, eigvals
+    >>> a = [[1,2,3], [1,2,1], [1,1,1]]
+    >>> eigvals(a)
+    array([ 4.12488542+0.j, -0.76155718+0.j,  0.63667176+0.j])
+    >>> eigvals(signm(a))
+    array([-1.+0.j,  1.+0.j,  1.+0.j])
+
+    """
+    A = _asarray_square(A)
+
+    def rounded_sign(x):
+        rx = np.real(x)
+        if rx.dtype.char == 'f':
+            c = 1e3*feps*amax(x)
+        else:
+            c = 1e3*eps*amax(x)
+        return sign((absolute(rx) > c) * rx)
+    result, errest = funm(A, rounded_sign, disp=0)
+    errtol = {0: 1e3*feps, 1: 1e3*eps}[_array_precision[result.dtype.char]]
+    if errest < errtol:
+        return result
+
+    # Handle signm of defective matrices:
+
+    # See "E.D.Denman and J.Leyva-Ramos, Appl.Math.Comp.,
+    # 8:237-250,1981" for how to improve the following (currently a
+    # rather naive) iteration process:
+
+    # a = result # sometimes iteration converges faster but where??
+
+    # Shifting to avoid zero eigenvalues. How to ensure that shifting does
+    # not change the spectrum too much?
+    vals = svd(A, compute_uv=False)
+    max_sv = np.amax(vals)
+    # min_nonzero_sv = vals[(vals>max_sv*errtol).tolist().count(1)-1]
+    # c = 0.5/min_nonzero_sv
+    c = 0.5/max_sv
+    S0 = A + c*np.identity(A.shape[0])
+    prev_errest = errest
+    for i in range(100):
+        iS0 = inv(S0)
+        S0 = 0.5*(S0 + iS0)
+        Pp = 0.5*(dot(S0, S0)+S0)
+        errest = norm(dot(Pp, Pp)-Pp, 1)
+        if errest < errtol or prev_errest == errest:
+            break
+        prev_errest = errest
+    if disp:
+        if not isfinite(errest) or errest >= errtol:
+            print("signm result may be inaccurate, approximate err =", errest)
+        return S0
+    else:
+        return S0, errest
+
+
+def khatri_rao(a, b):
+    r"""
+    Khatri-rao product
+
+    A column-wise Kronecker product of two matrices
+
+    Parameters
+    ----------
+    a : (n, k) array_like
+        Input array
+    b : (m, k) array_like
+        Input array
+
+    Returns
+    -------
+    c:  (n*m, k) ndarray
+        Khatri-rao product of `a` and `b`.
+
+    Notes
+    -----
+    The mathematical definition of the Khatri-Rao product is:
+
+    .. math::
+
+        (A_{ij}  \bigotimes B_{ij})_{ij}
+
+    which is the Kronecker product of every column of A and B, e.g.::
+
+        c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+    >>> b = np.array([[3, 4, 5], [6, 7, 8], [2, 3, 9]])
+    >>> linalg.khatri_rao(a, b)
+    array([[ 3,  8, 15],
+           [ 6, 14, 24],
+           [ 2,  6, 27],
+           [12, 20, 30],
+           [24, 35, 48],
+           [ 8, 15, 54]])
+
+    """
+    a = np.asarray(a)
+    b = np.asarray(b)
+
+    if not (a.ndim == 2 and b.ndim == 2):
+        raise ValueError("The both arrays should be 2-dimensional.")
+
+    if not a.shape[1] == b.shape[1]:
+        raise ValueError("The number of columns for both arrays "
+                         "should be equal.")
+
+    # accommodate empty arrays
+    if a.size == 0 or b.size == 0:
+        m = a.shape[0] * b.shape[0]
+        n = a.shape[1]
+        return np.empty_like(a, shape=(m, n))
+
+    # c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
+    c = a[..., :, np.newaxis, :] * b[..., np.newaxis, :, :]
+    return c.reshape((-1,) + c.shape[2:])
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..98ca455c6eb06c1e95e6e11d3db2dc346a295fde
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
@@ -0,0 +1,6 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def pick_pade_structure(a: NDArray[Any]) -> tuple[int, int]: ...
+
+def pade_UV_calc(Am: NDArray[Any], m: int) -> int: ...
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
new file mode 100644
index 0000000000000000000000000000000000000000..1decffae2e521f0a9325b873cc33b095a4e3c166
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
@@ -0,0 +1,886 @@
+"""
+Matrix functions that use Pade approximation with inverse scaling and squaring.
+
+"""
+import warnings
+
+import numpy as np
+
+from scipy.linalg._matfuncs_sqrtm import SqrtmError, _sqrtm_triu
+from scipy.linalg._decomp_schur import schur, rsf2csf
+from scipy.linalg._matfuncs import funm
+from scipy.linalg import svdvals, solve_triangular
+from scipy.sparse.linalg._interface import LinearOperator
+from scipy.sparse.linalg import onenormest
+import scipy.special
+
+
+class LogmRankWarning(UserWarning):
+    pass
+
+
+class LogmExactlySingularWarning(LogmRankWarning):
+    pass
+
+
+class LogmNearlySingularWarning(LogmRankWarning):
+    pass
+
+
+class LogmError(np.linalg.LinAlgError):
+    pass
+
+
+class FractionalMatrixPowerError(np.linalg.LinAlgError):
+    pass
+
+
+#TODO renovate or move this class when scipy operators are more mature
+class _MatrixM1PowerOperator(LinearOperator):
+    """
+    A representation of the linear operator (A - I)^p.
+    """
+
+    def __init__(self, A, p):
+        if A.ndim != 2 or A.shape[0] != A.shape[1]:
+            raise ValueError('expected A to be like a square matrix')
+        if p < 0 or p != int(p):
+            raise ValueError('expected p to be a non-negative integer')
+        self._A = A
+        self._p = p
+        self.ndim = A.ndim
+        self.shape = A.shape
+
+    def _matvec(self, x):
+        for i in range(self._p):
+            x = self._A.dot(x) - x
+        return x
+
+    def _rmatvec(self, x):
+        for i in range(self._p):
+            x = x.dot(self._A) - x
+        return x
+
+    def _matmat(self, X):
+        for i in range(self._p):
+            X = self._A.dot(X) - X
+        return X
+
+    def _adjoint(self):
+        return _MatrixM1PowerOperator(self._A.T, self._p)
+
+
+#TODO renovate or move this function when SciPy operators are more mature
+def _onenormest_m1_power(A, p,
+        t=2, itmax=5, compute_v=False, compute_w=False):
+    """
+    Efficiently estimate the 1-norm of (A - I)^p.
+
+    Parameters
+    ----------
+    A : ndarray
+        Matrix whose 1-norm of a power is to be computed.
+    p : int
+        Non-negative integer power.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+        Larger values take longer and use more memory
+        but give more accurate output.
+    itmax : int, optional
+        Use at most this many iterations.
+    compute_v : bool, optional
+        Request a norm-maximizing linear operator input vector if True.
+    compute_w : bool, optional
+        Request a norm-maximizing linear operator output vector if True.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse matrix.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+
+    """
+    return onenormest(_MatrixM1PowerOperator(A, p),
+            t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w)
+
+
+def _unwindk(z):
+    """
+    Compute the scalar unwinding number.
+
+    Uses Eq. (5.3) in [1]_, and should be equal to (z - log(exp(z)) / (2 pi i).
+    Note that this definition differs in sign from the original definition
+    in equations (5, 6) in [2]_.  The sign convention is justified in [3]_.
+
+    Parameters
+    ----------
+    z : complex
+        A complex number.
+
+    Returns
+    -------
+    unwinding_number : integer
+        The scalar unwinding number of z.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    .. [2] Robert M. Corless and David J. Jeffrey,
+           "The unwinding number." Newsletter ACM SIGSAM Bulletin
+           Volume 30, Issue 2, June 1996, Pages 28-35.
+
+    .. [3] Russell Bradford and Robert M. Corless and James H. Davenport and
+           David J. Jeffrey and Stephen M. Watt,
+           "Reasoning about the elementary functions of complex analysis"
+           Annals of Mathematics and Artificial Intelligence,
+           36: 303-318, 2002.
+
+    """
+    return int(np.ceil((z.imag - np.pi) / (2*np.pi)))
+
+
+def _briggs_helper_function(a, k):
+    """
+    Computes r = a^(1 / (2^k)) - 1.
+
+    This is algorithm (2) of [1]_.
+    The purpose is to avoid a danger of subtractive cancellation.
+    For more computational efficiency it should probably be cythonized.
+
+    Parameters
+    ----------
+    a : complex
+        A complex number.
+    k : integer
+        A nonnegative integer.
+
+    Returns
+    -------
+    r : complex
+        The value r = a^(1 / (2^k)) - 1 computed with less cancellation.
+
+    Notes
+    -----
+    The algorithm as formulated in the reference does not handle k=0 or k=1
+    correctly, so these are special-cased in this implementation.
+    This function is intended to not allow `a` to belong to the closed
+    negative real axis, but this constraint is relaxed.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy (2012)
+           "A more accurate Briggs method for the logarithm",
+           Numerical Algorithms, 59 : 393--402.
+
+    """
+    if k < 0 or int(k) != k:
+        raise ValueError('expected a nonnegative integer k')
+    if k == 0:
+        return a - 1
+    elif k == 1:
+        return np.sqrt(a) - 1
+    else:
+        k_hat = k
+        if np.angle(a) >= np.pi / 2:
+            a = np.sqrt(a)
+            k_hat = k - 1
+        z0 = a - 1
+        a = np.sqrt(a)
+        r = 1 + a
+        for j in range(1, k_hat):
+            a = np.sqrt(a)
+            r = r * (1 + a)
+        r = z0 / r
+        return r
+
+
+def _fractional_power_superdiag_entry(l1, l2, t12, p):
+    """
+    Compute a superdiagonal entry of a fractional matrix power.
+
+    This is Eq. (5.6) in [1]_.
+
+    Parameters
+    ----------
+    l1 : complex
+        A diagonal entry of the matrix.
+    l2 : complex
+        A diagonal entry of the matrix.
+    t12 : complex
+        A superdiagonal entry of the matrix.
+    p : float
+        A fractional power.
+
+    Returns
+    -------
+    f12 : complex
+        A superdiagonal entry of the fractional matrix power.
+
+    Notes
+    -----
+    Care has been taken to return a real number if possible when
+    all of the inputs are real numbers.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    if l1 == l2:
+        f12 = t12 * p * l1**(p-1)
+    elif abs(l2 - l1) > abs(l1 + l2) / 2:
+        f12 = t12 * ((l2**p) - (l1**p)) / (l2 - l1)
+    else:
+        # This is Eq. (5.5) in [1].
+        z = (l2 - l1) / (l2 + l1)
+        log_l1 = np.log(l1)
+        log_l2 = np.log(l2)
+        arctanh_z = np.arctanh(z)
+        tmp_a = t12 * np.exp((p/2)*(log_l2 + log_l1))
+        tmp_u = _unwindk(log_l2 - log_l1)
+        if tmp_u:
+            tmp_b = p * (arctanh_z + np.pi * 1j * tmp_u)
+        else:
+            tmp_b = p * arctanh_z
+        tmp_c = 2 * np.sinh(tmp_b) / (l2 - l1)
+        f12 = tmp_a * tmp_c
+    return f12
+
+
+def _logm_superdiag_entry(l1, l2, t12):
+    """
+    Compute a superdiagonal entry of a matrix logarithm.
+
+    This is like Eq. (11.28) in [1]_, except the determination of whether
+    l1 and l2 are sufficiently far apart has been modified.
+
+    Parameters
+    ----------
+    l1 : complex
+        A diagonal entry of the matrix.
+    l2 : complex
+        A diagonal entry of the matrix.
+    t12 : complex
+        A superdiagonal entry of the matrix.
+
+    Returns
+    -------
+    f12 : complex
+        A superdiagonal entry of the matrix logarithm.
+
+    Notes
+    -----
+    Care has been taken to return a real number if possible when
+    all of the inputs are real numbers.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    """
+    if l1 == l2:
+        f12 = t12 / l1
+    elif abs(l2 - l1) > abs(l1 + l2) / 2:
+        f12 = t12 * (np.log(l2) - np.log(l1)) / (l2 - l1)
+    else:
+        z = (l2 - l1) / (l2 + l1)
+        u = _unwindk(np.log(l2) - np.log(l1))
+        if u:
+            f12 = t12 * 2 * (np.arctanh(z) + np.pi*1j*u) / (l2 - l1)
+        else:
+            f12 = t12 * 2 * np.arctanh(z) / (l2 - l1)
+    return f12
+
+
+def _inverse_squaring_helper(T0, theta):
+    """
+    A helper function for inverse scaling and squaring for Pade approximation.
+
+    Parameters
+    ----------
+    T0 : (N, N) array_like upper triangular
+        Matrix involved in inverse scaling and squaring.
+    theta : indexable
+        The values theta[1] .. theta[7] must be available.
+        They represent bounds related to Pade approximation, and they depend
+        on the matrix function which is being computed.
+        For example, different values of theta are required for
+        matrix logarithm than for fractional matrix power.
+
+    Returns
+    -------
+    R : (N, N) array_like upper triangular
+        Composition of zero or more matrix square roots of T0, minus I.
+    s : non-negative integer
+        Number of square roots taken.
+    m : positive integer
+        The degree of the Pade approximation.
+
+    Notes
+    -----
+    This subroutine appears as a chunk of lines within
+    a couple of published algorithms; for example it appears
+    as lines 4--35 in algorithm (3.1) of [1]_, and
+    as lines 3--34 in algorithm (4.1) of [2]_.
+    The instances of 'goto line 38' in algorithm (3.1) of [1]_
+    probably mean 'goto line 36' and have been interpreted accordingly.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] 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
+
+    """
+    if len(T0.shape) != 2 or T0.shape[0] != T0.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = T0.shape
+    T = T0
+
+    # Find s0, the smallest s such that the spectral radius
+    # of a certain diagonal matrix is at most theta[7].
+    # Note that because theta[7] < 1,
+    # this search will not terminate if any diagonal entry of T is zero.
+    s0 = 0
+    tmp_diag = np.diag(T)
+    if np.count_nonzero(tmp_diag) != n:
+        raise Exception('Diagonal entries of T must be nonzero')
+    while np.max(np.absolute(tmp_diag - 1), initial=0.) > theta[7]:
+        tmp_diag = np.sqrt(tmp_diag)
+        s0 += 1
+
+    # Take matrix square roots of T.
+    for i in range(s0):
+        T = _sqrtm_triu(T)
+
+    # Flow control in this section is a little odd.
+    # This is because I am translating algorithm descriptions
+    # which have GOTOs in the publication.
+    s = s0
+    k = 0
+    d2 = _onenormest_m1_power(T, 2) ** (1/2)
+    d3 = _onenormest_m1_power(T, 3) ** (1/3)
+    a2 = max(d2, d3)
+    m = None
+    for i in (1, 2):
+        if a2 <= theta[i]:
+            m = i
+            break
+    while m is None:
+        if s > s0:
+            d3 = _onenormest_m1_power(T, 3) ** (1/3)
+        d4 = _onenormest_m1_power(T, 4) ** (1/4)
+        a3 = max(d3, d4)
+        if a3 <= theta[7]:
+            j1 = min(i for i in (3, 4, 5, 6, 7) if a3 <= theta[i])
+            if j1 <= 6:
+                m = j1
+                break
+            elif a3 / 2 <= theta[5] and k < 2:
+                k += 1
+                T = _sqrtm_triu(T)
+                s += 1
+                continue
+        d5 = _onenormest_m1_power(T, 5) ** (1/5)
+        a4 = max(d4, d5)
+        eta = min(a3, a4)
+        for i in (6, 7):
+            if eta <= theta[i]:
+                m = i
+                break
+        if m is not None:
+            break
+        T = _sqrtm_triu(T)
+        s += 1
+
+    # The subtraction of the identity is redundant here,
+    # because the diagonal will be replaced for improved numerical accuracy,
+    # but this formulation should help clarify the meaning of R.
+    R = T - np.identity(n)
+
+    # Replace the diagonal and first superdiagonal of T0^(1/(2^s)) - I
+    # using formulas that have less subtractive cancellation.
+    # Skip this step if the principal branch
+    # does not exist at T0; this happens when a diagonal entry of T0
+    # is negative with imaginary part 0.
+    has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
+    if has_principal_branch:
+        for j in range(n):
+            a = T0[j, j]
+            r = _briggs_helper_function(a, s)
+            R[j, j] = r
+        p = np.exp2(-s)
+        for j in range(n-1):
+            l1 = T0[j, j]
+            l2 = T0[j+1, j+1]
+            t12 = T0[j, j+1]
+            f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
+            R[j, j+1] = f12
+
+    # Return the T-I matrix, the number of square roots, and the Pade degree.
+    if not np.array_equal(R, np.triu(R)):
+        raise Exception('R is not upper triangular')
+    return R, s, m
+
+
+def _fractional_power_pade_constant(i, t):
+    # A helper function for matrix fractional power.
+    if i < 1:
+        raise ValueError('expected a positive integer i')
+    if not (-1 < t < 1):
+        raise ValueError('expected -1 < t < 1')
+    if i == 1:
+        return -t
+    elif i % 2 == 0:
+        j = i // 2
+        return (-j + t) / (2 * (2*j - 1))
+    elif i % 2 == 1:
+        j = (i - 1) // 2
+        return (-j - t) / (2 * (2*j + 1))
+    else:
+        raise Exception(f'unnexpected value of i, i = {i}')
+
+
+def _fractional_power_pade(R, t, m):
+    """
+    Evaluate the Pade approximation of a fractional matrix power.
+
+    Evaluate the degree-m Pade approximation of R
+    to the fractional matrix power t using the continued fraction
+    in bottom-up fashion using algorithm (4.1) in [1]_.
+
+    Parameters
+    ----------
+    R : (N, N) array_like
+        Upper triangular matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+    m : positive integer
+        Degree of Pade approximation.
+
+    Returns
+    -------
+    U : (N, N) array_like
+        The degree-m Pade approximation of R to the fractional power t.
+        This matrix will be upper triangular.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    if m < 1 or int(m) != m:
+        raise ValueError('expected a positive integer m')
+    if not (-1 < t < 1):
+        raise ValueError('expected -1 < t < 1')
+    R = np.asarray(R)
+    if len(R.shape) != 2 or R.shape[0] != R.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = R.shape
+    ident = np.identity(n)
+    Y = R * _fractional_power_pade_constant(2*m, t)
+    for j in range(2*m - 1, 0, -1):
+        rhs = R * _fractional_power_pade_constant(j, t)
+        Y = solve_triangular(ident + Y, rhs)
+    U = ident + Y
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _remainder_matrix_power_triu(T, t):
+    """
+    Compute a fractional power of an upper triangular matrix.
+
+    The fractional power is restricted to fractions -1 < t < 1.
+    This uses algorithm (3.1) of [1]_.
+    The Pade approximation itself uses algorithm (4.1) of [2]_.
+
+    Parameters
+    ----------
+    T : (N, N) array_like
+        Upper triangular matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    m_to_theta = {
+            1: 1.51e-5,
+            2: 2.24e-3,
+            3: 1.88e-2,
+            4: 6.04e-2,
+            5: 1.24e-1,
+            6: 2.00e-1,
+            7: 2.79e-1,
+            }
+    n, n = T.shape
+    T0 = T
+    T0_diag = np.diag(T0)
+    if np.array_equal(T0, np.diag(T0_diag)):
+        U = np.diag(T0_diag ** t)
+    else:
+        R, s, m = _inverse_squaring_helper(T0, m_to_theta)
+
+        # Evaluate the Pade approximation.
+        # Note that this function expects the negative of the matrix
+        # returned by the inverse squaring helper.
+        U = _fractional_power_pade(-R, t, m)
+
+        # Undo the inverse scaling and squaring.
+        # Be less clever about this
+        # if the principal branch does not exist at T0;
+        # this happens when a diagonal entry of T0
+        # is negative with imaginary part 0.
+        eivals = np.diag(T0)
+        has_principal_branch = all(x.real > 0 or x.imag != 0 for x in eivals)
+        for i in range(s, -1, -1):
+            if i < s:
+                U = U.dot(U)
+            else:
+                if has_principal_branch:
+                    p = t * np.exp2(-i)
+                    U[np.diag_indices(n)] = T0_diag ** p
+                    for j in range(n-1):
+                        l1 = T0[j, j]
+                        l2 = T0[j+1, j+1]
+                        t12 = T0[j, j+1]
+                        f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
+                        U[j, j+1] = f12
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _remainder_matrix_power(A, t):
+    """
+    Compute the fractional power of a matrix, for fractions -1 < t < 1.
+
+    This uses algorithm (3.1) of [1]_.
+    The Pade approximation itself uses algorithm (4.1) of [2]_.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    # This code block is copied from numpy.matrix_power().
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('input must be a square array')
+
+    # Get the number of rows and columns.
+    n, n = A.shape
+
+    # Triangularize the matrix if necessary,
+    # attempting to preserve dtype if possible.
+    if np.array_equal(A, np.triu(A)):
+        Z = None
+        T = A
+    else:
+        if np.isrealobj(A):
+            T, Z = schur(A)
+            if not np.array_equal(T, np.triu(T)):
+                T, Z = rsf2csf(T, Z)
+        else:
+            T, Z = schur(A, output='complex')
+
+    # Zeros on the diagonal of the triangular matrix are forbidden,
+    # because the inverse scaling and squaring cannot deal with it.
+    T_diag = np.diag(T)
+    if np.count_nonzero(T_diag) != n:
+        raise FractionalMatrixPowerError(
+                'cannot use inverse scaling and squaring to find '
+                'the fractional matrix power of a singular matrix')
+
+    # If the triangular matrix is real and has a negative
+    # entry on the diagonal, then force the matrix to be complex.
+    if np.isrealobj(T) and np.min(T_diag) < 0:
+        T = T.astype(complex)
+
+    # Get the fractional power of the triangular matrix,
+    # and de-triangularize it if necessary.
+    U = _remainder_matrix_power_triu(T, t)
+    if Z is not None:
+        ZH = np.conjugate(Z).T
+        return Z.dot(U).dot(ZH)
+    else:
+        return U
+
+
+def _fractional_matrix_power(A, p):
+    """
+    Compute the fractional power of a matrix.
+
+    See the fractional_matrix_power docstring in matfuncs.py for more info.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+    if p == int(p):
+        return np.linalg.matrix_power(A, int(p))
+    # Compute singular values.
+    s = svdvals(A)
+    # Inverse scaling and squaring cannot deal with a singular matrix,
+    # because the process of repeatedly taking square roots
+    # would not converge to the identity matrix.
+    if s[-1]:
+        # Compute the condition number relative to matrix inversion,
+        # and use this to decide between floor(p) and ceil(p).
+        k2 = s[0] / s[-1]
+        p1 = p - np.floor(p)
+        p2 = p - np.ceil(p)
+        if p1 * k2 ** (1 - p1) <= -p2 * k2:
+            a = int(np.floor(p))
+            b = p1
+        else:
+            a = int(np.ceil(p))
+            b = p2
+        try:
+            R = _remainder_matrix_power(A, b)
+            Q = np.linalg.matrix_power(A, a)
+            return Q.dot(R)
+        except np.linalg.LinAlgError:
+            pass
+    # If p is negative then we are going to give up.
+    # If p is non-negative then we can fall back to generic funm.
+    if p < 0:
+        X = np.empty_like(A)
+        X.fill(np.nan)
+        return X
+    else:
+        p1 = p - np.floor(p)
+        a = int(np.floor(p))
+        b = p1
+        R, info = funm(A, lambda x: pow(x, b), disp=False)
+        Q = np.linalg.matrix_power(A, a)
+        return Q.dot(R)
+
+
+def _logm_triu(T):
+    """
+    Compute matrix logarithm of an upper triangular matrix.
+
+    The matrix logarithm is the inverse of
+    expm: expm(logm(`T`)) == `T`
+
+    Parameters
+    ----------
+    T : (N, N) array_like
+        Upper triangular matrix whose logarithm to evaluate
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `T`
+
+    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
+
+    .. [2] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    .. [3] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    T = np.asarray(T)
+    if len(T.shape) != 2 or T.shape[0] != T.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = T.shape
+
+    # Construct T0 with the appropriate type,
+    # depending on the dtype and the spectrum of T.
+    T_diag = np.diag(T)
+    keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0
+    if keep_it_real:
+        T0 = T
+    else:
+        T0 = T.astype(complex)
+
+    # Define bounds given in Table (2.1).
+    theta = (None,
+            1.59e-5, 2.31e-3, 1.94e-2, 6.21e-2,
+            1.28e-1, 2.06e-1, 2.88e-1, 3.67e-1,
+            4.39e-1, 5.03e-1, 5.60e-1, 6.09e-1,
+            6.52e-1, 6.89e-1, 7.21e-1, 7.49e-1)
+
+    R, s, m = _inverse_squaring_helper(T0, theta)
+
+    # Evaluate U = 2**s r_m(T - I) using the partial fraction expansion (1.1).
+    # This requires the nodes and weights
+    # corresponding to degree-m Gauss-Legendre quadrature.
+    # These quadrature arrays need to be transformed from the [-1, 1] interval
+    # to the [0, 1] interval.
+    nodes, weights = scipy.special.p_roots(m)
+    nodes = nodes.real
+    if nodes.shape != (m,) or weights.shape != (m,):
+        raise Exception('internal error')
+    nodes = 0.5 + 0.5 * nodes
+    weights = 0.5 * weights
+    ident = np.identity(n)
+    U = np.zeros_like(R)
+    for alpha, beta in zip(weights, nodes):
+        U += solve_triangular(ident + beta*R, alpha*R)
+    U *= np.exp2(s)
+
+    # Skip this step if the principal branch
+    # does not exist at T0; this happens when a diagonal entry of T0
+    # is negative with imaginary part 0.
+    has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
+    if has_principal_branch:
+
+        # Recompute diagonal entries of U.
+        U[np.diag_indices(n)] = np.log(np.diag(T0))
+
+        # Recompute superdiagonal entries of U.
+        # This indexing of this code should be renovated
+        # when newer np.diagonal() becomes available.
+        for i in range(n-1):
+            l1 = T0[i, i]
+            l2 = T0[i+1, i+1]
+            t12 = T0[i, i+1]
+            U[i, i+1] = _logm_superdiag_entry(l1, l2, t12)
+
+    # Return the logm of the upper triangular matrix.
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _logm_force_nonsingular_triangular_matrix(T, inplace=False):
+    # The input matrix should be upper triangular.
+    # The eps is ad hoc and is not meant to be machine precision.
+    tri_eps = 1e-20
+    abs_diag = np.absolute(np.diag(T))
+    if np.any(abs_diag == 0):
+        exact_singularity_msg = 'The logm input matrix is exactly singular.'
+        warnings.warn(exact_singularity_msg, LogmExactlySingularWarning, stacklevel=3)
+        if not inplace:
+            T = T.copy()
+        n = T.shape[0]
+        for i in range(n):
+            if not T[i, i]:
+                T[i, i] = tri_eps
+    elif np.any(abs_diag < tri_eps):
+        near_singularity_msg = 'The logm input matrix may be nearly singular.'
+        warnings.warn(near_singularity_msg, LogmNearlySingularWarning, stacklevel=3)
+    return T
+
+
+def _logm(A):
+    """
+    Compute the matrix logarithm.
+
+    See the logm docstring in matfuncs.py for more info.
+
+    Notes
+    -----
+    In this function we look at triangular matrices that are similar
+    to the input matrix. If any diagonal entry of such a triangular matrix
+    is exactly zero then the original matrix is singular.
+    The matrix logarithm does not exist for such matrices,
+    but in such cases we will pretend that the diagonal entries that are zero
+    are actually slightly positive by an ad-hoc amount, in the interest
+    of returning something more useful than NaN. This will cause a warning.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    # If the input matrix dtype is integer then copy to a float dtype matrix.
+    if issubclass(A.dtype.type, np.integer):
+        A = np.asarray(A, dtype=float)
+
+    keep_it_real = np.isrealobj(A)
+    try:
+        if np.array_equal(A, np.triu(A)):
+            A = _logm_force_nonsingular_triangular_matrix(A)
+            if np.min(np.diag(A), initial=0.) < 0:
+                A = A.astype(complex)
+            return _logm_triu(A)
+        else:
+            if keep_it_real:
+                T, Z = schur(A)
+                if not np.array_equal(T, np.triu(T)):
+                    T, Z = rsf2csf(T, Z)
+            else:
+                T, Z = schur(A, output='complex')
+            T = _logm_force_nonsingular_triangular_matrix(T, inplace=True)
+            U = _logm_triu(T)
+            ZH = np.conjugate(Z).T
+            return Z.dot(U).dot(ZH)
+    except (SqrtmError, LogmError):
+        X = np.empty_like(A)
+        X.fill(np.nan)
+        return X
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7da6ced474ee3db548a24ecc08d7e2627f0d7a4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
@@ -0,0 +1,205 @@
+"""
+Matrix square root for general matrices and for upper triangular matrices.
+
+This module exists to avoid cyclic imports.
+
+"""
+__all__ = ['sqrtm']
+
+import numpy as np
+
+from scipy._lib._util import _asarray_validated
+
+# Local imports
+from ._misc import norm
+from .lapack import ztrsyl, dtrsyl
+from ._decomp_schur import schur, rsf2csf
+from ._basic import _ensure_dtype_cdsz
+
+
+
+class SqrtmError(np.linalg.LinAlgError):
+    pass
+
+
+from ._matfuncs_sqrtm_triu import within_block_loop  # noqa: E402
+
+
+def _sqrtm_triu(T, blocksize=64):
+    """
+    Matrix square root of an upper triangular matrix.
+
+    This is a helper function for `sqrtm` and `logm`.
+
+    Parameters
+    ----------
+    T : (N, N) array_like upper triangular
+        Matrix whose square root to evaluate
+    blocksize : int, optional
+        If the blocksize is not degenerate with respect to the
+        size of the input array, then use a blocked algorithm. (Default: 64)
+
+    Returns
+    -------
+    sqrtm : (N, N) ndarray
+        Value of the sqrt function at `T`
+
+    References
+    ----------
+    .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
+           "Blocked Schur Algorithms for Computing the Matrix Square Root,
+           Lecture Notes in Computer Science, 7782. pp. 171-182.
+
+    """
+    T_diag = np.diag(T)
+    keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0
+
+    # Cast to complex as necessary + ensure double precision
+    if not keep_it_real:
+        T = np.asarray(T, dtype=np.complex128, order="C")
+        T_diag = np.asarray(T_diag, dtype=np.complex128)
+    else:
+        T = np.asarray(T, dtype=np.float64, order="C")
+        T_diag = np.asarray(T_diag, dtype=np.float64)
+
+    R = np.diag(np.sqrt(T_diag))
+
+    # Compute the number of blocks to use; use at least one block.
+    n, n = T.shape
+    nblocks = max(n // blocksize, 1)
+
+    # Compute the smaller of the two sizes of blocks that
+    # we will actually use, and compute the number of large blocks.
+    bsmall, nlarge = divmod(n, nblocks)
+    blarge = bsmall + 1
+    nsmall = nblocks - nlarge
+    if nsmall * bsmall + nlarge * blarge != n:
+        raise Exception('internal inconsistency')
+
+    # Define the index range covered by each block.
+    start_stop_pairs = []
+    start = 0
+    for count, size in ((nsmall, bsmall), (nlarge, blarge)):
+        for i in range(count):
+            start_stop_pairs.append((start, start + size))
+            start += size
+
+    # Within-block interactions (Cythonized)
+    try:
+        within_block_loop(R, T, start_stop_pairs, nblocks)
+    except RuntimeError as e:
+        raise SqrtmError(*e.args) from e
+
+    # Between-block interactions (Cython would give no significant speedup)
+    for j in range(nblocks):
+        jstart, jstop = start_stop_pairs[j]
+        for i in range(j-1, -1, -1):
+            istart, istop = start_stop_pairs[i]
+            S = T[istart:istop, jstart:jstop]
+            if j - i > 1:
+                S = S - R[istart:istop, istop:jstart].dot(R[istop:jstart,
+                                                            jstart:jstop])
+
+            # Invoke LAPACK.
+            # For more details, see the solve_sylvester implementation
+            # and the fortran dtrsyl and ztrsyl docs.
+            Rii = R[istart:istop, istart:istop]
+            Rjj = R[jstart:jstop, jstart:jstop]
+            if keep_it_real:
+                x, scale, info = dtrsyl(Rii, Rjj, S)
+            else:
+                x, scale, info = ztrsyl(Rii, Rjj, S)
+            R[istart:istop, jstart:jstop] = x * scale
+
+    # Return the matrix square root.
+    return R
+
+
+def sqrtm(A, disp=True, blocksize=64):
+    """
+    Matrix square root.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose square root to evaluate
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+    blocksize : integer, optional
+        If the blocksize is not degenerate with respect to the
+        size of the input array, then use a blocked algorithm. (Default: 64)
+
+    Returns
+    -------
+    sqrtm : (N, N) ndarray
+        Value of the sqrt function at `A`. The dtype is float or complex.
+        The precision (data size) is determined based on the precision of
+        input `A`.
+
+    errest : float
+        (if disp == False)
+
+        Frobenius norm of the estimated error, ||err||_F / ||A||_F
+
+    References
+    ----------
+    .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
+           "Blocked Schur Algorithms for Computing the Matrix Square Root,
+           Lecture Notes in Computer Science, 7782. pp. 171-182.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import sqrtm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> r = sqrtm(a)
+    >>> r
+    array([[ 0.75592895,  1.13389342],
+           [ 0.37796447,  1.88982237]])
+    >>> r.dot(r)
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    A = _asarray_validated(A, check_finite=True, as_inexact=True)
+    if len(A.shape) != 2:
+        raise ValueError("Non-matrix input to matrix function.")
+    if blocksize < 1:
+        raise ValueError("The blocksize should be at least 1.")
+    A, = _ensure_dtype_cdsz(A)
+    keep_it_real = np.isrealobj(A)
+    if keep_it_real:
+        T, Z = schur(A)
+        d0 = np.diagonal(T)
+        d1 = np.diagonal(T, -1)
+        eps = np.finfo(T.dtype).eps
+        needs_conversion = abs(d1) > eps * (abs(d0[1:]) + abs(d0[:-1]))
+        if needs_conversion.any():
+            T, Z = rsf2csf(T, Z)
+    else:
+        T, Z = schur(A, output='complex')
+    failflag = False
+    try:
+        R = _sqrtm_triu(T, blocksize=blocksize)
+        ZH = np.conjugate(Z).T
+        X = Z.dot(R).dot(ZH)
+        dtype = np.result_type(A.dtype, 1j if np.iscomplexobj(X) else 1)
+        X = X.astype(dtype, copy=False)
+    except SqrtmError:
+        failflag = True
+        X = np.empty_like(A)
+        X.fill(np.nan)
+
+    if disp:
+        if failflag:
+            print("Failed to find a square root.")
+        return X
+    else:
+        try:
+            arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
+        except ValueError:
+            # NaNs in matrix
+            arg2 = np.inf
+
+        return X, arg2
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_misc.py b/venv/lib/python3.10/site-packages/scipy/linalg/_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..27cd442080c8569417694a8a612fe0a461c1a2ca
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_misc.py
@@ -0,0 +1,191 @@
+import numpy as np
+from numpy.linalg import LinAlgError
+from .blas import get_blas_funcs
+from .lapack import get_lapack_funcs
+
+__all__ = ['LinAlgError', 'LinAlgWarning', 'norm']
+
+
+class LinAlgWarning(RuntimeWarning):
+    """
+    The warning emitted when a linear algebra related operation is close
+    to fail conditions of the algorithm or loss of accuracy is expected.
+    """
+    pass
+
+
+def norm(a, ord=None, axis=None, keepdims=False, check_finite=True):
+    """
+    Matrix or vector norm.
+
+    This function is able to return one of eight different matrix norms,
+    or one of an infinite number of vector norms (described below), depending
+    on the value of the ``ord`` parameter. For tensors with rank different from
+    1 or 2, only `ord=None` is supported.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array. If `axis` is None, `a` must be 1-D or 2-D, unless `ord`
+        is None. If both `axis` and `ord` are None, the 2-norm of
+        ``a.ravel`` will be returned.
+    ord : {int, inf, -inf, 'fro', 'nuc', None}, optional
+        Order of the norm (see table under ``Notes``). inf means NumPy's
+        `inf` object.
+    axis : {int, 2-tuple of ints, None}, optional
+        If `axis` is an integer, it specifies the axis of `a` along which to
+        compute the vector norms. If `axis` is a 2-tuple, it specifies the
+        axes that hold 2-D matrices, and the matrix norms of these matrices
+        are computed. If `axis` is None then either a vector norm (when `a`
+        is 1-D) or a matrix norm (when `a` is 2-D) is returned.
+    keepdims : bool, optional
+        If this is set to True, the axes which are normed over are left in the
+        result as dimensions with size one. With this option the result will
+        broadcast correctly against the original `a`.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    n : float or ndarray
+        Norm of the matrix or vector(s).
+
+    Notes
+    -----
+    For values of ``ord <= 0``, the result is, strictly speaking, not a
+    mathematical 'norm', but it may still be useful for various numerical
+    purposes.
+
+    The following norms can be calculated:
+
+    =====  ============================  ==========================
+    ord    norm for matrices             norm for vectors
+    =====  ============================  ==========================
+    None   Frobenius norm                2-norm
+    'fro'  Frobenius norm                --
+    'nuc'  nuclear norm                  --
+    inf    max(sum(abs(a), axis=1))      max(abs(a))
+    -inf   min(sum(abs(a), axis=1))      min(abs(a))
+    0      --                            sum(a != 0)
+    1      max(sum(abs(a), axis=0))      as below
+    -1     min(sum(abs(a), axis=0))      as below
+    2      2-norm (largest sing. value)  as below
+    -2     smallest singular value       as below
+    other  --                            sum(abs(a)**ord)**(1./ord)
+    =====  ============================  ==========================
+
+    The Frobenius norm is given by [1]_:
+
+        :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
+
+    The nuclear norm is the sum of the singular values.
+
+    Both the Frobenius and nuclear norm orders are only defined for
+    matrices.
+
+    References
+    ----------
+    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
+           Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import norm
+    >>> a = np.arange(9) - 4.0
+    >>> a
+    array([-4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+    >>> b = a.reshape((3, 3))
+    >>> b
+    array([[-4., -3., -2.],
+           [-1.,  0.,  1.],
+           [ 2.,  3.,  4.]])
+
+    >>> norm(a)
+    7.745966692414834
+    >>> norm(b)
+    7.745966692414834
+    >>> norm(b, 'fro')
+    7.745966692414834
+    >>> norm(a, np.inf)
+    4.0
+    >>> norm(b, np.inf)
+    9.0
+    >>> norm(a, -np.inf)
+    0.0
+    >>> norm(b, -np.inf)
+    2.0
+
+    >>> norm(a, 1)
+    20.0
+    >>> norm(b, 1)
+    7.0
+    >>> norm(a, -1)
+    -4.6566128774142013e-010
+    >>> norm(b, -1)
+    6.0
+    >>> norm(a, 2)
+    7.745966692414834
+    >>> norm(b, 2)
+    7.3484692283495345
+
+    >>> norm(a, -2)
+    0.0
+    >>> norm(b, -2)
+    1.8570331885190563e-016
+    >>> norm(a, 3)
+    5.8480354764257312
+    >>> norm(a, -3)
+    0.0
+
+    """
+    # Differs from numpy only in non-finite handling and the use of blas.
+    if check_finite:
+        a = np.asarray_chkfinite(a)
+    else:
+        a = np.asarray(a)
+
+    if a.size and a.dtype.char in 'fdFD' and axis is None and not keepdims:
+
+        if ord in (None, 2) and (a.ndim == 1):
+            # use blas for fast and stable euclidean norm
+            nrm2 = get_blas_funcs('nrm2', dtype=a.dtype, ilp64='preferred')
+            return nrm2(a)
+
+        if a.ndim == 2:
+            # Use lapack for a couple fast matrix norms.
+            # For some reason the *lange frobenius norm is slow.
+            lange_args = None
+            # Make sure this works if the user uses the axis keywords
+            # to apply the norm to the transpose.
+            if ord == 1:
+                if np.isfortran(a):
+                    lange_args = '1', a
+                elif np.isfortran(a.T):
+                    lange_args = 'i', a.T
+            elif ord == np.inf:
+                if np.isfortran(a):
+                    lange_args = 'i', a
+                elif np.isfortran(a.T):
+                    lange_args = '1', a.T
+            if lange_args:
+                lange = get_lapack_funcs('lange', dtype=a.dtype, ilp64='preferred')
+                return lange(*lange_args)
+
+    # fall back to numpy in every other case
+    return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims)
+
+
+def _datacopied(arr, original):
+    """
+    Strict check for `arr` not sharing any data with `original`,
+    under the assumption that arr = asarray(original)
+
+    """
+    if arr is original:
+        return False
+    if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
+        return False
+    return arr.base is None
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py b/venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d68f0b737ead5d581095ad32a34ae88d153264c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
@@ -0,0 +1,111 @@
+"""
+Solve the orthogonal Procrustes problem.
+
+"""
+import numpy as np
+from ._decomp_svd import svd
+
+
+__all__ = ['orthogonal_procrustes']
+
+
+def orthogonal_procrustes(A, B, check_finite=True):
+    """
+    Compute the matrix solution of the orthogonal (or unitary) Procrustes problem.
+
+    Given matrices `A` and `B` of the same shape, find an orthogonal (or unitary in
+    the case of complex input) matrix `R` that most closely maps `A` to `B` using the
+    algorithm given in [1]_.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Matrix to be mapped.
+    B : (M, N) array_like
+        Target matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    R : (N, N) ndarray
+        The matrix solution of the orthogonal Procrustes problem.
+        Minimizes the Frobenius norm of ``(A @ R) - B``, subject to
+        ``R.conj().T @ R = I``.
+    scale : float
+        Sum of the singular values of ``A.conj().T @ B``.
+
+    Raises
+    ------
+    ValueError
+        If the input array shapes don't match or if check_finite is True and
+        the arrays contain Inf or NaN.
+
+    Notes
+    -----
+    Note that unlike higher level Procrustes analyses of spatial data, this
+    function only uses orthogonal transformations like rotations and
+    reflections, and it does not use scaling or translation.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Peter H. Schonemann, "A generalized solution of the orthogonal
+           Procrustes problem", Psychometrica -- Vol. 31, No. 1, March, 1966.
+           :doi:`10.1007/BF02289451`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import orthogonal_procrustes
+    >>> A = np.array([[ 2,  0,  1], [-2,  0,  0]])
+
+    Flip the order of columns and check for the anti-diagonal mapping
+
+    >>> R, sca = orthogonal_procrustes(A, np.fliplr(A))
+    >>> R
+    array([[-5.34384992e-17,  0.00000000e+00,  1.00000000e+00],
+           [ 0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
+           [ 1.00000000e+00,  0.00000000e+00, -7.85941422e-17]])
+    >>> sca
+    9.0
+
+    As an example of the unitary Procrustes problem, generate a
+    random complex matrix ``A``, a random unitary matrix ``Q``,
+    and their product ``B``.
+
+    >>> shape = (4, 4)
+    >>> rng = np.random.default_rng(589234981235)
+    >>> A = rng.random(shape) + rng.random(shape)*1j
+    >>> Q = rng.random(shape) + rng.random(shape)*1j
+    >>> Q, _ = np.linalg.qr(Q)
+    >>> B = A @ Q
+
+    `orthogonal_procrustes` recovers the unitary matrix ``Q``
+    from ``A`` and ``B``.
+
+    >>> R, _ = orthogonal_procrustes(A, B)
+    >>> np.allclose(R, Q)
+    True
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+        B = np.asarray_chkfinite(B)
+    else:
+        A = np.asanyarray(A)
+        B = np.asanyarray(B)
+    if A.ndim != 2:
+        raise ValueError(f'expected ndim to be 2, but observed {A.ndim}')
+    if A.shape != B.shape:
+        raise ValueError(f'the shapes of A and B differ ({A.shape} vs {B.shape})')
+    # Be clever with transposes, with the intention to save memory.
+    # The conjugate has no effect for real inputs, but gives the correct solution
+    # for complex inputs.
+    u, w, vt = svd((B.T @ np.conjugate(A)).T)
+    R = u @ vt
+    scale = w.sum()
+    return R, scale
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py b/venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..589172827f528799203cb3e93a4a013e07dc5ff8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py
@@ -0,0 +1,178 @@
+""" Sketching-based Matrix Computations """
+
+# Author: Jordi Montes 
+# August 28, 2017
+
+import numpy as np
+
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng)
+from scipy.sparse import csc_matrix
+
+__all__ = ['clarkson_woodruff_transform']
+
+
+def cwt_matrix(n_rows, n_columns, rng=None):
+    r"""
+    Generate a matrix S which represents a Clarkson-Woodruff transform.
+
+    Given the desired size of matrix, the method returns a matrix S of size
+    (n_rows, n_columns) where each column has all the entries set to 0
+    except for one position which has been randomly set to +1 or -1 with
+    equal probability.
+
+    Parameters
+    ----------
+    n_rows : int
+        Number of rows of S
+    n_columns : int
+        Number of columns of S
+    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``.
+
+
+    Returns
+    -------
+    S : (n_rows, n_columns) csc_matrix
+        The returned matrix has ``n_columns`` nonzero entries.
+
+    Notes
+    -----
+    Given a matrix A, with probability at least 9/10,
+    .. math:: \|SA\| = (1 \pm \epsilon)\|A\|
+    Where the error epsilon is related to the size of S.
+    """
+    rng = check_random_state(rng)
+    rows = rng_integers(rng, 0, n_rows, n_columns)
+    cols = np.arange(n_columns+1)
+    signs = rng.choice([1, -1], n_columns)
+    S = csc_matrix((signs, rows, cols), shape=(n_rows, n_columns))
+    return S
+
+
+@_transition_to_rng("seed", position_num=2)
+def clarkson_woodruff_transform(input_matrix, sketch_size, rng=None):
+    r"""
+    Applies a Clarkson-Woodruff Transform/sketch to the input matrix.
+
+    Given an input_matrix ``A`` of size ``(n, d)``, compute a matrix ``A'`` of
+    size (sketch_size, d) so that
+
+    .. math:: \|Ax\| \approx \|A'x\|
+
+    with high probability via the Clarkson-Woodruff Transform, otherwise
+    known as the CountSketch matrix.
+
+    Parameters
+    ----------
+    input_matrix : array_like
+        Input matrix, of shape ``(n, d)``.
+    sketch_size : int
+        Number of rows for the sketch.
+    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``.
+
+    Returns
+    -------
+    A' : array_like
+        Sketch of the input matrix ``A``, of size ``(sketch_size, d)``.
+
+    Notes
+    -----
+    To make the statement
+
+    .. math:: \|Ax\| \approx \|A'x\|
+
+    precise, observe the following result which is adapted from the
+    proof of Theorem 14 of [2]_ via Markov's Inequality. If we have
+    a sketch size ``sketch_size=k`` which is at least
+
+    .. math:: k \geq \frac{2}{\epsilon^2\delta}
+
+    Then for any fixed vector ``x``,
+
+    .. math:: \|Ax\| = (1\pm\epsilon)\|A'x\|
+
+    with probability at least one minus delta.
+
+    This implementation takes advantage of sparsity: computing
+    a sketch takes time proportional to ``A.nnz``. Data ``A`` which
+    is in ``scipy.sparse.csc_matrix`` format gives the quickest
+    computation time for sparse input.
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> from scipy import sparse
+    >>> rng = np.random.default_rng()
+    >>> n_rows, n_columns, density, sketch_n_rows = 15000, 100, 0.01, 200
+    >>> A = sparse.rand(n_rows, n_columns, density=density, format='csc')
+    >>> B = sparse.rand(n_rows, n_columns, density=density, format='csr')
+    >>> C = sparse.rand(n_rows, n_columns, density=density, format='coo')
+    >>> D = rng.standard_normal((n_rows, n_columns))
+    >>> SA = linalg.clarkson_woodruff_transform(A, sketch_n_rows) # fastest
+    >>> SB = linalg.clarkson_woodruff_transform(B, sketch_n_rows) # fast
+    >>> SC = linalg.clarkson_woodruff_transform(C, sketch_n_rows) # slower
+    >>> SD = linalg.clarkson_woodruff_transform(D, sketch_n_rows) # slowest
+
+    That said, this method does perform well on dense inputs, just slower
+    on a relative scale.
+
+    References
+    ----------
+    .. [1] Kenneth L. Clarkson and David P. Woodruff. Low rank approximation
+           and regression in input sparsity time. In STOC, 2013.
+    .. [2] David P. Woodruff. Sketching as a tool for numerical linear algebra.
+           In Foundations and Trends in Theoretical Computer Science, 2014.
+
+    Examples
+    --------
+    Create a big dense matrix ``A`` for the example:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> n_rows, n_columns  = 15000, 100
+    >>> rng = np.random.default_rng()
+    >>> A = rng.standard_normal((n_rows, n_columns))
+
+    Apply the transform to create a new matrix with 200 rows:
+
+    >>> sketch_n_rows = 200
+    >>> sketch = linalg.clarkson_woodruff_transform(A, sketch_n_rows, seed=rng)
+    >>> sketch.shape
+    (200, 100)
+
+    Now with high probability, the true norm is close to the sketched norm
+    in absolute value.
+
+    >>> linalg.norm(A)
+    1224.2812927123198
+    >>> linalg.norm(sketch)
+    1226.518328407333
+
+    Similarly, applying our sketch preserves the solution to a linear
+    regression of :math:`\min \|Ax - b\|`.
+
+    >>> b = rng.standard_normal(n_rows)
+    >>> x = linalg.lstsq(A, b)[0]
+    >>> Ab = np.hstack((A, b.reshape(-1, 1)))
+    >>> SAb = linalg.clarkson_woodruff_transform(Ab, sketch_n_rows, seed=rng)
+    >>> SA, Sb = SAb[:, :-1], SAb[:, -1]
+    >>> x_sketched = linalg.lstsq(SA, Sb)[0]
+
+    As with the matrix norm example, ``linalg.norm(A @ x - b)`` is close
+    to ``linalg.norm(A @ x_sketched - b)`` with high probability.
+
+    >>> linalg.norm(A @ x - b)
+    122.83242365433877
+    >>> linalg.norm(A @ x_sketched - b)
+    166.58473879945151
+
+    """
+    S = cwt_matrix(sketch_size, input_matrix.shape[0], rng=rng)
+    return S.dot(input_matrix)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py b/venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..60a6a73e7bf9cce36090137c0e884d3ed22c55a8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py
@@ -0,0 +1,857 @@
+"""Matrix equation solver routines"""
+# Author: Jeffrey Armstrong 
+# February 24, 2012
+
+# Modified: Chad Fulton 
+# June 19, 2014
+
+# Modified: Ilhan Polat 
+# September 13, 2016
+
+import warnings
+import numpy as np
+from numpy.linalg import inv, LinAlgError, norm, cond, svd
+
+from ._basic import solve, solve_triangular, matrix_balance
+from .lapack import get_lapack_funcs
+from ._decomp_schur import schur
+from ._decomp_lu import lu
+from ._decomp_qr import qr
+from ._decomp_qz import ordqz
+from ._decomp import _asarray_validated
+from ._special_matrices import block_diag
+
+__all__ = ['solve_sylvester',
+           'solve_continuous_lyapunov', 'solve_discrete_lyapunov',
+           'solve_lyapunov',
+           'solve_continuous_are', 'solve_discrete_are']
+
+
+def solve_sylvester(a, b, q):
+    """
+    Computes a solution (X) to the Sylvester equation :math:`AX + XB = Q`.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Leading matrix of the Sylvester equation
+    b : (N, N) array_like
+        Trailing matrix of the Sylvester equation
+    q : (M, N) array_like
+        Right-hand side
+
+    Returns
+    -------
+    x : (M, N) ndarray
+        The solution to the Sylvester equation.
+
+    Raises
+    ------
+    LinAlgError
+        If solution was not found
+
+    Notes
+    -----
+    Computes a solution to the Sylvester matrix equation via the Bartels-
+    Stewart algorithm. The A and B matrices first undergo Schur
+    decompositions. The resulting matrices are used to construct an
+    alternative Sylvester equation (``RY + YS^T = F``) where the R and S
+    matrices are in quasi-triangular form (or, when R, S or F are complex,
+    triangular form). The simplified equation is then solved using
+    ``*TRSYL`` from LAPACK directly.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    Given `a`, `b`, and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[-3, -2, 0], [-1, -1, 3], [3, -5, -1]])
+    >>> b = np.array([[1]])
+    >>> q = np.array([[1],[2],[3]])
+    >>> x = linalg.solve_sylvester(a, b, q)
+    >>> x
+    array([[ 0.0625],
+           [-0.5625],
+           [ 0.6875]])
+    >>> np.allclose(a.dot(x) + x.dot(b), q)
+    True
+
+    """
+    # Accommodate empty a
+    if a.size == 0 or b.size == 0:
+        tdict = {'s': np.float32, 'd': np.float64,
+                 'c': np.complex64, 'z': np.complex128}
+        func, = get_lapack_funcs(('trsyl',), arrays=(a, b, q))
+        return np.empty(q.shape, dtype=tdict[func.typecode])
+
+    # Compute the Schur decomposition form of a
+    r, u = schur(a, output='real')
+
+    # Compute the Schur decomposition of b
+    s, v = schur(b.conj().transpose(), output='real')
+
+    # Construct f = u'*q*v
+    f = np.dot(np.dot(u.conj().transpose(), q), v)
+
+    # Call the Sylvester equation solver
+    trsyl, = get_lapack_funcs(('trsyl',), (r, s, f))
+    if trsyl is None:
+        raise RuntimeError('LAPACK implementation does not contain a proper '
+                           'Sylvester equation solver (TRSYL)')
+    y, scale, info = trsyl(r, s, f, tranb='C')
+
+    y = scale*y
+
+    if info < 0:
+        raise LinAlgError("Illegal value encountered in "
+                          "the %d term" % (-info,))
+
+    return np.dot(np.dot(u, y), v.conj().transpose())
+
+
+def solve_continuous_lyapunov(a, q):
+    """
+    Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`.
+
+    Uses the Bartels-Stewart algorithm to find :math:`X`.
+
+    Parameters
+    ----------
+    a : array_like
+        A square matrix
+
+    q : array_like
+        Right-hand side square matrix
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the continuous Lyapunov equation
+
+    See Also
+    --------
+    solve_discrete_lyapunov : computes the solution to the discrete-time
+        Lyapunov equation
+    solve_sylvester : computes the solution to the Sylvester equation
+
+    Notes
+    -----
+    The continuous Lyapunov equation is a special form of the Sylvester
+    equation, hence this solver relies on LAPACK routine ?TRSYL.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    Given `a` and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]])
+    >>> b = np.array([2, 4, -1])
+    >>> q = np.eye(3)
+    >>> x = linalg.solve_continuous_lyapunov(a, q)
+    >>> x
+    array([[ -0.75  ,   0.875 ,  -3.75  ],
+           [  0.875 ,  -1.375 ,   5.3125],
+           [ -3.75  ,   5.3125, -27.0625]])
+    >>> np.allclose(a.dot(x) + x.dot(a.T), q)
+    True
+    """
+
+    a = np.atleast_2d(_asarray_validated(a, check_finite=True))
+    q = np.atleast_2d(_asarray_validated(q, check_finite=True))
+
+    r_or_c = float
+
+    for ind, _ in enumerate((a, q)):
+        if np.iscomplexobj(_):
+            r_or_c = complex
+
+        if not np.equal(*_.shape):
+            raise ValueError(f"Matrix {'aq'[ind]} should be square.")
+
+    # Shape consistency check
+    if a.shape != q.shape:
+        raise ValueError("Matrix a and q should have the same shape.")
+
+    # Accommodate empty array
+    if a.size == 0:
+        tdict = {'s': np.float32, 'd': np.float64,
+                 'c': np.complex64, 'z': np.complex128}
+        func, = get_lapack_funcs(('trsyl',), arrays=(a, q))
+        return np.empty(a.shape, dtype=tdict[func.typecode])
+
+    # Compute the Schur decomposition form of a
+    r, u = schur(a, output='real')
+
+    # Construct f = u'*q*u
+    f = u.conj().T.dot(q.dot(u))
+
+    # Call the Sylvester equation solver
+    trsyl = get_lapack_funcs('trsyl', (r, f))
+
+    dtype_string = 'T' if r_or_c is float else 'C'
+    y, scale, info = trsyl(r, r, f, tranb=dtype_string)
+
+    if info < 0:
+        raise ValueError('?TRSYL exited with the internal error '
+                         f'"illegal value in argument number {-info}.". See '
+                         'LAPACK documentation for the ?TRSYL error codes.')
+    elif info == 1:
+        warnings.warn('Input "a" has an eigenvalue pair whose sum is '
+                      'very close to or exactly zero. The solution is '
+                      'obtained via perturbing the coefficients.',
+                      RuntimeWarning, stacklevel=2)
+    y *= scale
+
+    return u.dot(y).dot(u.conj().T)
+
+
+# For backwards compatibility, keep the old name
+solve_lyapunov = solve_continuous_lyapunov
+
+
+def _solve_discrete_lyapunov_direct(a, q):
+    """
+    Solves the discrete Lyapunov equation directly.
+
+    This function is called by the `solve_discrete_lyapunov` function with
+    `method=direct`. It is not supposed to be called directly.
+    """
+
+    lhs = np.kron(a, a.conj())
+    lhs = np.eye(lhs.shape[0]) - lhs
+    x = solve(lhs, q.flatten())
+
+    return np.reshape(x, q.shape)
+
+
+def _solve_discrete_lyapunov_bilinear(a, q):
+    """
+    Solves the discrete Lyapunov equation using a bilinear transformation.
+
+    This function is called by the `solve_discrete_lyapunov` function with
+    `method=bilinear`. It is not supposed to be called directly.
+    """
+    eye = np.eye(a.shape[0])
+    aH = a.conj().transpose()
+    aHI_inv = inv(aH + eye)
+    b = np.dot(aH - eye, aHI_inv)
+    c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
+    return solve_lyapunov(b.conj().transpose(), -c)
+
+
+def solve_discrete_lyapunov(a, q, method=None):
+    """
+    Solves the discrete Lyapunov equation :math:`AXA^H - X + Q = 0`.
+
+    Parameters
+    ----------
+    a, q : (M, M) array_like
+        Square matrices corresponding to A and Q in the equation
+        above respectively. Must have the same shape.
+
+    method : {'direct', 'bilinear'}, optional
+        Type of solver.
+
+        If not given, chosen to be ``direct`` if ``M`` is less than 10 and
+        ``bilinear`` otherwise.
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the discrete Lyapunov equation
+
+    See Also
+    --------
+    solve_continuous_lyapunov : computes the solution to the continuous-time
+        Lyapunov equation
+
+    Notes
+    -----
+    This section describes the available solvers that can be selected by the
+    'method' parameter. The default method is *direct* if ``M`` is less than 10
+    and ``bilinear`` otherwise.
+
+    Method *direct* uses a direct analytical solution to the discrete Lyapunov
+    equation. The algorithm is given in, for example, [1]_. However, it requires
+    the linear solution of a system with dimension :math:`M^2` so that
+    performance degrades rapidly for even moderately sized matrices.
+
+    Method *bilinear* uses a bilinear transformation to convert the discrete
+    Lyapunov equation to a continuous Lyapunov equation :math:`(BX+XB'=-C)`
+    where :math:`B=(A-I)(A+I)^{-1}` and
+    :math:`C=2(A' + I)^{-1} Q (A + I)^{-1}`. The continuous equation can be
+    efficiently solved since it is a special case of a Sylvester equation.
+    The transformation algorithm is from Popov (1964) as described in [2]_.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1] "Lyapunov equation", Wikipedia,
+       https://en.wikipedia.org/wiki/Lyapunov_equation#Discrete_time
+    .. [2] Gajic, Z., and M.T.J. Qureshi. 2008.
+       Lyapunov Matrix Equation in System Stability and Control.
+       Dover Books on Engineering Series. Dover Publications.
+
+    Examples
+    --------
+    Given `a` and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0.2, 0.5],[0.7, -0.9]])
+    >>> q = np.eye(2)
+    >>> x = linalg.solve_discrete_lyapunov(a, q)
+    >>> x
+    array([[ 0.70872893,  1.43518822],
+           [ 1.43518822, -2.4266315 ]])
+    >>> np.allclose(a.dot(x).dot(a.T)-x, -q)
+    True
+
+    """
+    a = np.asarray(a)
+    q = np.asarray(q)
+    if method is None:
+        # Select automatically based on size of matrices
+        if a.shape[0] >= 10:
+            method = 'bilinear'
+        else:
+            method = 'direct'
+
+    meth = method.lower()
+
+    if meth == 'direct':
+        x = _solve_discrete_lyapunov_direct(a, q)
+    elif meth == 'bilinear':
+        x = _solve_discrete_lyapunov_bilinear(a, q)
+    else:
+        raise ValueError(f'Unknown solver {method}')
+
+    return x
+
+
+def solve_continuous_are(a, b, q, r, e=None, s=None, balanced=True):
+    r"""
+    Solves the continuous-time algebraic Riccati equation (CARE).
+
+    The CARE is defined as
+
+    .. math::
+
+          X A + A^H X - X B R^{-1} B^H X + Q = 0
+
+    The limitations for a solution to exist are :
+
+        * All eigenvalues of :math:`A` on the right half plane, should be
+          controllable.
+
+        * The associated hamiltonian pencil (See Notes), should have
+          eigenvalues sufficiently away from the imaginary axis.
+
+    Moreover, if ``e`` or ``s`` is not precisely ``None``, then the
+    generalized version of CARE
+
+    .. math::
+
+          E^HXA + A^HXE - (E^HXB + S) R^{-1} (B^HXE + S^H) + Q = 0
+
+    is solved. When omitted, ``e`` is assumed to be the identity and ``s``
+    is assumed to be the zero matrix with sizes compatible with ``a`` and
+    ``b``, respectively.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Square matrix
+    b : (M, N) array_like
+        Input
+    q : (M, M) array_like
+        Input
+    r : (N, N) array_like
+        Nonsingular square matrix
+    e : (M, M) array_like, optional
+        Nonsingular square matrix
+    s : (M, N) array_like, optional
+        Input
+    balanced : bool, optional
+        The boolean that indicates whether a balancing step is performed
+        on the data. The default is set to True.
+
+    Returns
+    -------
+    x : (M, M) ndarray
+        Solution to the continuous-time algebraic Riccati equation.
+
+    Raises
+    ------
+    LinAlgError
+        For cases where the stable subspace of the pencil could not be
+        isolated. See Notes section and the references for details.
+
+    See Also
+    --------
+    solve_discrete_are : Solves the discrete-time algebraic Riccati equation
+
+    Notes
+    -----
+    The equation is solved by forming the extended hamiltonian matrix pencil,
+    as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
+
+        [ A    0    B ]             [ E   0    0 ]
+        [-Q  -A^H  -S ] - \lambda * [ 0  E^H   0 ]
+        [ S^H B^H   R ]             [ 0   0    0 ]
+
+    and using a QZ decomposition method.
+
+    In this algorithm, the fail conditions are linked to the symmetry
+    of the product :math:`U_2 U_1^{-1}` and condition number of
+    :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
+    eigenvectors spanning the stable subspace with 2-m rows and partitioned
+    into two m-row matrices. See [1]_ and [2]_ for more details.
+
+    In order to improve the QZ decomposition accuracy, the pencil goes
+    through a balancing step where the sum of absolute values of
+    :math:`H` and :math:`J` entries (after removing the diagonal entries of
+    the sum) is balanced following the recipe given in [3]_.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1]  P. van Dooren , "A Generalized Eigenvalue Approach For Solving
+       Riccati Equations.", SIAM Journal on Scientific and Statistical
+       Computing, Vol.2(2), :doi:`10.1137/0902010`
+
+    .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
+       Equations.", Massachusetts Institute of Technology. Laboratory for
+       Information and Decision Systems. LIDS-R ; 859. Available online :
+       http://hdl.handle.net/1721.1/1301
+
+    .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
+       SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
+
+    Examples
+    --------
+    Given `a`, `b`, `q`, and `r` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[4, 3], [-4.5, -3.5]])
+    >>> b = np.array([[1], [-1]])
+    >>> q = np.array([[9, 6], [6, 4.]])
+    >>> r = 1
+    >>> x = linalg.solve_continuous_are(a, b, q, r)
+    >>> x
+    array([[ 21.72792206,  14.48528137],
+           [ 14.48528137,   9.65685425]])
+    >>> np.allclose(a.T.dot(x) + x.dot(a)-x.dot(b).dot(b.T).dot(x), -q)
+    True
+
+    """
+
+    # Validate input arguments
+    a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
+                                                     a, b, q, r, e, s, 'care')
+
+    H = np.empty((2*m+n, 2*m+n), dtype=r_or_c)
+    H[:m, :m] = a
+    H[:m, m:2*m] = 0.
+    H[:m, 2*m:] = b
+    H[m:2*m, :m] = -q
+    H[m:2*m, m:2*m] = -a.conj().T
+    H[m:2*m, 2*m:] = 0. if s is None else -s
+    H[2*m:, :m] = 0. if s is None else s.conj().T
+    H[2*m:, m:2*m] = b.conj().T
+    H[2*m:, 2*m:] = r
+
+    if gen_are and e is not None:
+        J = block_diag(e, e.conj().T, np.zeros_like(r, dtype=r_or_c))
+    else:
+        J = block_diag(np.eye(2*m), np.zeros_like(r, dtype=r_or_c))
+
+    if balanced:
+        # xGEBAL does not remove the diagonals before scaling. Also
+        # to avoid destroying the Symplectic structure, we follow Ref.3
+        M = np.abs(H) + np.abs(J)
+        np.fill_diagonal(M, 0.)
+        _, (sca, _) = matrix_balance(M, separate=1, permute=0)
+        # do we need to bother?
+        if not np.allclose(sca, np.ones_like(sca)):
+            # Now impose diag(D,inv(D)) from Benner where D is
+            # square root of s_i/s_(n+i) for i=0,....
+            sca = np.log2(sca)
+            # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
+            s = np.round((sca[m:2*m] - sca[:m])/2)
+            sca = 2 ** np.r_[s, -s, sca[2*m:]]
+            # Elementwise multiplication via broadcasting.
+            elwisescale = sca[:, None] * np.reciprocal(sca)
+            H *= elwisescale
+            J *= elwisescale
+
+    # Deflate the pencil to 2m x 2m ala Ref.1, eq.(55)
+    q, r = qr(H[:, -n:])
+    H = q[:, n:].conj().T.dot(H[:, :2*m])
+    J = q[:2*m, n:].conj().T.dot(J[:2*m, :2*m])
+
+    # Decide on which output type is needed for QZ
+    out_str = 'real' if r_or_c is float else 'complex'
+
+    _, _, _, _, _, u = ordqz(H, J, sort='lhp', overwrite_a=True,
+                             overwrite_b=True, check_finite=False,
+                             output=out_str)
+
+    # Get the relevant parts of the stable subspace basis
+    if e is not None:
+        u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
+    u00 = u[:m, :m]
+    u10 = u[m:, :m]
+
+    # Solve via back-substituion after checking the condition of u00
+    up, ul, uu = lu(u00)
+    if 1/cond(uu) < np.spacing(1.):
+        raise LinAlgError('Failed to find a finite solution.')
+
+    # Exploit the triangular structure
+    x = solve_triangular(ul.conj().T,
+                         solve_triangular(uu.conj().T,
+                                          u10.conj().T,
+                                          lower=True),
+                         unit_diagonal=True,
+                         ).conj().T.dot(up.conj().T)
+    if balanced:
+        x *= sca[:m, None] * sca[:m]
+
+    # Check the deviation from symmetry for lack of success
+    # See proof of Thm.5 item 3 in [2]
+    u_sym = u00.conj().T.dot(u10)
+    n_u_sym = norm(u_sym, 1)
+    u_sym = u_sym - u_sym.conj().T
+    sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
+
+    if norm(u_sym, 1) > sym_threshold:
+        raise LinAlgError('The associated Hamiltonian pencil has eigenvalues '
+                          'too close to the imaginary axis')
+
+    return (x + x.conj().T)/2
+
+
+def solve_discrete_are(a, b, q, r, e=None, s=None, balanced=True):
+    r"""
+    Solves the discrete-time algebraic Riccati equation (DARE).
+
+    The DARE is defined as
+
+    .. math::
+
+          A^HXA - X - (A^HXB) (R + B^HXB)^{-1} (B^HXA) + Q = 0
+
+    The limitations for a solution to exist are :
+
+        * All eigenvalues of :math:`A` outside the unit disc, should be
+          controllable.
+
+        * The associated symplectic pencil (See Notes), should have
+          eigenvalues sufficiently away from the unit circle.
+
+    Moreover, if ``e`` and ``s`` are not both precisely ``None``, then the
+    generalized version of DARE
+
+    .. math::
+
+          A^HXA - E^HXE - (A^HXB+S) (R+B^HXB)^{-1} (B^HXA+S^H) + Q = 0
+
+    is solved. When omitted, ``e`` is assumed to be the identity and ``s``
+    is assumed to be the zero matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Square matrix
+    b : (M, N) array_like
+        Input
+    q : (M, M) array_like
+        Input
+    r : (N, N) array_like
+        Square matrix
+    e : (M, M) array_like, optional
+        Nonsingular square matrix
+    s : (M, N) array_like, optional
+        Input
+    balanced : bool
+        The boolean that indicates whether a balancing step is performed
+        on the data. The default is set to True.
+
+    Returns
+    -------
+    x : (M, M) ndarray
+        Solution to the discrete algebraic Riccati equation.
+
+    Raises
+    ------
+    LinAlgError
+        For cases where the stable subspace of the pencil could not be
+        isolated. See Notes section and the references for details.
+
+    See Also
+    --------
+    solve_continuous_are : Solves the continuous algebraic Riccati equation
+
+    Notes
+    -----
+    The equation is solved by forming the extended symplectic matrix pencil,
+    as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
+
+           [  A   0   B ]             [ E   0   B ]
+           [ -Q  E^H -S ] - \lambda * [ 0  A^H  0 ]
+           [ S^H  0   R ]             [ 0 -B^H  0 ]
+
+    and using a QZ decomposition method.
+
+    In this algorithm, the fail conditions are linked to the symmetry
+    of the product :math:`U_2 U_1^{-1}` and condition number of
+    :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
+    eigenvectors spanning the stable subspace with 2-m rows and partitioned
+    into two m-row matrices. See [1]_ and [2]_ for more details.
+
+    In order to improve the QZ decomposition accuracy, the pencil goes
+    through a balancing step where the sum of absolute values of
+    :math:`H` and :math:`J` rows/cols (after removing the diagonal entries)
+    is balanced following the recipe given in [3]_. If the data has small
+    numerical noise, balancing may amplify their effects and some clean up
+    is required.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1]  P. van Dooren , "A Generalized Eigenvalue Approach For Solving
+       Riccati Equations.", SIAM Journal on Scientific and Statistical
+       Computing, Vol.2(2), :doi:`10.1137/0902010`
+
+    .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
+       Equations.", Massachusetts Institute of Technology. Laboratory for
+       Information and Decision Systems. LIDS-R ; 859. Available online :
+       http://hdl.handle.net/1721.1/1301
+
+    .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
+       SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
+
+    Examples
+    --------
+    Given `a`, `b`, `q`, and `r` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg as la
+    >>> a = np.array([[0, 1], [0, -1]])
+    >>> b = np.array([[1, 0], [2, 1]])
+    >>> q = np.array([[-4, -4], [-4, 7]])
+    >>> r = np.array([[9, 3], [3, 1]])
+    >>> x = la.solve_discrete_are(a, b, q, r)
+    >>> x
+    array([[-4., -4.],
+           [-4.,  7.]])
+    >>> R = la.solve(r + b.T.dot(x).dot(b), b.T.dot(x).dot(a))
+    >>> np.allclose(a.T.dot(x).dot(a) - x - a.T.dot(x).dot(b).dot(R), -q)
+    True
+
+    """
+
+    # Validate input arguments
+    a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
+                                                     a, b, q, r, e, s, 'dare')
+
+    # Form the matrix pencil
+    H = np.zeros((2*m+n, 2*m+n), dtype=r_or_c)
+    H[:m, :m] = a
+    H[:m, 2*m:] = b
+    H[m:2*m, :m] = -q
+    H[m:2*m, m:2*m] = np.eye(m) if e is None else e.conj().T
+    H[m:2*m, 2*m:] = 0. if s is None else -s
+    H[2*m:, :m] = 0. if s is None else s.conj().T
+    H[2*m:, 2*m:] = r
+
+    J = np.zeros_like(H, dtype=r_or_c)
+    J[:m, :m] = np.eye(m) if e is None else e
+    J[m:2*m, m:2*m] = a.conj().T
+    J[2*m:, m:2*m] = -b.conj().T
+
+    if balanced:
+        # xGEBAL does not remove the diagonals before scaling. Also
+        # to avoid destroying the Symplectic structure, we follow Ref.3
+        M = np.abs(H) + np.abs(J)
+        np.fill_diagonal(M, 0.)
+        _, (sca, _) = matrix_balance(M, separate=1, permute=0)
+        # do we need to bother?
+        if not np.allclose(sca, np.ones_like(sca)):
+            # Now impose diag(D,inv(D)) from Benner where D is
+            # square root of s_i/s_(n+i) for i=0,....
+            sca = np.log2(sca)
+            # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
+            s = np.round((sca[m:2*m] - sca[:m])/2)
+            sca = 2 ** np.r_[s, -s, sca[2*m:]]
+            # Elementwise multiplication via broadcasting.
+            elwisescale = sca[:, None] * np.reciprocal(sca)
+            H *= elwisescale
+            J *= elwisescale
+
+    # Deflate the pencil by the R column ala Ref.1
+    q_of_qr, _ = qr(H[:, -n:])
+    H = q_of_qr[:, n:].conj().T.dot(H[:, :2*m])
+    J = q_of_qr[:, n:].conj().T.dot(J[:, :2*m])
+
+    # Decide on which output type is needed for QZ
+    out_str = 'real' if r_or_c is float else 'complex'
+
+    _, _, _, _, _, u = ordqz(H, J, sort='iuc',
+                             overwrite_a=True,
+                             overwrite_b=True,
+                             check_finite=False,
+                             output=out_str)
+
+    # Get the relevant parts of the stable subspace basis
+    if e is not None:
+        u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
+    u00 = u[:m, :m]
+    u10 = u[m:, :m]
+
+    # Solve via back-substituion after checking the condition of u00
+    up, ul, uu = lu(u00)
+
+    if 1/cond(uu) < np.spacing(1.):
+        raise LinAlgError('Failed to find a finite solution.')
+
+    # Exploit the triangular structure
+    x = solve_triangular(ul.conj().T,
+                         solve_triangular(uu.conj().T,
+                                          u10.conj().T,
+                                          lower=True),
+                         unit_diagonal=True,
+                         ).conj().T.dot(up.conj().T)
+    if balanced:
+        x *= sca[:m, None] * sca[:m]
+
+    # Check the deviation from symmetry for lack of success
+    # See proof of Thm.5 item 3 in [2]
+    u_sym = u00.conj().T.dot(u10)
+    n_u_sym = norm(u_sym, 1)
+    u_sym = u_sym - u_sym.conj().T
+    sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
+
+    if norm(u_sym, 1) > sym_threshold:
+        raise LinAlgError('The associated symplectic pencil has eigenvalues '
+                          'too close to the unit circle')
+
+    return (x + x.conj().T)/2
+
+
+def _are_validate_args(a, b, q, r, e, s, eq_type='care'):
+    """
+    A helper function to validate the arguments supplied to the
+    Riccati equation solvers. Any discrepancy found in the input
+    matrices leads to a ``ValueError`` exception.
+
+    Essentially, it performs:
+
+        - a check whether the input is free of NaN and Infs
+        - a pass for the data through ``numpy.atleast_2d()``
+        - squareness check of the relevant arrays
+        - shape consistency check of the arrays
+        - singularity check of the relevant arrays
+        - symmetricity check of the relevant matrices
+        - a check whether the regular or the generalized version is asked.
+
+    This function is used by ``solve_continuous_are`` and
+    ``solve_discrete_are``.
+
+    Parameters
+    ----------
+    a, b, q, r, e, s : array_like
+        Input data
+    eq_type : str
+        Accepted arguments are 'care' and 'dare'.
+
+    Returns
+    -------
+    a, b, q, r, e, s : ndarray
+        Regularized input data
+    m, n : int
+        shape of the problem
+    r_or_c : type
+        Data type of the problem, returns float or complex
+    gen_or_not : bool
+        Type of the equation, True for generalized and False for regular ARE.
+
+    """
+
+    if eq_type.lower() not in ("dare", "care"):
+        raise ValueError("Equation type unknown. "
+                         "Only 'care' and 'dare' is understood")
+
+    a = np.atleast_2d(_asarray_validated(a, check_finite=True))
+    b = np.atleast_2d(_asarray_validated(b, check_finite=True))
+    q = np.atleast_2d(_asarray_validated(q, check_finite=True))
+    r = np.atleast_2d(_asarray_validated(r, check_finite=True))
+
+    # Get the correct data types otherwise NumPy complains
+    # about pushing complex numbers into real arrays.
+    r_or_c = complex if np.iscomplexobj(b) else float
+
+    for ind, mat in enumerate((a, q, r)):
+        if np.iscomplexobj(mat):
+            r_or_c = complex
+
+        if not np.equal(*mat.shape):
+            raise ValueError(f"Matrix {'aqr'[ind]} should be square.")
+
+    # Shape consistency checks
+    m, n = b.shape
+    if m != a.shape[0]:
+        raise ValueError("Matrix a and b should have the same number of rows.")
+    if m != q.shape[0]:
+        raise ValueError("Matrix a and q should have the same shape.")
+    if n != r.shape[0]:
+        raise ValueError("Matrix b and r should have the same number of cols.")
+
+    # Check if the data matrices q, r are (sufficiently) hermitian
+    for ind, mat in enumerate((q, r)):
+        if norm(mat - mat.conj().T, 1) > np.spacing(norm(mat, 1))*100:
+            raise ValueError(f"Matrix {'qr'[ind]} should be symmetric/hermitian.")
+
+    # Continuous time ARE should have a nonsingular r matrix.
+    if eq_type == 'care':
+        min_sv = svd(r, compute_uv=False)[-1]
+        if min_sv == 0. or min_sv < np.spacing(1.)*norm(r, 1):
+            raise ValueError('Matrix r is numerically singular.')
+
+    # Check if the generalized case is required with omitted arguments
+    # perform late shape checking etc.
+    generalized_case = e is not None or s is not None
+
+    if generalized_case:
+        if e is not None:
+            e = np.atleast_2d(_asarray_validated(e, check_finite=True))
+            if not np.equal(*e.shape):
+                raise ValueError("Matrix e should be square.")
+            if m != e.shape[0]:
+                raise ValueError("Matrix a and e should have the same shape.")
+            # numpy.linalg.cond doesn't check for exact zeros and
+            # emits a runtime warning. Hence the following manual check.
+            min_sv = svd(e, compute_uv=False)[-1]
+            if min_sv == 0. or min_sv < np.spacing(1.) * norm(e, 1):
+                raise ValueError('Matrix e is numerically singular.')
+            if np.iscomplexobj(e):
+                r_or_c = complex
+        if s is not None:
+            s = np.atleast_2d(_asarray_validated(s, check_finite=True))
+            if s.shape != b.shape:
+                raise ValueError("Matrix b and s should have the same shape.")
+            if np.iscomplexobj(s):
+                r_or_c = complex
+
+    return a, b, q, r, e, s, m, n, r_or_c, generalized_case
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py b/venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dca572f2d5a12a27ccb468425f03c75e86d5da7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
@@ -0,0 +1,1332 @@
+import math
+import warnings
+
+import numpy as np
+from numpy.lib.stride_tricks import as_strided
+
+
+__all__ = ['toeplitz', 'circulant', 'hankel',
+           'hadamard', 'leslie', 'kron', 'block_diag', 'companion',
+           'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+           'fiedler', 'fiedler_companion', 'convolution_matrix']
+
+
+# -----------------------------------------------------------------------------
+#  matrix construction functions
+# -----------------------------------------------------------------------------
+
+
+def toeplitz(c, r=None):
+    r"""
+    Construct a Toeplitz matrix.
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    Parameters
+    ----------
+    c : array_like
+        First column of the matrix.
+    r : array_like, optional
+        First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
+        in this case, if c[0] is real, the result is a Hermitian matrix.
+        r[0] is ignored; the first row of the returned matrix is
+        ``[c[0], r[1:]]``.
+
+        .. warning::
+
+            Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+            not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+            before passing them to `toeplitz`.
+
+    Returns
+    -------
+    A : (len(c), len(r)) ndarray
+        The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
+
+    See Also
+    --------
+    circulant : circulant matrix
+    hankel : Hankel matrix
+    solve_toeplitz : Solve a Toeplitz system.
+
+    Notes
+    -----
+    The behavior when `c` or `r` is a scalar, or when `c` is complex and
+    `r` is None, was changed in version 0.8.0. The behavior in previous
+    versions was undocumented and is no longer supported.
+
+    Examples
+    --------
+    >>> from scipy.linalg import toeplitz
+    >>> toeplitz([1,2,3], [1,4,5,6])
+    array([[1, 4, 5, 6],
+           [2, 1, 4, 5],
+           [3, 2, 1, 4]])
+    >>> toeplitz([1.0, 2+3j, 4-1j])
+    array([[ 1.+0.j,  2.-3.j,  4.+1.j],
+           [ 2.+3.j,  1.+0.j,  2.-3.j],
+           [ 4.-1.j,  2.+3.j,  1.+0.j]])
+
+    """
+    c = np.asarray(c)
+    if r is None:
+        r = c.conjugate()
+    else:
+        r = np.asarray(r)
+
+    if c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a "
+               "batch, not `ravel`ed. To preserve the existing behavior and silence "
+               "this warning, `ravel` arguments before passing them to `toeplitz`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+
+    c, r = c.ravel(), r.ravel()
+    # Form a 1-D array containing a reversed c followed by r[1:] that could be
+    # strided to give us toeplitz matrix.
+    vals = np.concatenate((c[::-1], r[1:]))
+    out_shp = len(c), len(r)
+    n = vals.strides[0]
+    return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy()
+
+
+def circulant(c):
+    """
+    Construct a circulant matrix.
+
+    Parameters
+    ----------
+    c : (..., N,)  array_like
+        The first column(s) of the matrix. Multidimensional arrays are treated as a
+        batch: each slice along the last axis is the first column of an output matrix.
+
+    Returns
+    -------
+    A : (..., N, N) ndarray
+        A circulant matrix whose first column is given by `c`.  For batch input, each
+        slice of shape ``(N, N)`` along the last two dimensions of the output
+        corresponds with a slice of shape ``(N,)`` along the last dimension of the
+        input.
+
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    hankel : Hankel matrix
+    solve_circulant : Solve a circulant system.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import circulant
+    >>> circulant([1, 2, 3])
+    array([[1, 3, 2],
+           [2, 1, 3],
+           [3, 2, 1]])
+
+    >>> circulant([[1, 2, 3], [4, 5, 6]])
+    array([[[1, 3, 2],
+            [2, 1, 3],
+            [3, 2, 1]],
+           [[4, 6, 5],
+            [5, 4, 6],
+            [6, 5, 4]]])
+    """
+    c = np.atleast_1d(c)
+    batch_shape, N = c.shape[:-1], c.shape[-1]
+    # Need to use `prod(batch_shape)` instead of `-1` in case array has zero size
+    c = c.reshape(math.prod(batch_shape), N) if batch_shape else c
+    # Form an extended array that could be strided to give circulant version
+    c_ext = np.concatenate((c[..., ::-1], c[..., :0:-1]), axis=-1).ravel()
+    L = c.shape[-1]
+    n = c_ext.strides[-1]
+    if c.ndim == 1:
+        A = as_strided(c_ext[L-1:], shape=(L, L), strides=(-n, n))
+    else:
+        m = c.shape[0]
+        A = as_strided(c_ext[L-1:], shape=(m, L, L), strides=(n*(2*L-1), -n, n))
+    return A.reshape(batch_shape + (N, N)).copy()
+
+
+def hankel(c, r=None):
+    """
+    Construct a Hankel matrix.
+
+    The Hankel matrix has constant anti-diagonals, with `c` as its
+    first column and `r` as its last row. If the first element of `r`
+    differs from the last element of `c`, the first element of `r` is
+    replaced by the last element of `c` to ensure that anti-diagonals
+    remain constant. If `r` is not given, then `r = zeros_like(c)` is
+    assumed.
+
+    Parameters
+    ----------
+    c : array_like
+        First column of the matrix. Whatever the actual shape of `c`, it
+        will be converted to a 1-D array.
+    r : array_like, optional
+        Last row of the matrix. If None, ``r = zeros_like(c)`` is assumed.
+        r[0] is ignored; the last row of the returned matrix is
+        ``[c[-1], r[1:]]``. Whatever the actual shape of `r`, it will be
+        converted to a 1-D array.
+
+    Returns
+    -------
+    A : (len(c), len(r)) ndarray
+        The Hankel matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    circulant : circulant matrix
+
+    Examples
+    --------
+    >>> from scipy.linalg import hankel
+    >>> hankel([1, 17, 99])
+    array([[ 1, 17, 99],
+           [17, 99,  0],
+           [99,  0,  0]])
+    >>> hankel([1,2,3,4], [4,7,7,8,9])
+    array([[1, 2, 3, 4, 7],
+           [2, 3, 4, 7, 7],
+           [3, 4, 7, 7, 8],
+           [4, 7, 7, 8, 9]])
+
+    """
+    c = np.asarray(c).ravel()
+    if r is None:
+        r = np.zeros_like(c)
+    else:
+        r = np.asarray(r).ravel()
+    # Form a 1-D array of values to be used in the matrix, containing `c`
+    # followed by r[1:].
+    vals = np.concatenate((c, r[1:]))
+    # Stride on concatenated array to get hankel matrix
+    out_shp = len(c), len(r)
+    n = vals.strides[0]
+    return as_strided(vals, shape=out_shp, strides=(n, n)).copy()
+
+
+def hadamard(n, dtype=int):
+    """
+    Construct an Hadamard matrix.
+
+    Constructs an n-by-n Hadamard matrix, using Sylvester's
+    construction. `n` must be a power of 2.
+
+    Parameters
+    ----------
+    n : int
+        The order of the matrix. `n` must be a power of 2.
+    dtype : dtype, optional
+        The data type of the array to be constructed.
+
+    Returns
+    -------
+    H : (n, n) ndarray
+        The Hadamard matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import hadamard
+    >>> hadamard(2, dtype=complex)
+    array([[ 1.+0.j,  1.+0.j],
+           [ 1.+0.j, -1.-0.j]])
+    >>> hadamard(4)
+    array([[ 1,  1,  1,  1],
+           [ 1, -1,  1, -1],
+           [ 1,  1, -1, -1],
+           [ 1, -1, -1,  1]])
+
+    """
+
+    # This function is a slightly modified version of the
+    # function contributed by Ivo in ticket #675.
+
+    if n < 1:
+        lg2 = 0
+    else:
+        lg2 = int(math.log(n, 2))
+    if 2 ** lg2 != n:
+        raise ValueError("n must be an positive integer, and n must be "
+                         "a power of 2")
+
+    H = np.array([[1]], dtype=dtype)
+
+    # Sylvester's construction
+    for i in range(0, lg2):
+        H = np.vstack((np.hstack((H, H)), np.hstack((H, -H))))
+
+    return H
+
+
+def leslie(f, s):
+    """
+    Create a Leslie matrix.
+
+    Given the length n array of fecundity coefficients `f` and the length
+    n-1 array of survival coefficients `s`, return the associated Leslie
+    matrix.
+
+    Parameters
+    ----------
+    f : (..., N,) array_like
+        The "fecundity" coefficients.
+    s : (..., N-1,) array_like
+        The "survival" coefficients. The length of each slice of `s` (along the last
+        axis) must be one less than the length of `f`, and it must be at least 1.
+
+    Returns
+    -------
+    L : (..., N, N) ndarray
+        The array is zero except for the first row,
+        which is `f`, and the first sub-diagonal, which is `s`.
+        For 1-D input, the data-type of the array will be the data-type of
+        ``f[0]+s[0]``.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    The Leslie matrix is used to model discrete-time, age-structured
+    population growth [1]_ [2]_. In a population with `n` age classes, two sets
+    of parameters define a Leslie matrix: the `n` "fecundity coefficients",
+    which give the number of offspring per-capita produced by each age
+    class, and the `n` - 1 "survival coefficients", which give the
+    per-capita survival rate of each age class.
+
+    N-dimensional input are treated as a batches of coefficient arrays: each
+    slice along the last axis of the input arrays is a 1-D coefficient array,
+    and each slice along the last two dimensions of the output is the
+    corresponding Leslie matrix.
+
+    References
+    ----------
+    .. [1] P. H. Leslie, On the use of matrices in certain population
+           mathematics, Biometrika, Vol. 33, No. 3, 183--212 (Nov. 1945)
+    .. [2] P. H. Leslie, Some further notes on the use of matrices in
+           population mathematics, Biometrika, Vol. 35, No. 3/4, 213--245
+           (Dec. 1948)
+
+    Examples
+    --------
+    >>> from scipy.linalg import leslie
+    >>> leslie([0.1, 2.0, 1.0, 0.1], [0.2, 0.8, 0.7])
+    array([[ 0.1,  2. ,  1. ,  0.1],
+           [ 0.2,  0. ,  0. ,  0. ],
+           [ 0. ,  0.8,  0. ,  0. ],
+           [ 0. ,  0. ,  0.7,  0. ]])
+
+    """
+    f = np.atleast_1d(f)
+    s = np.atleast_1d(s)
+
+    if f.shape[-1] != s.shape[-1] + 1:
+        raise ValueError("Incorrect lengths for f and s. The length of s along "
+                         "the last axis must be one less than the length of f.")
+    if s.shape[-1] == 0:
+        raise ValueError("The length of s must be at least 1.")
+
+    n = f.shape[-1]
+
+    if f.ndim > 1 or s.ndim > 1:
+        from scipy.stats._resampling import _vectorize_statistic
+        _leslie_nd = _vectorize_statistic(leslie)
+        return np.moveaxis(_leslie_nd(f, s, axis=-1), [0, 1], [-2, -1])
+
+    tmp = f[0] + s[0]
+    a = np.zeros((n, n), dtype=tmp.dtype)
+    a[0] = f
+    a[list(range(1, n)), list(range(0, n - 1))] = s
+    return a
+
+
+def kron(a, b):
+    """
+    Kronecker product.
+
+    .. deprecated:: 1.15.0
+        `kron` has been deprecated in favour of `numpy.kron` and will be
+        removed in SciPy 1.17.0.
+
+    The result is the block matrix::
+
+        a[0,0]*b    a[0,1]*b  ... a[0,-1]*b
+        a[1,0]*b    a[1,1]*b  ... a[1,-1]*b
+        ...
+        a[-1,0]*b   a[-1,1]*b ... a[-1,-1]*b
+
+    Parameters
+    ----------
+    a : (M, N) ndarray
+        Input array
+    b : (P, Q) ndarray
+        Input array
+
+    Returns
+    -------
+    A : (M*P, N*Q) ndarray
+        Kronecker product of `a` and `b`.
+
+    Examples
+    --------
+    >>> from numpy import array
+    >>> from scipy.linalg import kron
+    >>> kron(array([[1,2],[3,4]]), array([[1,1,1]]))
+    array([[1, 1, 1, 2, 2, 2],
+           [3, 3, 3, 4, 4, 4]])
+
+    """
+    msg = ("`kron` has been deprecated in favour of `numpy.kron` in SciPy"
+           " 1.15.0 and will be removed in SciPy 1.17.0.")
+    warnings.warn(msg, DeprecationWarning, stacklevel=2)
+    # accommodate empty arrays
+    if a.size == 0 or b.size == 0:
+        m = a.shape[0] * b.shape[0]
+        n = a.shape[1] * b.shape[1]
+        return np.empty_like(a, shape=(m, n))
+
+    if not a.flags['CONTIGUOUS']:
+        a = np.reshape(a, a.shape)
+    if not b.flags['CONTIGUOUS']:
+        b = np.reshape(b, b.shape)
+    o = np.outer(a, b)
+    o = o.reshape(a.shape + b.shape)
+    return np.concatenate(np.concatenate(o, axis=1), axis=1)
+
+
+def block_diag(*arrs):
+    """
+    Create a block diagonal matrix from provided arrays.
+
+    Given the inputs `A`, `B` and `C`, the output will have these
+    arrays arranged on the diagonal::
+
+        [[A, 0, 0],
+         [0, B, 0],
+         [0, 0, C]]
+
+    Parameters
+    ----------
+    A, B, C, ... : array_like, up to 2-D
+        Input arrays.  A 1-D array or array_like sequence of length `n` is
+        treated as a 2-D array with shape ``(1,n)``.
+
+    Returns
+    -------
+    D : ndarray
+        Array with `A`, `B`, `C`, ... on the diagonal. `D` has the
+        same dtype as `A`.
+
+    Notes
+    -----
+    If all the input arrays are square, the output is known as a
+    block diagonal matrix.
+
+    Empty sequences (i.e., array-likes of zero size) will not be ignored.
+    Noteworthy, both [] and [[]] are treated as matrices with shape ``(1,0)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import block_diag
+    >>> A = [[1, 0],
+    ...      [0, 1]]
+    >>> B = [[3, 4, 5],
+    ...      [6, 7, 8]]
+    >>> C = [[7]]
+    >>> P = np.zeros((2, 0), dtype='int32')
+    >>> block_diag(A, B, C)
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0],
+           [0, 0, 3, 4, 5, 0],
+           [0, 0, 6, 7, 8, 0],
+           [0, 0, 0, 0, 0, 7]])
+    >>> block_diag(A, P, B, C)
+    array([[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, 3, 4, 5, 0],
+           [0, 0, 6, 7, 8, 0],
+           [0, 0, 0, 0, 0, 7]])
+    >>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]])
+    array([[ 1.,  0.,  0.,  0.,  0.],
+           [ 0.,  2.,  3.,  0.,  0.],
+           [ 0.,  0.,  0.,  4.,  5.],
+           [ 0.,  0.,  0.,  6.,  7.]])
+
+    """
+    if arrs == ():
+        arrs = ([],)
+    arrs = [np.atleast_2d(a) for a in arrs]
+
+    bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2]
+    if bad_args:
+        raise ValueError("arguments in the following positions "
+                         f"have dimension greater than 2: {bad_args}")
+
+    shapes = np.array([a.shape for a in arrs])
+    out_dtype = np.result_type(*[arr.dtype for arr in arrs])
+    out = np.zeros(np.sum(shapes, axis=0), dtype=out_dtype)
+
+    r, c = 0, 0
+    for i, (rr, cc) in enumerate(shapes):
+        out[r:r + rr, c:c + cc] = arrs[i]
+        r += rr
+        c += cc
+    return out
+
+
+def companion(a):
+    """
+    Create a companion matrix.
+
+    Create the companion matrix [1]_ associated with the polynomial whose
+    coefficients are given in `a`.
+
+    Parameters
+    ----------
+    a : (..., N) array_like
+        1-D array of polynomial coefficients. The length of `a` must be
+        at least two, and ``a[0]`` must not be zero.
+        M-dimensional arrays are treated as a batch: each slice along the last
+        axis is a 1-D array of polynomial coefficients.
+
+    Returns
+    -------
+    c : (..., N-1, N-1) ndarray
+        For 1-D input, the first row of `c` is ``-a[1:]/a[0]``, and the first
+        sub-diagonal is all ones.  The data-type of the array is the same
+        as the data-type of ``1.0*a[0]``.
+        For batch input, each slice of shape ``(N-1, N-1)`` along the last two
+        dimensions of the output corresponds with a slice of shape ``(N,)``
+        along the last dimension of the input.
+
+    Raises
+    ------
+    ValueError
+        If any of the following are true: a) ``a.shape[-1] < 2``; b) ``a[..., 0] == 0``.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    References
+    ----------
+    .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*.  Cambridge, UK:
+        Cambridge University Press, 1999, pp. 146-7.
+
+    Examples
+    --------
+    >>> from scipy.linalg import companion
+    >>> companion([1, -10, 31, -30])
+    array([[ 10., -31.,  30.],
+           [  1.,   0.,   0.],
+           [  0.,   1.,   0.]])
+
+    """
+    a = np.atleast_1d(a)
+    n = a.shape[-1]
+
+    if n < 2:
+        raise ValueError("The length of `a` along the last axis must be at least 2.")
+
+    if np.any(a[..., 0] == 0):
+        raise ValueError("The first coefficient(s) of `a` (i.e. elements "
+                         "of `a[..., 0]`) must not be zero.")
+
+    first_row = -a[..., 1:] / (1.0 * a[..., 0:1])
+    c = np.zeros(a.shape[:-1] + (n - 1, n - 1), dtype=first_row.dtype)
+    c[..., 0, :] = first_row
+    c[..., np.arange(1, n - 1), np.arange(0, n - 2)] = 1
+    return c
+
+
+def helmert(n, full=False):
+    """
+    Create an Helmert matrix of order `n`.
+
+    This has applications in statistics, compositional or simplicial analysis,
+    and in Aitchison geometry.
+
+    Parameters
+    ----------
+    n : int
+        The size of the array to create.
+    full : bool, optional
+        If True the (n, n) ndarray will be returned.
+        Otherwise the submatrix that does not include the first
+        row will be returned.
+        Default: False.
+
+    Returns
+    -------
+    M : ndarray
+        The Helmert matrix.
+        The shape is (n, n) or (n-1, n) depending on the `full` argument.
+
+    Examples
+    --------
+    >>> from scipy.linalg import helmert
+    >>> helmert(5, full=True)
+    array([[ 0.4472136 ,  0.4472136 ,  0.4472136 ,  0.4472136 ,  0.4472136 ],
+           [ 0.70710678, -0.70710678,  0.        ,  0.        ,  0.        ],
+           [ 0.40824829,  0.40824829, -0.81649658,  0.        ,  0.        ],
+           [ 0.28867513,  0.28867513,  0.28867513, -0.8660254 ,  0.        ],
+           [ 0.2236068 ,  0.2236068 ,  0.2236068 ,  0.2236068 , -0.89442719]])
+
+    """
+    H = np.tril(np.ones((n, n)), -1) - np.diag(np.arange(n))
+    d = np.arange(n) * np.arange(1, n+1)
+    H[0] = 1
+    d[0] = n
+    H_full = H / np.sqrt(d)[:, np.newaxis]
+    if full:
+        return H_full
+    else:
+        return H_full[1:]
+
+
+def hilbert(n):
+    """
+    Create a Hilbert matrix of order `n`.
+
+    Returns the `n` by `n` array with entries `h[i,j] = 1 / (i + j + 1)`.
+
+    Parameters
+    ----------
+    n : int
+        The size of the array to create.
+
+    Returns
+    -------
+    h : (n, n) ndarray
+        The Hilbert matrix.
+
+    See Also
+    --------
+    invhilbert : Compute the inverse of a Hilbert matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.10.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import hilbert
+    >>> hilbert(3)
+    array([[ 1.        ,  0.5       ,  0.33333333],
+           [ 0.5       ,  0.33333333,  0.25      ],
+           [ 0.33333333,  0.25      ,  0.2       ]])
+
+    """
+    values = 1.0 / (1.0 + np.arange(2 * n - 1))
+    h = hankel(values[:n], r=values[n - 1:])
+    return h
+
+
+def invhilbert(n, exact=False):
+    """
+    Compute the inverse of the Hilbert matrix of order `n`.
+
+    The entries in the inverse of a Hilbert matrix are integers. When `n`
+    is greater than 14, some entries in the inverse exceed the upper limit
+    of 64 bit integers. The `exact` argument provides two options for
+    dealing with these large integers.
+
+    Parameters
+    ----------
+    n : int
+        The order of the Hilbert matrix.
+    exact : bool, optional
+        If False, the data type of the array that is returned is np.float64,
+        and the array is an approximation of the inverse.
+        If True, the array is the exact integer inverse array. To represent
+        the exact inverse when n > 14, the returned array is an object array
+        of long integers. For n <= 14, the exact inverse is returned as an
+        array with data type np.int64.
+
+    Returns
+    -------
+    invh : (n, n) ndarray
+        The data type of the array is np.float64 if `exact` is False.
+        If `exact` is True, the data type is either np.int64 (for n <= 14)
+        or object (for n > 14). In the latter case, the objects in the
+        array will be long integers.
+
+    See Also
+    --------
+    hilbert : Create a Hilbert matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.10.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import invhilbert
+    >>> invhilbert(4)
+    array([[   16.,  -120.,   240.,  -140.],
+           [ -120.,  1200., -2700.,  1680.],
+           [  240., -2700.,  6480., -4200.],
+           [ -140.,  1680., -4200.,  2800.]])
+    >>> invhilbert(4, exact=True)
+    array([[   16,  -120,   240,  -140],
+           [ -120,  1200, -2700,  1680],
+           [  240, -2700,  6480, -4200],
+           [ -140,  1680, -4200,  2800]], dtype=int64)
+    >>> invhilbert(16)[7,7]
+    4.2475099528537506e+19
+    >>> invhilbert(16, exact=True)[7,7]
+    42475099528537378560
+
+    """
+    from scipy.special import comb
+    if exact:
+        if n > 14:
+            dtype = object
+        else:
+            dtype = np.int64
+    else:
+        dtype = np.float64
+    invh = np.empty((n, n), dtype=dtype)
+    for i in range(n):
+        for j in range(0, i + 1):
+            s = i + j
+            invh[i, j] = ((-1) ** s * (s + 1) *
+                          comb(n + i, n - j - 1, exact=exact) *
+                          comb(n + j, n - i - 1, exact=exact) *
+                          comb(s, i, exact=exact) ** 2)
+            if i != j:
+                invh[j, i] = invh[i, j]
+    return invh
+
+
+def pascal(n, kind='symmetric', exact=True):
+    """
+    Returns the n x n Pascal matrix.
+
+    The Pascal matrix is a matrix containing the binomial coefficients as
+    its elements.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix to create; that is, the result is an n x n
+        matrix.
+    kind : str, optional
+        Must be one of 'symmetric', 'lower', or 'upper'.
+        Default is 'symmetric'.
+    exact : bool, optional
+        If `exact` is True, the result is either an array of type
+        numpy.uint64 (if n < 35) or an object array of Python long integers.
+        If `exact` is False, the coefficients in the matrix are computed using
+        `scipy.special.comb` with ``exact=False``. The result will be a floating
+        point array, and the values in the array will not be the exact
+        coefficients, but this version is much faster than ``exact=True``.
+
+    Returns
+    -------
+    p : (n, n) ndarray
+        The Pascal matrix.
+
+    See Also
+    --------
+    invpascal
+
+    Notes
+    -----
+    See https://en.wikipedia.org/wiki/Pascal_matrix for more information
+    about Pascal matrices.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import pascal
+    >>> pascal(4)
+    array([[ 1,  1,  1,  1],
+           [ 1,  2,  3,  4],
+           [ 1,  3,  6, 10],
+           [ 1,  4, 10, 20]], dtype=uint64)
+    >>> pascal(4, kind='lower')
+    array([[1, 0, 0, 0],
+           [1, 1, 0, 0],
+           [1, 2, 1, 0],
+           [1, 3, 3, 1]], dtype=uint64)
+    >>> pascal(50)[-1, -1]
+    25477612258980856902730428600
+    >>> from scipy.special import comb
+    >>> comb(98, 49, exact=True)
+    25477612258980856902730428600
+
+    """
+
+    from scipy.special import comb
+    if kind not in ['symmetric', 'lower', 'upper']:
+        raise ValueError("kind must be 'symmetric', 'lower', or 'upper'")
+
+    if exact:
+        if n >= 35:
+            L_n = np.empty((n, n), dtype=object)
+            L_n.fill(0)
+        else:
+            L_n = np.zeros((n, n), dtype=np.uint64)
+        for i in range(n):
+            for j in range(i + 1):
+                L_n[i, j] = comb(i, j, exact=True)
+    else:
+        L_n = comb(*np.ogrid[:n, :n])
+
+    if kind == 'lower':
+        p = L_n
+    elif kind == 'upper':
+        p = L_n.T
+    else:
+        p = np.dot(L_n, L_n.T)
+
+    return p
+
+
+def invpascal(n, kind='symmetric', exact=True):
+    """
+    Returns the inverse of the n x n Pascal matrix.
+
+    The Pascal matrix is a matrix containing the binomial coefficients as
+    its elements.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix to create; that is, the result is an n x n
+        matrix.
+    kind : str, optional
+        Must be one of 'symmetric', 'lower', or 'upper'.
+        Default is 'symmetric'.
+    exact : bool, optional
+        If `exact` is True, the result is either an array of type
+        ``numpy.int64`` (if `n` <= 35) or an object array of Python integers.
+        If `exact` is False, the coefficients in the matrix are computed using
+        `scipy.special.comb` with `exact=False`. The result will be a floating
+        point array, and for large `n`, the values in the array will not be the
+        exact coefficients.
+
+    Returns
+    -------
+    invp : (n, n) ndarray
+        The inverse of the Pascal matrix.
+
+    See Also
+    --------
+    pascal
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] "Pascal matrix", https://en.wikipedia.org/wiki/Pascal_matrix
+    .. [2] Cohen, A. M., "The inverse of a Pascal matrix", Mathematical
+           Gazette, 59(408), pp. 111-112, 1975.
+
+    Examples
+    --------
+    >>> from scipy.linalg import invpascal, pascal
+    >>> invp = invpascal(5)
+    >>> invp
+    array([[  5, -10,  10,  -5,   1],
+           [-10,  30, -35,  19,  -4],
+           [ 10, -35,  46, -27,   6],
+           [ -5,  19, -27,  17,  -4],
+           [  1,  -4,   6,  -4,   1]])
+
+    >>> p = pascal(5)
+    >>> p.dot(invp)
+    array([[ 1.,  0.,  0.,  0.,  0.],
+           [ 0.,  1.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  1.,  0.],
+           [ 0.,  0.,  0.,  0.,  1.]])
+
+    An example of the use of `kind` and `exact`:
+
+    >>> invpascal(5, kind='lower', exact=False)
+    array([[ 1., -0.,  0., -0.,  0.],
+           [-1.,  1., -0.,  0., -0.],
+           [ 1., -2.,  1., -0.,  0.],
+           [-1.,  3., -3.,  1., -0.],
+           [ 1., -4.,  6., -4.,  1.]])
+
+    """
+    from scipy.special import comb
+
+    if kind not in ['symmetric', 'lower', 'upper']:
+        raise ValueError("'kind' must be 'symmetric', 'lower' or 'upper'.")
+
+    if kind == 'symmetric':
+        if exact:
+            if n > 34:
+                dt = object
+            else:
+                dt = np.int64
+        else:
+            dt = np.float64
+        invp = np.empty((n, n), dtype=dt)
+        for i in range(n):
+            for j in range(0, i + 1):
+                v = 0
+                for k in range(n - i):
+                    v += comb(i + k, k, exact=exact) * comb(i + k, i + k - j,
+                                                            exact=exact)
+                invp[i, j] = (-1)**(i - j) * v
+                if i != j:
+                    invp[j, i] = invp[i, j]
+    else:
+        # For the 'lower' and 'upper' cases, we computer the inverse by
+        # changing the sign of every other diagonal of the pascal matrix.
+        invp = pascal(n, kind=kind, exact=exact)
+        if invp.dtype == np.uint64:
+            # This cast from np.uint64 to int64 OK, because if `kind` is not
+            # "symmetric", the values in invp are all much less than 2**63.
+            invp = invp.view(np.int64)
+
+        # The toeplitz matrix has alternating bands of 1 and -1.
+        invp *= toeplitz((-1)**np.arange(n)).astype(invp.dtype)
+
+    return invp
+
+
+def dft(n, scale=None):
+    """
+    Discrete Fourier transform matrix.
+
+    Create the matrix that computes the discrete Fourier transform of a
+    sequence [1]_. The nth primitive root of unity used to generate the
+    matrix is exp(-2*pi*i/n), where i = sqrt(-1).
+
+    Parameters
+    ----------
+    n : int
+        Size the matrix to create.
+    scale : str, optional
+        Must be None, 'sqrtn', or 'n'.
+        If `scale` is 'sqrtn', the matrix is divided by `sqrt(n)`.
+        If `scale` is 'n', the matrix is divided by `n`.
+        If `scale` is None (the default), the matrix is not normalized, and the
+        return value is simply the Vandermonde matrix of the roots of unity.
+
+    Returns
+    -------
+    m : (n, n) ndarray
+        The DFT matrix.
+
+    Notes
+    -----
+    When `scale` is None, multiplying a vector by the matrix returned by
+    `dft` is mathematically equivalent to (but much less efficient than)
+    the calculation performed by `scipy.fft.fft`.
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] "DFT matrix", https://en.wikipedia.org/wiki/DFT_matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import dft
+    >>> np.set_printoptions(precision=2, suppress=True)  # for compact output
+    >>> m = dft(5)
+    >>> m
+    array([[ 1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ],
+           [ 1.  +0.j  ,  0.31-0.95j, -0.81-0.59j, -0.81+0.59j,  0.31+0.95j],
+           [ 1.  +0.j  , -0.81-0.59j,  0.31+0.95j,  0.31-0.95j, -0.81+0.59j],
+           [ 1.  +0.j  , -0.81+0.59j,  0.31-0.95j,  0.31+0.95j, -0.81-0.59j],
+           [ 1.  +0.j  ,  0.31+0.95j, -0.81+0.59j, -0.81-0.59j,  0.31-0.95j]])
+    >>> x = np.array([1, 2, 3, 0, 3])
+    >>> m @ x  # Compute the DFT of x
+    array([ 9.  +0.j  ,  0.12-0.81j, -2.12+3.44j, -2.12-3.44j,  0.12+0.81j])
+
+    Verify that ``m @ x`` is the same as ``fft(x)``.
+
+    >>> from scipy.fft import fft
+    >>> fft(x)     # Same result as m @ x
+    array([ 9.  +0.j  ,  0.12-0.81j, -2.12+3.44j, -2.12-3.44j,  0.12+0.81j])
+    """
+    if scale not in [None, 'sqrtn', 'n']:
+        raise ValueError("scale must be None, 'sqrtn', or 'n'; "
+                         f"{scale!r} is not valid.")
+
+    omegas = np.exp(-2j * np.pi * np.arange(n) / n).reshape(-1, 1)
+    m = omegas ** np.arange(n)
+    if scale == 'sqrtn':
+        m /= math.sqrt(n)
+    elif scale == 'n':
+        m /= n
+    return m
+
+
+def fiedler(a):
+    """Returns a symmetric Fiedler matrix
+
+    Given an sequence of numbers `a`, Fiedler matrices have the structure
+    ``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative
+    entries. A Fiedler matrix has a dominant positive eigenvalue and other
+    eigenvalues are negative. Although not valid generally, for certain inputs,
+    the inverse and the determinant can be derived explicitly as given in [1]_.
+
+    Parameters
+    ----------
+    a : (..., n,) array_like
+        Coefficient array. N-dimensional arrays are treated as a batch:
+        each slice along the last axis is a 1-D coefficient array.
+
+    Returns
+    -------
+    F : (..., n, n) ndarray
+        Fiedler matrix. For batch input, each slice of shape ``(n, n)``
+        along the last two dimensions of the output corresponds with a
+        slice of shape ``(n,)`` along the last dimension of the input.
+
+    See Also
+    --------
+    circulant, toeplitz
+
+    Notes
+    -----
+
+    .. versionadded:: 1.3.0
+
+    References
+    ----------
+    .. [1] J. Todd, "Basic Numerical Mathematics: Vol.2 : Numerical Algebra",
+        1977, Birkhauser, :doi:`10.1007/978-3-0348-7286-7`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import det, inv, fiedler
+    >>> a = [1, 4, 12, 45, 77]
+    >>> n = len(a)
+    >>> A = fiedler(a)
+    >>> A
+    array([[ 0,  3, 11, 44, 76],
+           [ 3,  0,  8, 41, 73],
+           [11,  8,  0, 33, 65],
+           [44, 41, 33,  0, 32],
+           [76, 73, 65, 32,  0]])
+
+    The explicit formulas for determinant and inverse seem to hold only for
+    monotonically increasing/decreasing arrays. Note the tridiagonal structure
+    and the corners.
+
+    >>> Ai = inv(A)
+    >>> Ai[np.abs(Ai) < 1e-12] = 0.  # cleanup the numerical noise for display
+    >>> Ai
+    array([[-0.16008772,  0.16666667,  0.        ,  0.        ,  0.00657895],
+           [ 0.16666667, -0.22916667,  0.0625    ,  0.        ,  0.        ],
+           [ 0.        ,  0.0625    , -0.07765152,  0.01515152,  0.        ],
+           [ 0.        ,  0.        ,  0.01515152, -0.03077652,  0.015625  ],
+           [ 0.00657895,  0.        ,  0.        ,  0.015625  , -0.00904605]])
+    >>> det(A)
+    15409151.999999998
+    >>> (-1)**(n-1) * 2**(n-2) * np.diff(a).prod() * (a[-1] - a[0])
+    15409152
+
+    """
+    a = np.atleast_1d(a)
+
+    if a.ndim > 1:
+        return np.apply_along_axis(fiedler, -1, a)
+
+    if a.size == 0:
+        return np.array([], dtype=float)
+    elif a.size == 1:
+        return np.array([[0.]])
+    else:
+        return np.abs(a[:, None] - a)
+
+
+def fiedler_companion(a):
+    """ Returns a Fiedler companion matrix
+
+    Given a polynomial coefficient array ``a``, this function forms a
+    pentadiagonal matrix with a special structure whose eigenvalues coincides
+    with the roots of ``a``.
+
+    Parameters
+    ----------
+    a : (..., N) array_like
+        1-D array of polynomial coefficients in descending order with a nonzero
+        leading coefficient. For ``N < 2``, an empty array is returned.
+        N-dimensional arrays are treated as a batch: each slice along the last
+        axis is a 1-D array of polynomial coefficients.
+
+    Returns
+    -------
+    c : (..., N-1, N-1) ndarray
+        Resulting companion matrix. For batch input, each slice of shape
+        ``(N-1, N-1)`` along the last two dimensions of the output corresponds
+        with a slice of shape ``(N,)`` along the last dimension of the input.
+
+    See Also
+    --------
+    companion
+
+    Notes
+    -----
+    Similar to `companion`, each leading coefficient along the last axis of the
+    input should be nonzero.
+    If the leading coefficient is not 1, other coefficients are rescaled before
+    the array generation. To avoid numerical issues, it is best to provide a
+    monic polynomial.
+
+    .. versionadded:: 1.3.0
+
+    References
+    ----------
+    .. [1] M. Fiedler, " A note on companion matrices", Linear Algebra and its
+        Applications, 2003, :doi:`10.1016/S0024-3795(03)00548-2`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import fiedler_companion, eigvals
+    >>> p = np.poly(np.arange(1, 9, 2))  # [1., -16., 86., -176., 105.]
+    >>> fc = fiedler_companion(p)
+    >>> fc
+    array([[  16.,  -86.,    1.,    0.],
+           [   1.,    0.,    0.,    0.],
+           [   0.,  176.,    0., -105.],
+           [   0.,    1.,    0.,    0.]])
+    >>> eigvals(fc)
+    array([7.+0.j, 5.+0.j, 3.+0.j, 1.+0.j])
+
+    """
+    a = np.atleast_1d(a)
+
+    if a.ndim > 1:
+        return np.apply_along_axis(fiedler_companion, -1, a)
+
+    if a.size <= 2:
+        if a.size == 2:
+            return np.array([[-(a/a[0])[-1]]])
+        return np.array([], dtype=a.dtype)
+
+    if a[0] == 0.:
+        raise ValueError('Leading coefficient is zero.')
+
+    a = a/a[0]
+    n = a.size - 1
+    c = np.zeros((n, n), dtype=a.dtype)
+    # subdiagonals
+    c[range(3, n, 2), range(1, n-2, 2)] = 1.
+    c[range(2, n, 2), range(1, n-1, 2)] = -a[3::2]
+    # superdiagonals
+    c[range(0, n-2, 2), range(2, n, 2)] = 1.
+    c[range(0, n-1, 2), range(1, n, 2)] = -a[2::2]
+    c[[0, 1], 0] = [-a[1], 1]
+
+    return c
+
+
+def convolution_matrix(a, n, mode='full'):
+    """
+    Construct a convolution matrix.
+
+    Constructs the Toeplitz matrix representing one-dimensional
+    convolution [1]_.  See the notes below for details.
+
+    Parameters
+    ----------
+    a : (..., m) array_like
+        The 1-D array to convolve. N-dimensional arrays are treated as a
+        batch: each slice along the last axis is a 1-D array to convolve.
+    n : int
+        The number of columns in the resulting matrix.  It gives the length
+        of the input to be convolved with `a`.  This is analogous to the
+        length of `v` in ``numpy.convolve(a, v)``.
+    mode : str
+        This is analogous to `mode` in ``numpy.convolve(v, a, mode)``.
+        It must be one of ('full', 'valid', 'same').
+        See below for how `mode` determines the shape of the result.
+
+    Returns
+    -------
+    A : (..., k, n) ndarray
+        The convolution matrix whose row count `k` depends on `mode`::
+
+            =======  =========================
+             mode    k
+            =======  =========================
+            'full'   m + n -1
+            'same'   max(m, n)
+            'valid'  max(m, n) - min(m, n) + 1
+            =======  =========================
+
+        For batch input, each slice of shape ``(k, n)`` along the last two
+        dimensions of the output corresponds with a slice of shape ``(m,)``
+        along the last dimension of the input.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+
+    Notes
+    -----
+    The code::
+
+        A = convolution_matrix(a, n, mode)
+
+    creates a Toeplitz matrix `A` such that ``A @ v`` is equivalent to
+    using ``convolve(a, v, mode)``.  The returned array always has `n`
+    columns.  The number of rows depends on the specified `mode`, as
+    explained above.
+
+    In the default 'full' mode, the entries of `A` are given by::
+
+        A[i, j] == (a[i-j] if (0 <= (i-j) < m) else 0)
+
+    where ``m = len(a)``.  Suppose, for example, the input array is
+    ``[x, y, z]``.  The convolution matrix has the form::
+
+        [x, 0, 0, ..., 0, 0]
+        [y, x, 0, ..., 0, 0]
+        [z, y, x, ..., 0, 0]
+        ...
+        [0, 0, 0, ..., x, 0]
+        [0, 0, 0, ..., y, x]
+        [0, 0, 0, ..., z, y]
+        [0, 0, 0, ..., 0, z]
+
+    In 'valid' mode, the entries of `A` are given by::
+
+        A[i, j] == (a[i-j+m-1] if (0 <= (i-j+m-1) < m) else 0)
+
+    This corresponds to a matrix whose rows are the subset of those from
+    the 'full' case where all the coefficients in `a` are contained in the
+    row.  For input ``[x, y, z]``, this array looks like::
+
+        [z, y, x, 0, 0, ..., 0, 0, 0]
+        [0, z, y, x, 0, ..., 0, 0, 0]
+        [0, 0, z, y, x, ..., 0, 0, 0]
+        ...
+        [0, 0, 0, 0, 0, ..., x, 0, 0]
+        [0, 0, 0, 0, 0, ..., y, x, 0]
+        [0, 0, 0, 0, 0, ..., z, y, x]
+
+    In the 'same' mode, the entries of `A` are given by::
+
+        d = (m - 1) // 2
+        A[i, j] == (a[i-j+d] if (0 <= (i-j+d) < m) else 0)
+
+    The typical application of the 'same' mode is when one has a signal of
+    length `n` (with `n` greater than ``len(a)``), and the desired output
+    is a filtered signal that is still of length `n`.
+
+    For input ``[x, y, z]``, this array looks like::
+
+        [y, x, 0, 0, ..., 0, 0, 0]
+        [z, y, x, 0, ..., 0, 0, 0]
+        [0, z, y, x, ..., 0, 0, 0]
+        [0, 0, z, y, ..., 0, 0, 0]
+        ...
+        [0, 0, 0, 0, ..., y, x, 0]
+        [0, 0, 0, 0, ..., z, y, x]
+        [0, 0, 0, 0, ..., 0, z, y]
+
+    .. versionadded:: 1.5.0
+
+    References
+    ----------
+    .. [1] "Convolution", https://en.wikipedia.org/wiki/Convolution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import convolution_matrix
+    >>> A = convolution_matrix([-1, 4, -2], 5, mode='same')
+    >>> A
+    array([[ 4, -1,  0,  0,  0],
+           [-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1],
+           [ 0,  0,  0, -2,  4]])
+
+    Compare multiplication by `A` with the use of `numpy.convolve`.
+
+    >>> x = np.array([1, 2, 0, -3, 0.5])
+    >>> A @ x
+    array([  2. ,   6. ,  -1. , -12.5,   8. ])
+
+    Verify that ``A @ x`` produced the same result as applying the
+    convolution function.
+
+    >>> np.convolve([-1, 4, -2], x, mode='same')
+    array([  2. ,   6. ,  -1. , -12.5,   8. ])
+
+    For comparison to the case ``mode='same'`` shown above, here are the
+    matrices produced by ``mode='full'`` and ``mode='valid'`` for the
+    same coefficients and size.
+
+    >>> convolution_matrix([-1, 4, -2], 5, mode='full')
+    array([[-1,  0,  0,  0,  0],
+           [ 4, -1,  0,  0,  0],
+           [-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1],
+           [ 0,  0,  0, -2,  4],
+           [ 0,  0,  0,  0, -2]])
+
+    >>> convolution_matrix([-1, 4, -2], 5, mode='valid')
+    array([[-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1]])
+    """
+    if n <= 0:
+        raise ValueError('n must be a positive integer.')
+
+    a = np.asarray(a)
+
+    if a.size == 0:
+        raise ValueError('len(a) must be at least 1.')
+
+    if mode not in ('full', 'valid', 'same'):
+        raise ValueError(
+            "'mode' argument must be one of ('full', 'valid', 'same')")
+
+    if a.ndim > 1:
+        return np.apply_along_axis(lambda a: convolution_matrix(a, n, mode), -1, a)
+
+    # create zero padded versions of the array
+    az = np.pad(a, (0, n-1), 'constant')
+    raz = np.pad(a[::-1], (0, n-1), 'constant')
+
+    if mode == 'same':
+        trim = min(n, len(a)) - 1
+        tb = trim//2
+        te = trim - tb
+        col0 = az[tb:len(az)-te]
+        row0 = raz[-n-tb:len(raz)-tb]
+    elif mode == 'valid':
+        tb = min(n, len(a)) - 1
+        te = tb
+        col0 = az[tb:len(az)-te]
+        row0 = raz[-n-tb:len(raz)-tb]
+    else:  # 'full'
+        col0 = az
+        row0 = raz[-n:]
+    return toeplitz(col0, row0)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py b/venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6d01d2b6e59b040f39c0b53cc2788bbd3d0888f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py
@@ -0,0 +1,65 @@
+import numpy as np
+
+
+class _FakeMatrix:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+class _FakeMatrix2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        if copy:
+            return self._data.copy()
+        return self._data
+
+
+def _get_array(shape, dtype):
+    """
+    Get a test array of given shape and data type.
+    Returned NxN matrices are posdef, and 2xN are banded-posdef.
+
+    """
+    if len(shape) == 2 and shape[0] == 2:
+        # yield a banded positive definite one
+        x = np.zeros(shape, dtype=dtype)
+        x[0, 1:] = -1
+        x[1] = 2
+        return x
+    elif len(shape) == 2 and shape[0] == shape[1]:
+        # always yield a positive definite matrix
+        x = np.zeros(shape, dtype=dtype)
+        j = np.arange(shape[0])
+        x[j, j] = 2
+        x[j[:-1], j[:-1]+1] = -1
+        x[j[:-1]+1, j[:-1]] = -1
+        return x
+    else:
+        np.random.seed(1234)
+        return np.random.randn(*shape).astype(dtype)
+
+
+def _id(x):
+    return x
+
+
+def assert_no_overwrite(call, shapes, dtypes=None):
+    """
+    Test that a call does not overwrite its input arguments
+    """
+
+    if dtypes is None:
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+
+    for dtype in dtypes:
+        for order in ["C", "F"]:
+            for faker in [_id, _FakeMatrix, _FakeMatrix2]:
+                orig_inputs = [_get_array(s, dtype) for s in shapes]
+                inputs = [faker(x.copy(order)) for x in orig_inputs]
+                call(*inputs)
+                msg = f"call modified inputs [{dtype!r}, {faker!r}]"
+                for a, b in zip(inputs, orig_inputs):
+                    np.testing.assert_equal(a, b, err_msg=msg)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/basic.py b/venv/lib/python3.10/site-packages/scipy/linalg/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..04ef3645a2ed6a22106ed8ca1acf9e9ac93df5cf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/basic.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+    'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+    'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz',
+    'get_lapack_funcs', 'LinAlgError', 'LinAlgWarning',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="basic",
+                                   private_modules=["_basic"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/blas.py b/venv/lib/python3.10/site-packages/scipy/linalg/blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..c943460e6bafcd9a382586d5a5155357382ea596
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/blas.py
@@ -0,0 +1,484 @@
+"""
+Low-level BLAS functions (:mod:`scipy.linalg.blas`)
+===================================================
+
+This module contains low-level functions from the BLAS library.
+
+.. versionadded:: 0.12.0
+
+.. note::
+
+   The common ``overwrite_<>`` option in many routines, allows the
+   input arrays to be overwritten to avoid extra memory allocation.
+   However this requires the array to satisfy two conditions
+   which are memory order and the data type to match exactly the
+   order and the type expected by the routine.
+
+   As an example, if you pass a double precision float array to any
+   ``S....`` routine which expects single precision arguments, f2py
+   will create an intermediate array to match the argument types and
+   overwriting will be performed on that intermediate array.
+
+   Similarly, if a C-contiguous array is passed, f2py will pass a
+   FORTRAN-contiguous array internally. Please make sure that these
+   details are satisfied. More information can be found in the f2py
+   documentation.
+
+.. warning::
+
+   These functions do little to no error checking.
+   It is possible to cause crashes by mis-using them,
+   so prefer using the higher-level routines in `scipy.linalg`.
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   find_best_blas_type
+
+BLAS Level 1 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   caxpy
+   ccopy
+   cdotc
+   cdotu
+   crotg
+   cscal
+   csrot
+   csscal
+   cswap
+   dasum
+   daxpy
+   dcopy
+   ddot
+   dnrm2
+   drot
+   drotg
+   drotm
+   drotmg
+   dscal
+   dswap
+   dzasum
+   dznrm2
+   icamax
+   idamax
+   isamax
+   izamax
+   sasum
+   saxpy
+   scasum
+   scnrm2
+   scopy
+   sdot
+   snrm2
+   srot
+   srotg
+   srotm
+   srotmg
+   sscal
+   sswap
+   zaxpy
+   zcopy
+   zdotc
+   zdotu
+   zdrot
+   zdscal
+   zrotg
+   zscal
+   zswap
+
+BLAS Level 2 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbmv
+   sgemv
+   sger
+   ssbmv
+   sspr
+   sspr2
+   ssymv
+   ssyr
+   ssyr2
+   stbmv
+   stpsv
+   strmv
+   strsv
+   dgbmv
+   dgemv
+   dger
+   dsbmv
+   dspr
+   dspr2
+   dsymv
+   dsyr
+   dsyr2
+   dtbmv
+   dtpsv
+   dtrmv
+   dtrsv
+   cgbmv
+   cgemv
+   cgerc
+   cgeru
+   chbmv
+   chemv
+   cher
+   cher2
+   chpmv
+   chpr
+   chpr2
+   ctbmv
+   ctbsv
+   ctpmv
+   ctpsv
+   ctrmv
+   ctrsv
+   csyr
+   zgbmv
+   zgemv
+   zgerc
+   zgeru
+   zhbmv
+   zhemv
+   zher
+   zher2
+   zhpmv
+   zhpr
+   zhpr2
+   ztbmv
+   ztbsv
+   ztpmv
+   ztrmv
+   ztrsv
+   zsyr
+
+BLAS Level 3 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgemm
+   ssymm
+   ssyr2k
+   ssyrk
+   strmm
+   strsm
+   dgemm
+   dsymm
+   dsyr2k
+   dsyrk
+   dtrmm
+   dtrsm
+   cgemm
+   chemm
+   cher2k
+   cherk
+   csymm
+   csyr2k
+   csyrk
+   ctrmm
+   ctrsm
+   zgemm
+   zhemm
+   zher2k
+   zherk
+   zsymm
+   zsyr2k
+   zsyrk
+   ztrmm
+   ztrsm
+
+"""
+#
+# Author: Pearu Peterson, March 2002
+#         refactoring by Fabian Pedregosa, March 2010
+#
+
+__all__ = ['get_blas_funcs', 'find_best_blas_type']
+
+import numpy as np
+import functools
+
+from scipy.linalg import _fblas
+try:
+    from scipy.linalg import _cblas
+except ImportError:
+    _cblas = None
+
+try:
+    from scipy.linalg import _fblas_64
+    HAS_ILP64 = True
+except ImportError:
+    HAS_ILP64 = False
+    _fblas_64 = None
+
+# Expose all functions (only fblas --- cblas is an implementation detail)
+empty_module = None
+from scipy.linalg._fblas import *  # noqa: E402, F403
+del empty_module
+
+# all numeric dtypes '?bBhHiIlLqQefdgFDGO' that are safe to be converted to
+
+# single precision float   : '?bBhH!!!!!!ef!!!!!!'
+# double precision float   : '?bBhHiIlLqQefdg!!!!'
+# single precision complex : '?bBhH!!!!!!ef!!F!!!'
+# double precision complex : '?bBhHiIlLqQefdgFDG!'
+
+_type_score = {x: 1 for x in '?bBhHef'}
+_type_score.update({x: 2 for x in 'iIlLqQd'})
+
+# Handle float128(g) and complex256(G) separately in case non-Windows systems.
+# On Windows, the values will be rewritten to the same key with the same value.
+_type_score.update({'F': 3, 'D': 4, 'g': 2, 'G': 4})
+
+# Final mapping to the actual prefixes and dtypes
+_type_conv = {1: ('s', np.dtype('float32')),
+              2: ('d', np.dtype('float64')),
+              3: ('c', np.dtype('complex64')),
+              4: ('z', np.dtype('complex128'))}
+
+# some convenience alias for complex functions
+_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2',
+               'cdot': 'cdotc', 'zdot': 'zdotc',
+               'cger': 'cgerc', 'zger': 'zgerc',
+               'sdotc': 'sdot', 'sdotu': 'sdot',
+               'ddotc': 'ddot', 'ddotu': 'ddot'}
+
+
+def find_best_blas_type(arrays=(), dtype=None):
+    """Find best-matching BLAS/LAPACK type.
+
+    Arrays are used to determine the optimal prefix of BLAS routines.
+
+    Parameters
+    ----------
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of BLAS
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    Returns
+    -------
+    prefix : str
+        BLAS/LAPACK prefix character.
+    dtype : dtype
+        Inferred Numpy data type.
+    prefer_fortran : bool
+        Whether to prefer Fortran order routines over C order.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.linalg.blas as bla
+    >>> rng = np.random.default_rng()
+    >>> a = rng.random((10,15))
+    >>> b = np.asfortranarray(a)  # Change the memory layout order
+    >>> bla.find_best_blas_type((a,))
+    ('d', dtype('float64'), False)
+    >>> bla.find_best_blas_type((a*1j,))
+    ('z', dtype('complex128'), False)
+    >>> bla.find_best_blas_type((b,))
+    ('d', dtype('float64'), True)
+
+    """
+    dtype = np.dtype(dtype)
+    max_score = _type_score.get(dtype.char, 5)
+    prefer_fortran = False
+
+    if arrays:
+        # In most cases, single element is passed through, quicker route
+        if len(arrays) == 1:
+            max_score = _type_score.get(arrays[0].dtype.char, 5)
+            prefer_fortran = arrays[0].flags['FORTRAN']
+        else:
+            # use the most generic type in arrays
+            scores = [_type_score.get(x.dtype.char, 5) for x in arrays]
+            max_score = max(scores)
+            ind_max_score = scores.index(max_score)
+            # safe upcasting for mix of float64 and complex64 --> prefix 'z'
+            if max_score == 3 and (2 in scores):
+                max_score = 4
+
+            if arrays[ind_max_score].flags['FORTRAN']:
+                # prefer Fortran for leading array with column major order
+                prefer_fortran = True
+
+    # Get the LAPACK prefix and the corresponding dtype if not fall back
+    # to 'd' and double precision float.
+    prefix, dtype = _type_conv.get(max_score, ('d', np.dtype('float64')))
+
+    return prefix, dtype, prefer_fortran
+
+
+def _get_funcs(names, arrays, dtype,
+               lib_name, fmodule, cmodule,
+               fmodule_name, cmodule_name, alias,
+               ilp64=False):
+    """
+    Return available BLAS/LAPACK functions.
+
+    Used also in lapack.py. See get_blas_funcs for docstring.
+    """
+
+    funcs = []
+    unpack = False
+    dtype = np.dtype(dtype)
+    module1 = (cmodule, cmodule_name)
+    module2 = (fmodule, fmodule_name)
+
+    if isinstance(names, str):
+        names = (names,)
+        unpack = True
+
+    prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype)
+
+    if prefer_fortran:
+        module1, module2 = module2, module1
+
+    for name in names:
+        func_name = prefix + name
+        func_name = alias.get(func_name, func_name)
+        func = getattr(module1[0], func_name, None)
+        module_name = module1[1]
+        if func is None:
+            func = getattr(module2[0], func_name, None)
+            module_name = module2[1]
+        if func is None:
+            raise ValueError(
+                f'{lib_name} function {func_name} could not be found')
+        func.module_name, func.typecode = module_name, prefix
+        func.dtype = dtype
+        if not ilp64:
+            func.int_dtype = np.dtype(np.intc)
+        else:
+            func.int_dtype = np.dtype(np.int64)
+        func.prefix = prefix  # Backward compatibility
+        funcs.append(func)
+
+    if unpack:
+        return funcs[0]
+    else:
+        return funcs
+
+
+def _memoize_get_funcs(func):
+    """
+    Memoized fast path for _get_funcs instances
+    """
+    memo = {}
+    func.memo = memo
+
+    @functools.wraps(func)
+    def getter(names, arrays=(), dtype=None, ilp64=False):
+        key = (names, dtype, ilp64)
+        for array in arrays:
+            # cf. find_blas_funcs
+            key += (array.dtype.char, array.flags.fortran)
+
+        try:
+            value = memo.get(key)
+        except TypeError:
+            # unhashable key etc.
+            key = None
+            value = None
+
+        if value is not None:
+            return value
+
+        value = func(names, arrays, dtype, ilp64)
+
+        if key is not None:
+            memo[key] = value
+
+        return value
+
+    return getter
+
+
+@_memoize_get_funcs
+def get_blas_funcs(names, arrays=(), dtype=None, ilp64=False):
+    """Return available BLAS function objects from names.
+
+    Arrays are used to determine the optimal prefix of BLAS routines.
+
+    Parameters
+    ----------
+    names : str or sequence of str
+        Name(s) of BLAS functions without type prefix.
+
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of BLAS
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    ilp64 : {True, False, 'preferred'}, optional
+        Whether to return ILP64 routine variant.
+        Choosing 'preferred' returns ILP64 routine if available,
+        and otherwise the 32-bit routine. Default: False
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+
+    Notes
+    -----
+    This routine automatically chooses between Fortran/C
+    interfaces. Fortran code is used whenever possible for arrays with
+    column major order. In all other cases, C code is preferred.
+
+    In BLAS, the naming convention is that all functions start with a
+    type prefix, which depends on the type of the principal
+    matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy
+    types {float32, float64, complex64, complex128} respectively.
+    The code and the dtype are stored in attributes `typecode` and `dtype`
+    of the returned functions.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.linalg as LA
+    >>> rng = np.random.default_rng()
+    >>> a = rng.random((3,2))
+    >>> x_gemv = LA.get_blas_funcs('gemv', (a,))
+    >>> x_gemv.typecode
+    'd'
+    >>> x_gemv = LA.get_blas_funcs('gemv',(a*1j,))
+    >>> x_gemv.typecode
+    'z'
+
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError("Invalid value for 'ilp64'")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "BLAS", _fblas, _cblas, "fblas", "cblas",
+                          _blas_alias, ilp64=False)
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("BLAS ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit BLAS")
+        return _get_funcs(names, arrays, dtype,
+                          "BLAS", _fblas_64, None, "fblas_64", None,
+                          _blas_alias, ilp64=True)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd b/venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7ed44f6ea8611f926e3ea5fd2670446cdf9b398c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
@@ -0,0 +1,169 @@
+"""
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+"""
+
+# Within scipy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_blas
+# from scipy.linalg cimport cython_blas
+# cimport scipy.linalg.cython_blas as cython_blas
+# cimport ..linalg.cython_blas as cython_blas
+
+# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+ctypedef float s
+ctypedef double d
+ctypedef float complex c
+ctypedef double complex z
+
+cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
+cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil
+cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil
+cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil
+cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil
+cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil
+cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil
+cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil
+cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil
+cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil
+cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
+cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
+cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef d dasum(int *n, d *dx, int *incx) noexcept nogil
+cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef d dcabs1(z *z) noexcept nogil
+cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
+cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil
+cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil
+cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil
+cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil
+cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil
+cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil
+cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil
+cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil
+cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil
+cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
+cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
+cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
+cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil
+cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil
+cdef int icamax(int *n, c *cx, int *incx) noexcept nogil
+cdef int idamax(int *n, d *dx, int *incx) noexcept nogil
+cdef int isamax(int *n, s *sx, int *incx) noexcept nogil
+cdef int izamax(int *n, z *zx, int *incx) noexcept nogil
+cdef bint lsame(char *ca, char *cb) noexcept nogil
+cdef s sasum(int *n, s *sx, int *incx) noexcept nogil
+cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s scasum(int *n, c *cx, int *incx) noexcept nogil
+cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil
+cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
+cdef s snrm2(int *n, s *x, int *incx) noexcept nogil
+cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil
+cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil
+cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil
+cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil
+cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil
+cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil
+cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil
+cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil
+cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
+cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil
+cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
+cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
+cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil
+cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil
+cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
+cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil
+cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil
+cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil
+cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil
+cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil
+cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil
+cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil
+cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
+cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
+cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx b/venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..35286fe11d72226269c0e459d9a3109151f74a4a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
@@ -0,0 +1,1432 @@
+# This file was generated by _generate_pyx.py.
+# Do not edit this file directly.
+# cython: boundscheck = False
+# cython: wraparound = False
+# cython: cdivision = True
+
+"""
+BLAS Functions for Cython
+=========================
+
+Usable from Cython via::
+
+    cimport scipy.linalg.cython_blas
+
+These wrappers do not check for alignment of arrays.
+Alignment should be checked before these wrappers are used.
+
+If using ``cdotu``, ``cdotc``, ``zdotu``, ``zdotc``, ``sladiv``, or ``dladiv``,
+the ``CYTHON_CCOMPLEX`` define must be set to 0 during compilation. For
+example, in a ``meson.build`` file when using Meson::
+
+    py.extension_module('ext_module'
+        'ext_module.pyx',
+        c_args: ['-DCYTHON_CCOMPLEX=0'],
+        ...
+    )
+
+Raw function pointers (Fortran-style pointer arguments):
+
+- caxpy
+- ccopy
+- cdotc
+- cdotu
+- cgbmv
+- cgemm
+- cgemv
+- cgerc
+- cgeru
+- chbmv
+- chemm
+- chemv
+- cher
+- cher2
+- cher2k
+- cherk
+- chpmv
+- chpr
+- chpr2
+- crotg
+- cscal
+- csrot
+- csscal
+- cswap
+- csymm
+- csyr2k
+- csyrk
+- ctbmv
+- ctbsv
+- ctpmv
+- ctpsv
+- ctrmm
+- ctrmv
+- ctrsm
+- ctrsv
+- dasum
+- daxpy
+- dcabs1
+- dcopy
+- ddot
+- dgbmv
+- dgemm
+- dgemv
+- dger
+- dnrm2
+- drot
+- drotg
+- drotm
+- drotmg
+- dsbmv
+- dscal
+- dsdot
+- dspmv
+- dspr
+- dspr2
+- dswap
+- dsymm
+- dsymv
+- dsyr
+- dsyr2
+- dsyr2k
+- dsyrk
+- dtbmv
+- dtbsv
+- dtpmv
+- dtpsv
+- dtrmm
+- dtrmv
+- dtrsm
+- dtrsv
+- dzasum
+- dznrm2
+- icamax
+- idamax
+- isamax
+- izamax
+- lsame
+- sasum
+- saxpy
+- scasum
+- scnrm2
+- scopy
+- sdot
+- sdsdot
+- sgbmv
+- sgemm
+- sgemv
+- sger
+- snrm2
+- srot
+- srotg
+- srotm
+- srotmg
+- ssbmv
+- sscal
+- sspmv
+- sspr
+- sspr2
+- sswap
+- ssymm
+- ssymv
+- ssyr
+- ssyr2
+- ssyr2k
+- ssyrk
+- stbmv
+- stbsv
+- stpmv
+- stpsv
+- strmm
+- strmv
+- strsm
+- strsv
+- zaxpy
+- zcopy
+- zdotc
+- zdotu
+- zdrot
+- zdscal
+- zgbmv
+- zgemm
+- zgemv
+- zgerc
+- zgeru
+- zhbmv
+- zhemm
+- zhemv
+- zher
+- zher2
+- zher2k
+- zherk
+- zhpmv
+- zhpr
+- zhpr2
+- zrotg
+- zscal
+- zswap
+- zsymm
+- zsyr2k
+- zsyrk
+- ztbmv
+- ztbsv
+- ztpmv
+- ztpsv
+- ztrmm
+- ztrmv
+- ztrsm
+- ztrsv
+
+
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_blas
+# from scipy.linalg cimport cython_blas
+# cimport scipy.linalg.cython_blas as cython_blas
+# cimport ..linalg.cython_blas as cython_blas
+
+# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+cdef extern from "fortran_defs.h":
+    pass
+
+from numpy cimport npy_complex64, npy_complex128
+
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_caxpy "BLAS_FUNC(caxpy)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_caxpy(n, ca, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ccopy "BLAS_FUNC(ccopy)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_ccopy(n, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cdotc "F_FUNC(cdotcwrp,CDOTCWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    cdef c out
+    _fortran_cdotc(&out, n, cx, incx, cy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cdotu "F_FUNC(cdotuwrp,CDOTUWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    cdef c out
+    _fortran_cdotu(&out, n, cx, incx, cy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgbmv "BLAS_FUNC(cgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgemm "BLAS_FUNC(cgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_cgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgemv "BLAS_FUNC(cgemv)"(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgerc "BLAS_FUNC(cgerc)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cgerc(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgeru "BLAS_FUNC(cgeru)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cgeru(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chbmv "BLAS_FUNC(chbmv)"(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chemm "BLAS_FUNC(chemm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_chemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chemv "BLAS_FUNC(chemv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher "BLAS_FUNC(cher)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
+cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cher(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher2 "BLAS_FUNC(cher2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cher2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher2k "BLAS_FUNC(cher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *beta, npy_complex64 *c, int *ldc) nogil
+cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_cher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cherk "BLAS_FUNC(cherk)"(char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c, int *ldc) nogil
+cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_cherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpmv "BLAS_FUNC(chpmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chpmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpr "BLAS_FUNC(chpr)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
+cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil:
+    
+    _fortran_chpr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpr2 "BLAS_FUNC(chpr2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap) nogil
+cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil:
+    
+    _fortran_chpr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_crotg "BLAS_FUNC(crotg)"(npy_complex64 *ca, npy_complex64 *cb, s *c, npy_complex64 *s) nogil
+cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil:
+    
+    _fortran_crotg(ca, cb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cscal "BLAS_FUNC(cscal)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx) nogil
+cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil:
+    
+    _fortran_cscal(n, ca, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csrot "BLAS_FUNC(csrot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, s *s) nogil
+cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil:
+    
+    _fortran_csrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csscal "BLAS_FUNC(csscal)"(int *n, s *sa, npy_complex64 *cx, int *incx) nogil
+cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil:
+    
+    _fortran_csscal(n, sa, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cswap "BLAS_FUNC(cswap)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_cswap(n, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csymm "BLAS_FUNC(csymm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_csymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csyr2k "BLAS_FUNC(csyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_csyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csyrk "BLAS_FUNC(csyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_csyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctbmv "BLAS_FUNC(ctbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctbsv "BLAS_FUNC(ctbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctpmv "BLAS_FUNC(ctpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
+cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctpsv "BLAS_FUNC(ctpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
+cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrmm "BLAS_FUNC(ctrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_ctrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrmv "BLAS_FUNC(ctrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrsm "BLAS_FUNC(ctrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_ctrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrsv "BLAS_FUNC(ctrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dasum "BLAS_FUNC(dasum)"(int *n, d *dx, int *incx) nogil
+cdef d dasum(int *n, d *dx, int *incx) noexcept nogil:
+    
+    return _fortran_dasum(n, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_daxpy "BLAS_FUNC(daxpy)"(int *n, d *da, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_daxpy(n, da, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dcabs1 "BLAS_FUNC(dcabs1)"(npy_complex128 *z) nogil
+cdef d dcabs1(z *z) noexcept nogil:
+    
+    return _fortran_dcabs1(z)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dcopy "BLAS_FUNC(dcopy)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_dcopy(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_ddot "BLAS_FUNC(ddot)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    return _fortran_ddot(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgbmv "BLAS_FUNC(dgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgemm "BLAS_FUNC(dgemm)"(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
+cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgemv "BLAS_FUNC(dgemv)"(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dger "BLAS_FUNC(dger)"(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
+cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dger(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dnrm2 "BLAS_FUNC(dnrm2)"(int *n, d *x, int *incx) nogil
+cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil:
+    
+    return _fortran_dnrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drot "BLAS_FUNC(drot)"(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) nogil
+cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil:
+    
+    _fortran_drot(n, dx, incx, dy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotg "BLAS_FUNC(drotg)"(d *da, d *db, d *c, d *s) nogil
+cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil:
+    
+    _fortran_drotg(da, db, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotm "BLAS_FUNC(drotm)"(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) nogil
+cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil:
+    
+    _fortran_drotm(n, dx, incx, dy, incy, dparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotmg "BLAS_FUNC(drotmg)"(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) nogil
+cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil:
+    
+    _fortran_drotmg(dd1, dd2, dx1, dy1, dparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsbmv "BLAS_FUNC(dsbmv)"(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dsbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dscal "BLAS_FUNC(dscal)"(int *n, d *da, d *dx, int *incx) nogil
+cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil:
+    
+    _fortran_dscal(n, da, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dsdot "BLAS_FUNC(dsdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_dsdot(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspmv "BLAS_FUNC(dspmv)"(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspr "BLAS_FUNC(dspr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) nogil
+cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil:
+    
+    _fortran_dspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspr2 "BLAS_FUNC(dspr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) nogil
+cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil:
+    
+    _fortran_dspr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dswap "BLAS_FUNC(dswap)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_dswap(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsymm "BLAS_FUNC(dsymm)"(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
+cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsymv "BLAS_FUNC(dsymv)"(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr "BLAS_FUNC(dsyr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) nogil
+cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dsyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr2 "BLAS_FUNC(dsyr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
+cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dsyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr2k "BLAS_FUNC(dsyr2k)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
+cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyrk "BLAS_FUNC(dsyrk)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) nogil
+cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtbmv "BLAS_FUNC(dtbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtbsv "BLAS_FUNC(dtbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtpmv "BLAS_FUNC(dtpmv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
+cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtpsv "BLAS_FUNC(dtpsv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
+cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrmm "BLAS_FUNC(dtrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrmv "BLAS_FUNC(dtrmv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrsm "BLAS_FUNC(dtrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrsv "BLAS_FUNC(dtrsv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dzasum "BLAS_FUNC(dzasum)"(int *n, npy_complex128 *zx, int *incx) nogil
+cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil:
+    
+    return _fortran_dzasum(n, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dznrm2 "BLAS_FUNC(dznrm2)"(int *n, npy_complex128 *x, int *incx) nogil
+cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil:
+    
+    return _fortran_dznrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_icamax "BLAS_FUNC(icamax)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef int icamax(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_icamax(n, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_idamax "BLAS_FUNC(idamax)"(int *n, d *dx, int *incx) nogil
+cdef int idamax(int *n, d *dx, int *incx) noexcept nogil:
+    
+    return _fortran_idamax(n, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_isamax "BLAS_FUNC(isamax)"(int *n, s *sx, int *incx) nogil
+cdef int isamax(int *n, s *sx, int *incx) noexcept nogil:
+    
+    return _fortran_isamax(n, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_izamax "BLAS_FUNC(izamax)"(int *n, npy_complex128 *zx, int *incx) nogil
+cdef int izamax(int *n, z *zx, int *incx) noexcept nogil:
+    
+    return _fortran_izamax(n, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    bint _fortran_lsame "BLAS_FUNC(lsame)"(char *ca, char *cb) nogil
+cdef bint lsame(char *ca, char *cb) noexcept nogil:
+    
+    return _fortran_lsame(ca, cb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sasum "BLAS_FUNC(sasum)"(int *n, s *sx, int *incx) nogil
+cdef s sasum(int *n, s *sx, int *incx) noexcept nogil:
+    
+    return _fortran_sasum(n, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_saxpy "BLAS_FUNC(saxpy)"(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_saxpy(n, sa, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_scasum "BLAS_FUNC(scasum)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef s scasum(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_scasum(n, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_scnrm2 "BLAS_FUNC(scnrm2)"(int *n, npy_complex64 *x, int *incx) nogil
+cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil:
+    
+    return _fortran_scnrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_scopy "BLAS_FUNC(scopy)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_scopy(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sdot "BLAS_FUNC(sdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_sdot(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sdsdot "BLAS_FUNC(sdsdot)"(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) nogil
+cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_sdsdot(n, sb, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgbmv "BLAS_FUNC(sgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgemm "BLAS_FUNC(sgemm)"(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
+cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_sgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgemv "BLAS_FUNC(sgemv)"(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sger "BLAS_FUNC(sger)"(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
+cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
+    
+    _fortran_sger(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_snrm2 "BLAS_FUNC(snrm2)"(int *n, s *x, int *incx) nogil
+cdef s snrm2(int *n, s *x, int *incx) noexcept nogil:
+    
+    return _fortran_snrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srot "BLAS_FUNC(srot)"(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) nogil
+cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil:
+    
+    _fortran_srot(n, sx, incx, sy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotg "BLAS_FUNC(srotg)"(s *sa, s *sb, s *c, s *s) nogil
+cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil:
+    
+    _fortran_srotg(sa, sb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotm "BLAS_FUNC(srotm)"(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) nogil
+cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil:
+    
+    _fortran_srotm(n, sx, incx, sy, incy, sparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotmg "BLAS_FUNC(srotmg)"(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) nogil
+cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil:
+    
+    _fortran_srotmg(sd1, sd2, sx1, sy1, sparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssbmv "BLAS_FUNC(ssbmv)"(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_ssbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sscal "BLAS_FUNC(sscal)"(int *n, s *sa, s *sx, int *incx) nogil
+cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil:
+    
+    _fortran_sscal(n, sa, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspmv "BLAS_FUNC(sspmv)"(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspr "BLAS_FUNC(sspr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) nogil
+cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil:
+    
+    _fortran_sspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspr2 "BLAS_FUNC(sspr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) nogil
+cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil:
+    
+    _fortran_sspr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sswap "BLAS_FUNC(sswap)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_sswap(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssymm "BLAS_FUNC(ssymm)"(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
+cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_ssymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssymv "BLAS_FUNC(ssymv)"(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_ssymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr "BLAS_FUNC(ssyr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) nogil
+cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil:
+    
+    _fortran_ssyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr2 "BLAS_FUNC(ssyr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
+cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
+    
+    _fortran_ssyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr2k "BLAS_FUNC(ssyr2k)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
+cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_ssyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyrk "BLAS_FUNC(ssyrk)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) nogil
+cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_ssyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stbmv "BLAS_FUNC(stbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
+cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stbsv "BLAS_FUNC(stbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
+cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stpmv "BLAS_FUNC(stpmv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
+cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stpsv "BLAS_FUNC(stpsv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
+cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strmm "BLAS_FUNC(strmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil
+cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strmv "BLAS_FUNC(strmv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
+cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_strmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strsm "BLAS_FUNC(strsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil
+cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_strsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strsv "BLAS_FUNC(strsv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
+cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_strsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zaxpy "BLAS_FUNC(zaxpy)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zaxpy(n, za, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zcopy "BLAS_FUNC(zcopy)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zcopy(n, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdotc "F_FUNC(zdotcwrp,ZDOTCWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    cdef z out
+    _fortran_zdotc(&out, n, zx, incx, zy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdotu "F_FUNC(zdotuwrp,ZDOTUWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    cdef z out
+    _fortran_zdotu(&out, n, zx, incx, zy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdrot "BLAS_FUNC(zdrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, d *s) nogil
+cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil:
+    
+    _fortran_zdrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdscal "BLAS_FUNC(zdscal)"(int *n, d *da, npy_complex128 *zx, int *incx) nogil
+cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil:
+    
+    _fortran_zdscal(n, da, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgbmv "BLAS_FUNC(zgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgemm "BLAS_FUNC(zgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgemv "BLAS_FUNC(zgemv)"(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgerc "BLAS_FUNC(zgerc)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zgerc(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgeru "BLAS_FUNC(zgeru)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zgeru(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhbmv "BLAS_FUNC(zhbmv)"(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhemm "BLAS_FUNC(zhemm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zhemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhemv "BLAS_FUNC(zhemv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher "BLAS_FUNC(zher)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
+cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zher(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher2 "BLAS_FUNC(zher2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zher2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher2k "BLAS_FUNC(zher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zherk "BLAS_FUNC(zherk)"(char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpmv "BLAS_FUNC(zhpmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhpmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpr "BLAS_FUNC(zhpr)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
+cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil:
+    
+    _fortran_zhpr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpr2 "BLAS_FUNC(zhpr2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap) nogil
+cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil:
+    
+    _fortran_zhpr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zrotg "BLAS_FUNC(zrotg)"(npy_complex128 *ca, npy_complex128 *cb, d *c, npy_complex128 *s) nogil
+cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil:
+    
+    _fortran_zrotg(ca, cb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zscal "BLAS_FUNC(zscal)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx) nogil
+cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil:
+    
+    _fortran_zscal(n, za, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zswap "BLAS_FUNC(zswap)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zswap(n, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsymm "BLAS_FUNC(zsymm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsyr2k "BLAS_FUNC(zsyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsyrk "BLAS_FUNC(zsyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztbmv "BLAS_FUNC(ztbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztbsv "BLAS_FUNC(ztbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztpmv "BLAS_FUNC(ztpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
+cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztpsv "BLAS_FUNC(ztpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
+cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrmm "BLAS_FUNC(ztrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_ztrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrmv "BLAS_FUNC(ztrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrsm "BLAS_FUNC(ztrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_ztrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrsv "BLAS_FUNC(ztrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+
+# Python-accessible wrappers for testing:
+
+cdef inline bint _is_contiguous(double[:,:] a, int axis) noexcept nogil:
+    return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1)
+
+cpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotc(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef double _test_dasum(double[:] dx) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+    return dasum(&n, &dx[0], &incx)
+
+cpdef double _test_ddot(double[:] dx, double[:] dy) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+        int incy = dy.strides[0] // sizeof(dy[0])
+    return ddot(&n, &dx[0], &incx, &dy[0], &incy)
+
+cpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta,
+                double[:,:] c) except -1 nogil:
+    cdef:
+        char *transa
+        char *transb
+        int m, n, k, lda, ldb, ldc
+        double *a0=&a[0,0]
+        double *b0=&b[0,0]
+        double *c0=&c[0,0]
+    # In the case that c is C contiguous, swap a and b and
+    # swap whether or not each of them is transposed.
+    # This can be done because a.dot(b) = b.T.dot(a.T).T.
+    if _is_contiguous(c, 1):
+        if _is_contiguous(a, 1):
+            transb = 'n'
+            ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
+        elif _is_contiguous(a, 0):
+            transb = 't'
+            ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
+        if _is_contiguous(b, 1):
+            transa = 'n'
+            lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
+        elif _is_contiguous(b, 0):
+            transa = 't'
+            lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
+        k = b.shape[0]
+        if k != a.shape[1]:
+            with gil:
+                raise ValueError("Shape mismatch in input arrays.")
+        m = b.shape[1]
+        n = a.shape[0]
+        if n != c.shape[0] or m != c.shape[1]:
+            with gil:
+                raise ValueError("Output array does not have the correct shape.")
+        ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1
+        dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0,
+                   &ldb, &beta, c0, &ldc)
+    elif _is_contiguous(c, 0):
+        if _is_contiguous(a, 1):
+            transa = 't'
+            lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
+        elif _is_contiguous(a, 0):
+            transa = 'n'
+            lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
+        if _is_contiguous(b, 1):
+            transb = 't'
+            ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
+        elif _is_contiguous(b, 0):
+            transb = 'n'
+            ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
+        m = a.shape[0]
+        k = a.shape[1]
+        if k != b.shape[0]:
+            with gil:
+                raise ValueError("Shape mismatch in input arrays.")
+        n = b.shape[1]
+        if m != c.shape[0] or n != c.shape[1]:
+            with gil:
+                raise ValueError("Output array does not have the correct shape.")
+        ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1
+        dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0,
+                   &ldb, &beta, c0, &ldc)
+    else:
+        with gil:
+            raise ValueError("Input 'c' is neither C nor Fortran contiguous.")
+    return 0
+
+cpdef double _test_dnrm2(double[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return dnrm2(&n, &x[0], &incx)
+
+cpdef double _test_dzasum(double complex[:] zx) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+    return dzasum(&n, &zx[0], &incx)
+
+cpdef double _test_dznrm2(double complex[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return dznrm2(&n, &x[0], &incx)
+
+cpdef int _test_icamax(float complex[:] cx) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+    return icamax(&n, &cx[0], &incx)
+
+cpdef int _test_idamax(double[:] dx) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+    return idamax(&n, &dx[0], &incx)
+
+cpdef int _test_isamax(float[:] sx) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+    return isamax(&n, &sx[0], &incx)
+
+cpdef int _test_izamax(double complex[:] zx) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+    return izamax(&n, &zx[0], &incx)
+
+cpdef float _test_sasum(float[:] sx) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+    return sasum(&n, &sx[0], &incx)
+
+cpdef float _test_scasum(float complex[:] cx) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+    return scasum(&n, &cx[0], &incx)
+
+cpdef float _test_scnrm2(float complex[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return scnrm2(&n, &x[0], &incx)
+
+cpdef float _test_sdot(float[:] sx, float[:] sy) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+        int incy = sy.strides[0] // sizeof(sy[0])
+    return sdot(&n, &sx[0], &incx, &sy[0], &incy)
+
+cpdef float _test_snrm2(float[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return snrm2(&n, &x[0], &incx)
+
+cpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+        int incy = zy.strides[0] // sizeof(zy[0])
+    return zdotc(&n, &zx[0], &incx, &zy[0], &incy)
+
+cpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+        int incy = zy.strides[0] // sizeof(zy[0])
+    return zdotu(&n, &zx[0], &incx, &zy[0], &incy)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd b/venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7964c52d766cd1b08bda6411960a29dbeb6bfe2d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
@@ -0,0 +1,1528 @@
+"""
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_lapack
+# from scipy.linalg cimport cython_lapack
+# cimport scipy.linalg.cython_lapack as cython_lapack
+# cimport ..linalg.cython_lapack as cython_lapack
+
+# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+ctypedef float s
+ctypedef double d
+ctypedef float complex c
+ctypedef double complex z
+
+# Function pointer type declarations for
+# gees and gges families of functions.
+ctypedef bint cselect1(c*)
+ctypedef bint cselect2(c*, c*)
+ctypedef bint dselect2(d*, d*)
+ctypedef bint dselect3(d*, d*, d*)
+ctypedef bint sselect2(s*, s*)
+ctypedef bint sselect3(s*, s*, s*)
+ctypedef bint zselect1(z*)
+ctypedef bint zselect2(z*, z*)
+
+cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil
+cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil
+cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil
+cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil
+cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil
+cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil
+cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil
+cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil
+cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil
+cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil
+cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil
+cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil
+cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil
+cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil
+cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil
+cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil
+cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil
+cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil
+cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil
+cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil
+cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil
+cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef char chla_transtype(int *trans) noexcept nogil
+cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil
+cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil
+cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil
+cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil
+cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil
+cdef void clacgv(int *n, c *x, int *incx) noexcept nogil
+cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil
+cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil
+cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil
+cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil
+cdef c cladiv(c *x, c *y) noexcept nogil
+cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil
+cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil
+cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil
+cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil
+cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil
+cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil
+cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil
+cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil
+cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil
+cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil
+cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil
+cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil
+cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil
+cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil
+cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil
+cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil
+cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil
+cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil
+cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil
+cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil
+cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil
+cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil
+cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil
+cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil
+cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil
+cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil
+cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil
+cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil
+cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil
+cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil
+cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil
+cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil
+cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil
+cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil
+cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil
+cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil
+cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil
+cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil
+cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil
+cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil
+cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil
+cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil
+cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil
+cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil
+cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil
+cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil
+cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil
+cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil
+cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil
+cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil
+cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil
+cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil
+cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil
+cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil
+cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil
+cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil
+cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil
+cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil
+cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil
+cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil
+cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil
+cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil
+cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
+cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil
+cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil
+cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil
+cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil
+cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil
+cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil
+cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil
+cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil
+cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil
+cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil
+cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil
+cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil
+cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil
+cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil
+cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil
+cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil
+cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil
+cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil
+cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil
+cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil
+cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil
+cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil
+cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil
+cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil
+cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil
+cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil
+cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil
+cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil
+cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil
+cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil
+cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil
+cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil
+cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil
+cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil
+cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil
+cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil
+cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef bint disnan(d *din) noexcept nogil
+cdef void dlabad(d *small, d *large) noexcept nogil
+cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil
+cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil
+cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil
+cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil
+cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil
+cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil
+cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil
+cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil
+cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil
+cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil
+cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil
+cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil
+cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil
+cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil
+cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil
+cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil
+cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil
+cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil
+cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil
+cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil
+cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil
+cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil
+cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil
+cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil
+cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil
+cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil
+cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil
+cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil
+cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil
+cdef d dlamch(char *cmach) noexcept nogil
+cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil
+cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil
+cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil
+cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil
+cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil
+cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil
+cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil
+cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil
+cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil
+cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil
+cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil
+cdef d dlapy2(d *x, d *y) noexcept nogil
+cdef d dlapy3(d *x, d *y, d *z) noexcept nogil
+cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil
+cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil
+cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil
+cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil
+cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil
+cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil
+cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil
+cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil
+cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil
+cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil
+cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil
+cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil
+cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil
+cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil
+cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil
+cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil
+cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil
+cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil
+cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil
+cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil
+cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil
+cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil
+cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil
+cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil
+cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil
+cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil
+cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil
+cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil
+cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil
+cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil
+cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil
+cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil
+cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil
+cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil
+cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil
+cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil
+cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil
+cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil
+cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil
+cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil
+cdef void dlasq2(int *n, d *z, int *info) noexcept nogil
+cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil
+cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil
+cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil
+cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil
+cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil
+cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil
+cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil
+cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil
+cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil
+cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil
+cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil
+cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil
+cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil
+cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil
+cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil
+cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil
+cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil
+cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil
+cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil
+cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil
+cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil
+cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil
+cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil
+cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil
+cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil
+cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil
+cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil
+cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil
+cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil
+cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil
+cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil
+cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil
+cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil
+cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil
+cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil
+cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil
+cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil
+cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil
+cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil
+cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil
+cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil
+cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil
+cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil
+cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil
+cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil
+cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil
+cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil
+cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil
+cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil
+cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil
+cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil
+cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil
+cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil
+cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil
+cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil
+cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil
+cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil
+cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil
+cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil
+cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil
+cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil
+cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil
+cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil
+cdef int iladiag(char *diag) noexcept nogil
+cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil
+cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil
+cdef int ilaprec(char *prec) noexcept nogil
+cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil
+cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil
+cdef int ilatrans(char *trans) noexcept nogil
+cdef int ilauplo(char *uplo) noexcept nogil
+cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil
+cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil
+cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil
+cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil
+cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil
+cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil
+cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil
+cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil
+cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil
+cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil
+cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil
+cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil
+cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil
+cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil
+cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil
+cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil
+cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil
+cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil
+cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil
+cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil
+cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slabad(s *small, s *large) noexcept nogil
+cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil
+cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil
+cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil
+cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil
+cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil
+cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil
+cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil
+cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil
+cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil
+cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil
+cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil
+cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil
+cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil
+cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil
+cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil
+cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil
+cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil
+cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil
+cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil
+cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil
+cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil
+cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil
+cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil
+cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil
+cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil
+cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil
+cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil
+cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil
+cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil
+cdef s slamch(char *cmach) noexcept nogil
+cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil
+cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil
+cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil
+cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil
+cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil
+cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil
+cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil
+cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil
+cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil
+cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil
+cdef s slapy2(s *x, s *y) noexcept nogil
+cdef s slapy3(s *x, s *y, s *z) noexcept nogil
+cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil
+cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil
+cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil
+cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil
+cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil
+cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil
+cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil
+cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil
+cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil
+cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil
+cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil
+cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil
+cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil
+cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil
+cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil
+cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil
+cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil
+cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil
+cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil
+cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil
+cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil
+cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil
+cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil
+cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil
+cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil
+cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil
+cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil
+cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil
+cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil
+cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil
+cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil
+cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil
+cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil
+cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil
+cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil
+cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil
+cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil
+cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil
+cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil
+cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil
+cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil
+cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil
+cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil
+cdef void slasq2(int *n, s *z, int *info) noexcept nogil
+cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil
+cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil
+cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil
+cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil
+cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil
+cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil
+cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil
+cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil
+cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil
+cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil
+cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil
+cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil
+cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil
+cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil
+cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil
+cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil
+cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil
+cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil
+cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil
+cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil
+cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil
+cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil
+cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil
+cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil
+cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil
+cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil
+cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil
+cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil
+cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil
+cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil
+cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil
+cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil
+cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil
+cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil
+cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil
+cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil
+cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil
+cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil
+cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil
+cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil
+cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil
+cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil
+cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil
+cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil
+cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil
+cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil
+cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil
+cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil
+cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil
+cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil
+cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil
+cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil
+cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil
+cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil
+cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil
+cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil
+cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil
+cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil
+cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil
+cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil
+cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil
+cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil
+cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil
+cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil
+cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil
+cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil
+cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil
+cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil
+cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil
+cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil
+cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil
+cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil
+cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil
+cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil
+cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil
+cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil
+cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil
+cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil
+cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil
+cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil
+cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil
+cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil
+cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil
+cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil
+cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil
+cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil
+cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil
+cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil
+cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil
+cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil
+cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil
+cdef z zladiv(z *x, z *y) noexcept nogil
+cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil
+cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil
+cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil
+cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil
+cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil
+cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil
+cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil
+cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil
+cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil
+cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil
+cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil
+cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil
+cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil
+cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil
+cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil
+cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil
+cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil
+cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil
+cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil
+cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil
+cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil
+cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil
+cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil
+cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil
+cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil
+cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil
+cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil
+cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil
+cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil
+cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil
+cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil
+cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil
+cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil
+cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil
+cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil
+cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil
+cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil
+cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil
+cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil
+cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil
+cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil
+cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil
+cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil
+cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil
+cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil
+cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil
+cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil
+cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil
+cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil
+cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil
+cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil
+cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil
+cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil
+cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil
+cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil
+cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil
+cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil
+cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil
+cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil
+cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil
+cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil
+cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil
+cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
+cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil
+cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil
+cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil
+cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil
+cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil
+cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil
+cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil
+cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil
+cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil
+cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil
+cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil
+cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil
+cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil
+cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil
+cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil
+cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil
+cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil
+cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil
+cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil
+cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil
+cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil
+cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx b/venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..7f9cbfbb519603d4107af51ac353e0650720cf8c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
@@ -0,0 +1,12045 @@
+# This file was generated by _generate_pyx.py.
+# Do not edit this file directly.
+"""
+LAPACK functions for Cython
+===========================
+
+Usable from Cython via::
+
+    cimport scipy.linalg.cython_lapack
+
+This module provides Cython-level wrappers for all primary routines included
+in LAPACK 3.4.0 except for ``zcgesv`` since its interface is not consistent
+from LAPACK 3.4.0 to 3.6.0. It also provides some of the
+fixed-api auxiliary routines.
+
+These wrappers do not check for alignment of arrays.
+Alignment should be checked before these wrappers are used.
+
+Raw function pointers (Fortran-style pointer arguments):
+
+- cbbcsd
+- cbdsqr
+- cgbbrd
+- cgbcon
+- cgbequ
+- cgbequb
+- cgbrfs
+- cgbsv
+- cgbsvx
+- cgbtf2
+- cgbtrf
+- cgbtrs
+- cgebak
+- cgebal
+- cgebd2
+- cgebrd
+- cgecon
+- cgeequ
+- cgeequb
+- cgees
+- cgeesx
+- cgeev
+- cgeevx
+- cgehd2
+- cgehrd
+- cgelq2
+- cgelqf
+- cgels
+- cgelsd
+- cgelss
+- cgelsy
+- cgemqrt
+- cgeql2
+- cgeqlf
+- cgeqp3
+- cgeqr2
+- cgeqr2p
+- cgeqrf
+- cgeqrfp
+- cgeqrt
+- cgeqrt2
+- cgeqrt3
+- cgerfs
+- cgerq2
+- cgerqf
+- cgesc2
+- cgesdd
+- cgesv
+- cgesvd
+- cgesvx
+- cgetc2
+- cgetf2
+- cgetrf
+- cgetri
+- cgetrs
+- cggbak
+- cggbal
+- cgges
+- cggesx
+- cggev
+- cggevx
+- cggglm
+- cgghrd
+- cgglse
+- cggqrf
+- cggrqf
+- cgtcon
+- cgtrfs
+- cgtsv
+- cgtsvx
+- cgttrf
+- cgttrs
+- cgtts2
+- chbev
+- chbevd
+- chbevx
+- chbgst
+- chbgv
+- chbgvd
+- chbgvx
+- chbtrd
+- checon
+- cheequb
+- cheev
+- cheevd
+- cheevr
+- cheevx
+- chegs2
+- chegst
+- chegv
+- chegvd
+- chegvx
+- cherfs
+- chesv
+- chesvx
+- cheswapr
+- chetd2
+- chetf2
+- chetrd
+- chetrf
+- chetri
+- chetri2
+- chetri2x
+- chetrs
+- chetrs2
+- chfrk
+- chgeqz
+- chla_transtype
+- chpcon
+- chpev
+- chpevd
+- chpevx
+- chpgst
+- chpgv
+- chpgvd
+- chpgvx
+- chprfs
+- chpsv
+- chpsvx
+- chptrd
+- chptrf
+- chptri
+- chptrs
+- chsein
+- chseqr
+- clabrd
+- clacgv
+- clacn2
+- clacon
+- clacp2
+- clacpy
+- clacrm
+- clacrt
+- cladiv
+- claed0
+- claed7
+- claed8
+- claein
+- claesy
+- claev2
+- clag2z
+- clags2
+- clagtm
+- clahef
+- clahqr
+- clahr2
+- claic1
+- clals0
+- clalsa
+- clalsd
+- clangb
+- clange
+- clangt
+- clanhb
+- clanhe
+- clanhf
+- clanhp
+- clanhs
+- clanht
+- clansb
+- clansp
+- clansy
+- clantb
+- clantp
+- clantr
+- clapll
+- clapmr
+- clapmt
+- claqgb
+- claqge
+- claqhb
+- claqhe
+- claqhp
+- claqp2
+- claqps
+- claqr0
+- claqr1
+- claqr2
+- claqr3
+- claqr4
+- claqr5
+- claqsb
+- claqsp
+- claqsy
+- clar1v
+- clar2v
+- clarcm
+- clarf
+- clarfb
+- clarfg
+- clarfgp
+- clarft
+- clarfx
+- clargv
+- clarnv
+- clarrv
+- clartg
+- clartv
+- clarz
+- clarzb
+- clarzt
+- clascl
+- claset
+- clasr
+- classq
+- claswp
+- clasyf
+- clatbs
+- clatdf
+- clatps
+- clatrd
+- clatrs
+- clatrz
+- clauu2
+- clauum
+- cpbcon
+- cpbequ
+- cpbrfs
+- cpbstf
+- cpbsv
+- cpbsvx
+- cpbtf2
+- cpbtrf
+- cpbtrs
+- cpftrf
+- cpftri
+- cpftrs
+- cpocon
+- cpoequ
+- cpoequb
+- cporfs
+- cposv
+- cposvx
+- cpotf2
+- cpotrf
+- cpotri
+- cpotrs
+- cppcon
+- cppequ
+- cpprfs
+- cppsv
+- cppsvx
+- cpptrf
+- cpptri
+- cpptrs
+- cpstf2
+- cpstrf
+- cptcon
+- cpteqr
+- cptrfs
+- cptsv
+- cptsvx
+- cpttrf
+- cpttrs
+- cptts2
+- crot
+- cspcon
+- cspmv
+- cspr
+- csprfs
+- cspsv
+- cspsvx
+- csptrf
+- csptri
+- csptrs
+- csrscl
+- cstedc
+- cstegr
+- cstein
+- cstemr
+- csteqr
+- csycon
+- csyconv
+- csyequb
+- csymv
+- csyr
+- csyrfs
+- csysv
+- csysvx
+- csyswapr
+- csytf2
+- csytrf
+- csytri
+- csytri2
+- csytri2x
+- csytrs
+- csytrs2
+- ctbcon
+- ctbrfs
+- ctbtrs
+- ctfsm
+- ctftri
+- ctfttp
+- ctfttr
+- ctgevc
+- ctgex2
+- ctgexc
+- ctgsen
+- ctgsja
+- ctgsna
+- ctgsy2
+- ctgsyl
+- ctpcon
+- ctpmqrt
+- ctpqrt
+- ctpqrt2
+- ctprfb
+- ctprfs
+- ctptri
+- ctptrs
+- ctpttf
+- ctpttr
+- ctrcon
+- ctrevc
+- ctrexc
+- ctrrfs
+- ctrsen
+- ctrsna
+- ctrsyl
+- ctrti2
+- ctrtri
+- ctrtrs
+- ctrttf
+- ctrttp
+- ctzrzf
+- cunbdb
+- cuncsd
+- cung2l
+- cung2r
+- cungbr
+- cunghr
+- cungl2
+- cunglq
+- cungql
+- cungqr
+- cungr2
+- cungrq
+- cungtr
+- cunm2l
+- cunm2r
+- cunmbr
+- cunmhr
+- cunml2
+- cunmlq
+- cunmql
+- cunmqr
+- cunmr2
+- cunmr3
+- cunmrq
+- cunmrz
+- cunmtr
+- cupgtr
+- cupmtr
+- dbbcsd
+- dbdsdc
+- dbdsqr
+- ddisna
+- dgbbrd
+- dgbcon
+- dgbequ
+- dgbequb
+- dgbrfs
+- dgbsv
+- dgbsvx
+- dgbtf2
+- dgbtrf
+- dgbtrs
+- dgebak
+- dgebal
+- dgebd2
+- dgebrd
+- dgecon
+- dgeequ
+- dgeequb
+- dgees
+- dgeesx
+- dgeev
+- dgeevx
+- dgehd2
+- dgehrd
+- dgejsv
+- dgelq2
+- dgelqf
+- dgels
+- dgelsd
+- dgelss
+- dgelsy
+- dgemqrt
+- dgeql2
+- dgeqlf
+- dgeqp3
+- dgeqr2
+- dgeqr2p
+- dgeqrf
+- dgeqrfp
+- dgeqrt
+- dgeqrt2
+- dgeqrt3
+- dgerfs
+- dgerq2
+- dgerqf
+- dgesc2
+- dgesdd
+- dgesv
+- dgesvd
+- dgesvj
+- dgesvx
+- dgetc2
+- dgetf2
+- dgetrf
+- dgetri
+- dgetrs
+- dggbak
+- dggbal
+- dgges
+- dggesx
+- dggev
+- dggevx
+- dggglm
+- dgghrd
+- dgglse
+- dggqrf
+- dggrqf
+- dgsvj0
+- dgsvj1
+- dgtcon
+- dgtrfs
+- dgtsv
+- dgtsvx
+- dgttrf
+- dgttrs
+- dgtts2
+- dhgeqz
+- dhsein
+- dhseqr
+- disnan
+- dlabad
+- dlabrd
+- dlacn2
+- dlacon
+- dlacpy
+- dladiv
+- dlae2
+- dlaebz
+- dlaed0
+- dlaed1
+- dlaed2
+- dlaed3
+- dlaed4
+- dlaed5
+- dlaed6
+- dlaed7
+- dlaed8
+- dlaed9
+- dlaeda
+- dlaein
+- dlaev2
+- dlaexc
+- dlag2
+- dlag2s
+- dlags2
+- dlagtf
+- dlagtm
+- dlagts
+- dlagv2
+- dlahqr
+- dlahr2
+- dlaic1
+- dlaln2
+- dlals0
+- dlalsa
+- dlalsd
+- dlamch
+- dlamrg
+- dlaneg
+- dlangb
+- dlange
+- dlangt
+- dlanhs
+- dlansb
+- dlansf
+- dlansp
+- dlanst
+- dlansy
+- dlantb
+- dlantp
+- dlantr
+- dlanv2
+- dlapll
+- dlapmr
+- dlapmt
+- dlapy2
+- dlapy3
+- dlaqgb
+- dlaqge
+- dlaqp2
+- dlaqps
+- dlaqr0
+- dlaqr1
+- dlaqr2
+- dlaqr3
+- dlaqr4
+- dlaqr5
+- dlaqsb
+- dlaqsp
+- dlaqsy
+- dlaqtr
+- dlar1v
+- dlar2v
+- dlarf
+- dlarfb
+- dlarfg
+- dlarfgp
+- dlarft
+- dlarfx
+- dlargv
+- dlarnv
+- dlarra
+- dlarrb
+- dlarrc
+- dlarrd
+- dlarre
+- dlarrf
+- dlarrj
+- dlarrk
+- dlarrr
+- dlarrv
+- dlartg
+- dlartgp
+- dlartgs
+- dlartv
+- dlaruv
+- dlarz
+- dlarzb
+- dlarzt
+- dlas2
+- dlascl
+- dlasd0
+- dlasd1
+- dlasd2
+- dlasd3
+- dlasd4
+- dlasd5
+- dlasd6
+- dlasd7
+- dlasd8
+- dlasda
+- dlasdq
+- dlasdt
+- dlaset
+- dlasq1
+- dlasq2
+- dlasq3
+- dlasq4
+- dlasq6
+- dlasr
+- dlasrt
+- dlassq
+- dlasv2
+- dlaswp
+- dlasy2
+- dlasyf
+- dlat2s
+- dlatbs
+- dlatdf
+- dlatps
+- dlatrd
+- dlatrs
+- dlatrz
+- dlauu2
+- dlauum
+- dopgtr
+- dopmtr
+- dorbdb
+- dorcsd
+- dorg2l
+- dorg2r
+- dorgbr
+- dorghr
+- dorgl2
+- dorglq
+- dorgql
+- dorgqr
+- dorgr2
+- dorgrq
+- dorgtr
+- dorm2l
+- dorm2r
+- dormbr
+- dormhr
+- dorml2
+- dormlq
+- dormql
+- dormqr
+- dormr2
+- dormr3
+- dormrq
+- dormrz
+- dormtr
+- dpbcon
+- dpbequ
+- dpbrfs
+- dpbstf
+- dpbsv
+- dpbsvx
+- dpbtf2
+- dpbtrf
+- dpbtrs
+- dpftrf
+- dpftri
+- dpftrs
+- dpocon
+- dpoequ
+- dpoequb
+- dporfs
+- dposv
+- dposvx
+- dpotf2
+- dpotrf
+- dpotri
+- dpotrs
+- dppcon
+- dppequ
+- dpprfs
+- dppsv
+- dppsvx
+- dpptrf
+- dpptri
+- dpptrs
+- dpstf2
+- dpstrf
+- dptcon
+- dpteqr
+- dptrfs
+- dptsv
+- dptsvx
+- dpttrf
+- dpttrs
+- dptts2
+- drscl
+- dsbev
+- dsbevd
+- dsbevx
+- dsbgst
+- dsbgv
+- dsbgvd
+- dsbgvx
+- dsbtrd
+- dsfrk
+- dsgesv
+- dspcon
+- dspev
+- dspevd
+- dspevx
+- dspgst
+- dspgv
+- dspgvd
+- dspgvx
+- dsposv
+- dsprfs
+- dspsv
+- dspsvx
+- dsptrd
+- dsptrf
+- dsptri
+- dsptrs
+- dstebz
+- dstedc
+- dstegr
+- dstein
+- dstemr
+- dsteqr
+- dsterf
+- dstev
+- dstevd
+- dstevr
+- dstevx
+- dsycon
+- dsyconv
+- dsyequb
+- dsyev
+- dsyevd
+- dsyevr
+- dsyevx
+- dsygs2
+- dsygst
+- dsygv
+- dsygvd
+- dsygvx
+- dsyrfs
+- dsysv
+- dsysvx
+- dsyswapr
+- dsytd2
+- dsytf2
+- dsytrd
+- dsytrf
+- dsytri
+- dsytri2
+- dsytri2x
+- dsytrs
+- dsytrs2
+- dtbcon
+- dtbrfs
+- dtbtrs
+- dtfsm
+- dtftri
+- dtfttp
+- dtfttr
+- dtgevc
+- dtgex2
+- dtgexc
+- dtgsen
+- dtgsja
+- dtgsna
+- dtgsy2
+- dtgsyl
+- dtpcon
+- dtpmqrt
+- dtpqrt
+- dtpqrt2
+- dtprfb
+- dtprfs
+- dtptri
+- dtptrs
+- dtpttf
+- dtpttr
+- dtrcon
+- dtrevc
+- dtrexc
+- dtrrfs
+- dtrsen
+- dtrsna
+- dtrsyl
+- dtrti2
+- dtrtri
+- dtrtrs
+- dtrttf
+- dtrttp
+- dtzrzf
+- dzsum1
+- icmax1
+- ieeeck
+- ilaclc
+- ilaclr
+- iladiag
+- iladlc
+- iladlr
+- ilaprec
+- ilaslc
+- ilaslr
+- ilatrans
+- ilauplo
+- ilaver
+- ilazlc
+- ilazlr
+- izmax1
+- sbbcsd
+- sbdsdc
+- sbdsqr
+- scsum1
+- sdisna
+- sgbbrd
+- sgbcon
+- sgbequ
+- sgbequb
+- sgbrfs
+- sgbsv
+- sgbsvx
+- sgbtf2
+- sgbtrf
+- sgbtrs
+- sgebak
+- sgebal
+- sgebd2
+- sgebrd
+- sgecon
+- sgeequ
+- sgeequb
+- sgees
+- sgeesx
+- sgeev
+- sgeevx
+- sgehd2
+- sgehrd
+- sgejsv
+- sgelq2
+- sgelqf
+- sgels
+- sgelsd
+- sgelss
+- sgelsy
+- sgemqrt
+- sgeql2
+- sgeqlf
+- sgeqp3
+- sgeqr2
+- sgeqr2p
+- sgeqrf
+- sgeqrfp
+- sgeqrt
+- sgeqrt2
+- sgeqrt3
+- sgerfs
+- sgerq2
+- sgerqf
+- sgesc2
+- sgesdd
+- sgesv
+- sgesvd
+- sgesvj
+- sgesvx
+- sgetc2
+- sgetf2
+- sgetrf
+- sgetri
+- sgetrs
+- sggbak
+- sggbal
+- sgges
+- sggesx
+- sggev
+- sggevx
+- sggglm
+- sgghrd
+- sgglse
+- sggqrf
+- sggrqf
+- sgsvj0
+- sgsvj1
+- sgtcon
+- sgtrfs
+- sgtsv
+- sgtsvx
+- sgttrf
+- sgttrs
+- sgtts2
+- shgeqz
+- shsein
+- shseqr
+- slabad
+- slabrd
+- slacn2
+- slacon
+- slacpy
+- sladiv
+- slae2
+- slaebz
+- slaed0
+- slaed1
+- slaed2
+- slaed3
+- slaed4
+- slaed5
+- slaed6
+- slaed7
+- slaed8
+- slaed9
+- slaeda
+- slaein
+- slaev2
+- slaexc
+- slag2
+- slag2d
+- slags2
+- slagtf
+- slagtm
+- slagts
+- slagv2
+- slahqr
+- slahr2
+- slaic1
+- slaln2
+- slals0
+- slalsa
+- slalsd
+- slamch
+- slamrg
+- slangb
+- slange
+- slangt
+- slanhs
+- slansb
+- slansf
+- slansp
+- slanst
+- slansy
+- slantb
+- slantp
+- slantr
+- slanv2
+- slapll
+- slapmr
+- slapmt
+- slapy2
+- slapy3
+- slaqgb
+- slaqge
+- slaqp2
+- slaqps
+- slaqr0
+- slaqr1
+- slaqr2
+- slaqr3
+- slaqr4
+- slaqr5
+- slaqsb
+- slaqsp
+- slaqsy
+- slaqtr
+- slar1v
+- slar2v
+- slarf
+- slarfb
+- slarfg
+- slarfgp
+- slarft
+- slarfx
+- slargv
+- slarnv
+- slarra
+- slarrb
+- slarrc
+- slarrd
+- slarre
+- slarrf
+- slarrj
+- slarrk
+- slarrr
+- slarrv
+- slartg
+- slartgp
+- slartgs
+- slartv
+- slaruv
+- slarz
+- slarzb
+- slarzt
+- slas2
+- slascl
+- slasd0
+- slasd1
+- slasd2
+- slasd3
+- slasd4
+- slasd5
+- slasd6
+- slasd7
+- slasd8
+- slasda
+- slasdq
+- slasdt
+- slaset
+- slasq1
+- slasq2
+- slasq3
+- slasq4
+- slasq6
+- slasr
+- slasrt
+- slassq
+- slasv2
+- slaswp
+- slasy2
+- slasyf
+- slatbs
+- slatdf
+- slatps
+- slatrd
+- slatrs
+- slatrz
+- slauu2
+- slauum
+- sopgtr
+- sopmtr
+- sorbdb
+- sorcsd
+- sorg2l
+- sorg2r
+- sorgbr
+- sorghr
+- sorgl2
+- sorglq
+- sorgql
+- sorgqr
+- sorgr2
+- sorgrq
+- sorgtr
+- sorm2l
+- sorm2r
+- sormbr
+- sormhr
+- sorml2
+- sormlq
+- sormql
+- sormqr
+- sormr2
+- sormr3
+- sormrq
+- sormrz
+- sormtr
+- spbcon
+- spbequ
+- spbrfs
+- spbstf
+- spbsv
+- spbsvx
+- spbtf2
+- spbtrf
+- spbtrs
+- spftrf
+- spftri
+- spftrs
+- spocon
+- spoequ
+- spoequb
+- sporfs
+- sposv
+- sposvx
+- spotf2
+- spotrf
+- spotri
+- spotrs
+- sppcon
+- sppequ
+- spprfs
+- sppsv
+- sppsvx
+- spptrf
+- spptri
+- spptrs
+- spstf2
+- spstrf
+- sptcon
+- spteqr
+- sptrfs
+- sptsv
+- sptsvx
+- spttrf
+- spttrs
+- sptts2
+- srscl
+- ssbev
+- ssbevd
+- ssbevx
+- ssbgst
+- ssbgv
+- ssbgvd
+- ssbgvx
+- ssbtrd
+- ssfrk
+- sspcon
+- sspev
+- sspevd
+- sspevx
+- sspgst
+- sspgv
+- sspgvd
+- sspgvx
+- ssprfs
+- sspsv
+- sspsvx
+- ssptrd
+- ssptrf
+- ssptri
+- ssptrs
+- sstebz
+- sstedc
+- sstegr
+- sstein
+- sstemr
+- ssteqr
+- ssterf
+- sstev
+- sstevd
+- sstevr
+- sstevx
+- ssycon
+- ssyconv
+- ssyequb
+- ssyev
+- ssyevd
+- ssyevr
+- ssyevx
+- ssygs2
+- ssygst
+- ssygv
+- ssygvd
+- ssygvx
+- ssyrfs
+- ssysv
+- ssysvx
+- ssyswapr
+- ssytd2
+- ssytf2
+- ssytrd
+- ssytrf
+- ssytri
+- ssytri2
+- ssytri2x
+- ssytrs
+- ssytrs2
+- stbcon
+- stbrfs
+- stbtrs
+- stfsm
+- stftri
+- stfttp
+- stfttr
+- stgevc
+- stgex2
+- stgexc
+- stgsen
+- stgsja
+- stgsna
+- stgsy2
+- stgsyl
+- stpcon
+- stpmqrt
+- stpqrt
+- stpqrt2
+- stprfb
+- stprfs
+- stptri
+- stptrs
+- stpttf
+- stpttr
+- strcon
+- strevc
+- strexc
+- strrfs
+- strsen
+- strsna
+- strsyl
+- strti2
+- strtri
+- strtrs
+- strttf
+- strttp
+- stzrzf
+- xerbla_array
+- zbbcsd
+- zbdsqr
+- zcgesv
+- zcposv
+- zdrscl
+- zgbbrd
+- zgbcon
+- zgbequ
+- zgbequb
+- zgbrfs
+- zgbsv
+- zgbsvx
+- zgbtf2
+- zgbtrf
+- zgbtrs
+- zgebak
+- zgebal
+- zgebd2
+- zgebrd
+- zgecon
+- zgeequ
+- zgeequb
+- zgees
+- zgeesx
+- zgeev
+- zgeevx
+- zgehd2
+- zgehrd
+- zgelq2
+- zgelqf
+- zgels
+- zgelsd
+- zgelss
+- zgelsy
+- zgemqrt
+- zgeql2
+- zgeqlf
+- zgeqp3
+- zgeqr2
+- zgeqr2p
+- zgeqrf
+- zgeqrfp
+- zgeqrt
+- zgeqrt2
+- zgeqrt3
+- zgerfs
+- zgerq2
+- zgerqf
+- zgesc2
+- zgesdd
+- zgesv
+- zgesvd
+- zgesvx
+- zgetc2
+- zgetf2
+- zgetrf
+- zgetri
+- zgetrs
+- zggbak
+- zggbal
+- zgges
+- zggesx
+- zggev
+- zggevx
+- zggglm
+- zgghrd
+- zgglse
+- zggqrf
+- zggrqf
+- zgtcon
+- zgtrfs
+- zgtsv
+- zgtsvx
+- zgttrf
+- zgttrs
+- zgtts2
+- zhbev
+- zhbevd
+- zhbevx
+- zhbgst
+- zhbgv
+- zhbgvd
+- zhbgvx
+- zhbtrd
+- zhecon
+- zheequb
+- zheev
+- zheevd
+- zheevr
+- zheevx
+- zhegs2
+- zhegst
+- zhegv
+- zhegvd
+- zhegvx
+- zherfs
+- zhesv
+- zhesvx
+- zheswapr
+- zhetd2
+- zhetf2
+- zhetrd
+- zhetrf
+- zhetri
+- zhetri2
+- zhetri2x
+- zhetrs
+- zhetrs2
+- zhfrk
+- zhgeqz
+- zhpcon
+- zhpev
+- zhpevd
+- zhpevx
+- zhpgst
+- zhpgv
+- zhpgvd
+- zhpgvx
+- zhprfs
+- zhpsv
+- zhpsvx
+- zhptrd
+- zhptrf
+- zhptri
+- zhptrs
+- zhsein
+- zhseqr
+- zlabrd
+- zlacgv
+- zlacn2
+- zlacon
+- zlacp2
+- zlacpy
+- zlacrm
+- zlacrt
+- zladiv
+- zlaed0
+- zlaed7
+- zlaed8
+- zlaein
+- zlaesy
+- zlaev2
+- zlag2c
+- zlags2
+- zlagtm
+- zlahef
+- zlahqr
+- zlahr2
+- zlaic1
+- zlals0
+- zlalsa
+- zlalsd
+- zlangb
+- zlange
+- zlangt
+- zlanhb
+- zlanhe
+- zlanhf
+- zlanhp
+- zlanhs
+- zlanht
+- zlansb
+- zlansp
+- zlansy
+- zlantb
+- zlantp
+- zlantr
+- zlapll
+- zlapmr
+- zlapmt
+- zlaqgb
+- zlaqge
+- zlaqhb
+- zlaqhe
+- zlaqhp
+- zlaqp2
+- zlaqps
+- zlaqr0
+- zlaqr1
+- zlaqr2
+- zlaqr3
+- zlaqr4
+- zlaqr5
+- zlaqsb
+- zlaqsp
+- zlaqsy
+- zlar1v
+- zlar2v
+- zlarcm
+- zlarf
+- zlarfb
+- zlarfg
+- zlarfgp
+- zlarft
+- zlarfx
+- zlargv
+- zlarnv
+- zlarrv
+- zlartg
+- zlartv
+- zlarz
+- zlarzb
+- zlarzt
+- zlascl
+- zlaset
+- zlasr
+- zlassq
+- zlaswp
+- zlasyf
+- zlat2c
+- zlatbs
+- zlatdf
+- zlatps
+- zlatrd
+- zlatrs
+- zlatrz
+- zlauu2
+- zlauum
+- zpbcon
+- zpbequ
+- zpbrfs
+- zpbstf
+- zpbsv
+- zpbsvx
+- zpbtf2
+- zpbtrf
+- zpbtrs
+- zpftrf
+- zpftri
+- zpftrs
+- zpocon
+- zpoequ
+- zpoequb
+- zporfs
+- zposv
+- zposvx
+- zpotf2
+- zpotrf
+- zpotri
+- zpotrs
+- zppcon
+- zppequ
+- zpprfs
+- zppsv
+- zppsvx
+- zpptrf
+- zpptri
+- zpptrs
+- zpstf2
+- zpstrf
+- zptcon
+- zpteqr
+- zptrfs
+- zptsv
+- zptsvx
+- zpttrf
+- zpttrs
+- zptts2
+- zrot
+- zspcon
+- zspmv
+- zspr
+- zsprfs
+- zspsv
+- zspsvx
+- zsptrf
+- zsptri
+- zsptrs
+- zstedc
+- zstegr
+- zstein
+- zstemr
+- zsteqr
+- zsycon
+- zsyconv
+- zsyequb
+- zsymv
+- zsyr
+- zsyrfs
+- zsysv
+- zsysvx
+- zsyswapr
+- zsytf2
+- zsytrf
+- zsytri
+- zsytri2
+- zsytri2x
+- zsytrs
+- zsytrs2
+- ztbcon
+- ztbrfs
+- ztbtrs
+- ztfsm
+- ztftri
+- ztfttp
+- ztfttr
+- ztgevc
+- ztgex2
+- ztgexc
+- ztgsen
+- ztgsja
+- ztgsna
+- ztgsy2
+- ztgsyl
+- ztpcon
+- ztpmqrt
+- ztpqrt
+- ztpqrt2
+- ztprfb
+- ztprfs
+- ztptri
+- ztptrs
+- ztpttf
+- ztpttr
+- ztrcon
+- ztrevc
+- ztrexc
+- ztrrfs
+- ztrsen
+- ztrsna
+- ztrsyl
+- ztrti2
+- ztrtri
+- ztrtrs
+- ztrttf
+- ztrttp
+- ztzrzf
+- zunbdb
+- zuncsd
+- zung2l
+- zung2r
+- zungbr
+- zunghr
+- zungl2
+- zunglq
+- zungql
+- zungqr
+- zungr2
+- zungrq
+- zungtr
+- zunm2l
+- zunm2r
+- zunmbr
+- zunmhr
+- zunml2
+- zunmlq
+- zunmql
+- zunmqr
+- zunmr2
+- zunmr3
+- zunmrq
+- zunmrz
+- zunmtr
+- zupgtr
+- zupmtr
+
+
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_lapack
+# from scipy.linalg cimport cython_lapack
+# cimport scipy.linalg.cython_lapack as cython_lapack
+# cimport ..linalg.cython_lapack as cython_lapack
+
+# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+cdef extern from "fortran_defs.h":
+    pass
+
+from numpy cimport npy_complex64, npy_complex128
+
+cdef extern from "_lapack_subroutines.h":
+    # Function pointer type declarations for
+    # gees and gges families of functions.
+    ctypedef bint _cselect1(npy_complex64*)
+    ctypedef bint _cselect2(npy_complex64*, npy_complex64*)
+    ctypedef bint _dselect2(d*, d*)
+    ctypedef bint _dselect3(d*, d*, d*)
+    ctypedef bint _sselect2(s*, s*)
+    ctypedef bint _sselect3(s*, s*, s*)
+    ctypedef bint _zselect1(npy_complex128*)
+    ctypedef bint _zselect2(npy_complex128*, npy_complex128*)
+
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cbbcsd "BLAS_FUNC(cbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) nogil
+cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil:
+    
+    _fortran_cbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cbdsqr "BLAS_FUNC(cbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, s *rwork, int *info) nogil
+cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbbrd "BLAS_FUNC(cgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbcon "BLAS_FUNC(cgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbequ "BLAS_FUNC(cgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbequb "BLAS_FUNC(cgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbrfs "BLAS_FUNC(cgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbsv "BLAS_FUNC(cgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbsvx "BLAS_FUNC(cgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtf2 "BLAS_FUNC(cgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtrf "BLAS_FUNC(cgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtrs "BLAS_FUNC(cgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebak "BLAS_FUNC(cgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, npy_complex64 *v, int *ldv, int *info) nogil
+cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_cgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebal "BLAS_FUNC(cgebal)"(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil
+cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil:
+    
+    _fortran_cgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebd2 "BLAS_FUNC(cgebd2)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info) nogil
+cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebrd "BLAS_FUNC(cgebrd)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgecon "BLAS_FUNC(cgecon)"(char *norm, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeequ "BLAS_FUNC(cgeequ)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeequb "BLAS_FUNC(cgeequb)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgees "BLAS_FUNC(cgees)"(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil
+cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cgees(jobvs, sort, <_cselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeesx "BLAS_FUNC(cgeesx)"(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil
+cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cgeesx(jobvs, sort, <_cselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeev "BLAS_FUNC(cgeev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeevx "BLAS_FUNC(cgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgehd2 "BLAS_FUNC(cgehd2)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgehrd "BLAS_FUNC(cgehrd)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelq2 "BLAS_FUNC(cgelq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelqf "BLAS_FUNC(cgelqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgels "BLAS_FUNC(cgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelsd "BLAS_FUNC(cgelsd)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) nogil
+cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_cgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelss "BLAS_FUNC(cgelss)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelsy "BLAS_FUNC(cgelsy)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgemqrt "BLAS_FUNC(cgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeql2 "BLAS_FUNC(cgeql2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqlf "BLAS_FUNC(cgeqlf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqp3 "BLAS_FUNC(cgeqp3)"(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqr2 "BLAS_FUNC(cgeqr2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqr2p "BLAS_FUNC(cgeqr2p)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrf "BLAS_FUNC(cgeqrf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrfp "BLAS_FUNC(cgeqrfp)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt "BLAS_FUNC(cgeqrt)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil
+cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt2 "BLAS_FUNC(cgeqrt2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt3 "BLAS_FUNC(cgeqrt3)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerfs "BLAS_FUNC(cgerfs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerq2 "BLAS_FUNC(cgerq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerqf "BLAS_FUNC(cgerqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesc2 "BLAS_FUNC(cgesc2)"(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, s *scale) nogil
+cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil:
+    
+    _fortran_cgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesdd "BLAS_FUNC(cgesdd)"(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) nogil
+cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_cgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesv "BLAS_FUNC(cgesv)"(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesvd "BLAS_FUNC(cgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesvx "BLAS_FUNC(cgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetc2 "BLAS_FUNC(cgetc2)"(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_cgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetf2 "BLAS_FUNC(cgetf2)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetrf "BLAS_FUNC(cgetrf)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetri "BLAS_FUNC(cgetri)"(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetrs "BLAS_FUNC(cgetrs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggbak "BLAS_FUNC(cggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, npy_complex64 *v, int *ldv, int *info) nogil
+cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_cggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggbal "BLAS_FUNC(cggbal)"(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) nogil
+cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil:
+    
+    _fortran_cggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgges "BLAS_FUNC(cgges)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil
+cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cgges(jobvsl, jobvsr, sort, <_cselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggesx "BLAS_FUNC(cggesx)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cggesx(jobvsl, jobvsr, sort, <_cselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggev "BLAS_FUNC(cggev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggevx "BLAS_FUNC(cggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) nogil
+cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggglm "BLAS_FUNC(cggglm)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgghrd "BLAS_FUNC(cgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info) nogil
+cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_cgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgglse "BLAS_FUNC(cgglse)"(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggqrf "BLAS_FUNC(cggqrf)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggrqf "BLAS_FUNC(cggrqf)"(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtcon "BLAS_FUNC(cgtcon)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtrfs "BLAS_FUNC(cgtrfs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtsv "BLAS_FUNC(cgtsv)"(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtsvx "BLAS_FUNC(cgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgttrf "BLAS_FUNC(cgttrf)"(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info) nogil
+cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgttrs "BLAS_FUNC(cgttrs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtts2 "BLAS_FUNC(cgtts2)"(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb) nogil
+cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_cgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbev "BLAS_FUNC(chbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbevd "BLAS_FUNC(chbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbevx "BLAS_FUNC(chbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgst "BLAS_FUNC(chbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgv "BLAS_FUNC(chbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgvd "BLAS_FUNC(chbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgvx "BLAS_FUNC(chbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbtrd "BLAS_FUNC(chbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil
+cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil:
+    
+    _fortran_chbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_checon "BLAS_FUNC(checon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_checon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheequb "BLAS_FUNC(cheequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil
+cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil:
+    
+    _fortran_cheequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheev "BLAS_FUNC(cheev)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevd "BLAS_FUNC(cheevd)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevr "BLAS_FUNC(cheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevx "BLAS_FUNC(cheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_cheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegs2 "BLAS_FUNC(chegs2)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chegs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegst "BLAS_FUNC(chegst)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chegst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegv "BLAS_FUNC(chegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegvd "BLAS_FUNC(chegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegvx "BLAS_FUNC(chegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cherfs "BLAS_FUNC(cherfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chesv "BLAS_FUNC(chesv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chesvx "BLAS_FUNC(chesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheswapr "BLAS_FUNC(cheswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil
+cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_cheswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetd2 "BLAS_FUNC(chetd2)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, int *info) nogil
+cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil:
+    
+    _fortran_chetd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetf2 "BLAS_FUNC(chetf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_chetf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrd "BLAS_FUNC(chetrd)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrf "BLAS_FUNC(chetrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri "BLAS_FUNC(chetri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_chetri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri2 "BLAS_FUNC(chetri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri2x "BLAS_FUNC(chetri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil
+cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_chetri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrs "BLAS_FUNC(chetrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrs2 "BLAS_FUNC(chetrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil
+cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil:
+    
+    _fortran_chetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chfrk "BLAS_FUNC(chfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c) nogil
+cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil:
+    
+    _fortran_chfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chgeqz "BLAS_FUNC(chgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    char _fortran_chla_transtype "BLAS_FUNC(chla_transtype)"(int *trans) nogil
+cdef char chla_transtype(int *trans) noexcept nogil:
+    
+    return _fortran_chla_transtype(trans)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpcon "BLAS_FUNC(chpcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_chpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpev "BLAS_FUNC(chpev)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpevd "BLAS_FUNC(chpevd)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpevx "BLAS_FUNC(chpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgst "BLAS_FUNC(chpgst)"(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info) nogil
+cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil:
+    
+    _fortran_chpgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgv "BLAS_FUNC(chpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgvd "BLAS_FUNC(chpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgvx "BLAS_FUNC(chpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chprfs "BLAS_FUNC(chprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpsv "BLAS_FUNC(chpsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpsvx "BLAS_FUNC(chpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrd "BLAS_FUNC(chptrd)"(char *uplo, int *n, npy_complex64 *ap, s *d, s *e, npy_complex64 *tau, int *info) nogil
+cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil:
+    
+    _fortran_chptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrf "BLAS_FUNC(chptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil
+cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_chptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptri "BLAS_FUNC(chptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_chptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrs "BLAS_FUNC(chptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chsein "BLAS_FUNC(chsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *ifaill, int *ifailr, int *info) nogil
+cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_chsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chseqr "BLAS_FUNC(chseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clabrd "BLAS_FUNC(clabrd)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy) nogil
+cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil:
+    
+    _fortran_clabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacgv "BLAS_FUNC(clacgv)"(int *n, npy_complex64 *x, int *incx) nogil
+cdef void clacgv(int *n, c *x, int *incx) noexcept nogil:
+    
+    _fortran_clacgv(n, x, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacn2 "BLAS_FUNC(clacn2)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase, int *isave) nogil
+cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_clacn2(n, v, x, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacon "BLAS_FUNC(clacon)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase) nogil
+cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil:
+    
+    _fortran_clacon(n, v, x, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacp2 "BLAS_FUNC(clacp2)"(char *uplo, int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clacp2(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacpy "BLAS_FUNC(clacpy)"(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacrm "BLAS_FUNC(clacrm)"(int *m, int *n, npy_complex64 *a, int *lda, s *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil
+cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil:
+    
+    _fortran_clacrm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacrt "BLAS_FUNC(clacrt)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s) nogil
+cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil:
+    
+    _fortran_clacrt(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cladiv "F_FUNC(cladivwrp,CLADIVWRP)"(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y) nogil
+cdef c cladiv(c *x, c *y) noexcept nogil:
+    cdef c out
+    _fortran_cladiv(&out, x, y)
+    return out
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed0 "BLAS_FUNC(claed0)"(int *qsiz, int *n, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, s *rwork, int *iwork, int *info) nogil
+cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_claed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed7 "BLAS_FUNC(claed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, npy_complex64 *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, npy_complex64 *work, s *rwork, int *iwork, int *info) nogil
+cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_claed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed8 "BLAS_FUNC(claed8)"(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, npy_complex64 *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) nogil
+cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil:
+    
+    _fortran_claed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claein "BLAS_FUNC(claein)"(bint *rightv, bint *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) nogil
+cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil:
+    
+    _fortran_claein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claesy "BLAS_FUNC(claesy)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1) nogil
+cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil:
+    
+    _fortran_claesy(a, b, c, rt1, rt2, evscal, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claev2 "BLAS_FUNC(claev2)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, s *rt1, s *rt2, s *cs1, npy_complex64 *sn1) nogil
+cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil:
+    
+    _fortran_claev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clag2z "BLAS_FUNC(clag2z)"(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info) nogil
+cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clag2z(m, n, sa, ldsa, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clags2 "BLAS_FUNC(clags2)"(bint *upper, s *a1, npy_complex64 *a2, s *a3, s *b1, npy_complex64 *b2, s *b3, s *csu, npy_complex64 *snu, s *csv, npy_complex64 *snv, s *csq, npy_complex64 *snq) nogil
+cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil:
+    
+    _fortran_clags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clagtm "BLAS_FUNC(clagtm)"(char *trans, int *n, int *nrhs, s *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, s *beta, npy_complex64 *b, int *ldb) nogil
+cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahef "BLAS_FUNC(clahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) nogil
+cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_clahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahqr "BLAS_FUNC(clahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info) nogil
+cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_clahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahr2 "BLAS_FUNC(clahr2)"(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy) nogil
+cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil:
+    
+    _fortran_clahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claic1 "BLAS_FUNC(claic1)"(int *job, int *j, npy_complex64 *x, s *sest, npy_complex64 *w, npy_complex64 *gamma, s *sestpr, npy_complex64 *s, npy_complex64 *c) nogil
+cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil:
+    
+    _fortran_claic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clals0 "BLAS_FUNC(clals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) nogil
+cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_clals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clalsa "BLAS_FUNC(clalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) nogil
+cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_clalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clalsd "BLAS_FUNC(clalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, npy_complex64 *b, int *ldb, s *rcond, int *rank, npy_complex64 *work, s *rwork, int *iwork, int *info) nogil
+cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_clalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clangb "BLAS_FUNC(clangb)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clange "BLAS_FUNC(clange)"(char *norm, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clangt "BLAS_FUNC(clangt)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du) nogil
+cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil:
+    
+    return _fortran_clangt(norm, n, dl, d, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhb "BLAS_FUNC(clanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clanhb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhe "BLAS_FUNC(clanhe)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clanhe(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhf "BLAS_FUNC(clanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, s *work) nogil
+cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil:
+    
+    return _fortran_clanhf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhp "BLAS_FUNC(clanhp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clanhp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhs "BLAS_FUNC(clanhs)"(char *norm, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanht "BLAS_FUNC(clanht)"(char *norm, int *n, s *d, npy_complex64 *e) nogil
+cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil:
+    
+    return _fortran_clanht(norm, n, d, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansb "BLAS_FUNC(clansb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansp "BLAS_FUNC(clansp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansy "BLAS_FUNC(clansy)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantb "BLAS_FUNC(clantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantp "BLAS_FUNC(clantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantr "BLAS_FUNC(clantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapll "BLAS_FUNC(clapll)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *ssmin) nogil
+cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil:
+    
+    _fortran_clapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapmr "BLAS_FUNC(clapmr)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil
+cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_clapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapmt "BLAS_FUNC(clapmt)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil
+cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_clapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqgb "BLAS_FUNC(claqgb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqge "BLAS_FUNC(claqge)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhb "BLAS_FUNC(claqhb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhe "BLAS_FUNC(claqhe)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhe(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhp "BLAS_FUNC(claqhp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqp2 "BLAS_FUNC(claqp2)"(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *work) nogil
+cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil:
+    
+    _fortran_claqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqps "BLAS_FUNC(claqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf) nogil
+cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil:
+    
+    _fortran_claqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr0 "BLAS_FUNC(claqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_claqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr1 "BLAS_FUNC(claqr1)"(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v) nogil
+cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil:
+    
+    _fortran_claqr1(n, h, ldh, s1, s2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr2 "BLAS_FUNC(claqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) nogil
+cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil:
+    
+    _fortran_claqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr3 "BLAS_FUNC(claqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) nogil
+cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil:
+    
+    _fortran_claqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr4 "BLAS_FUNC(claqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_claqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr5 "BLAS_FUNC(claqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh) nogil
+cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_claqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsb "BLAS_FUNC(claqsb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsp "BLAS_FUNC(claqsp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsy "BLAS_FUNC(claqsy)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clar1v "BLAS_FUNC(clar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, npy_complex64 *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) nogil
+cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil:
+    
+    _fortran_clar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clar2v "BLAS_FUNC(clar2v)"(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, s *c, npy_complex64 *s, int *incc) nogil
+cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil:
+    
+    _fortran_clar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarcm "BLAS_FUNC(clarcm)"(int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil
+cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil:
+    
+    _fortran_clarcm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarf "BLAS_FUNC(clarf)"(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfb "BLAS_FUNC(clarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) nogil
+cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil:
+    
+    _fortran_clarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfg "BLAS_FUNC(clarfg)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil
+cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil:
+    
+    _fortran_clarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfgp "BLAS_FUNC(clarfgp)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil
+cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil:
+    
+    _fortran_clarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarft "BLAS_FUNC(clarft)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil
+cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil:
+    
+    _fortran_clarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfx "BLAS_FUNC(clarfx)"(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clargv "BLAS_FUNC(clargv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, int *incc) nogil
+cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil:
+    
+    _fortran_clargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarnv "BLAS_FUNC(clarnv)"(int *idist, int *iseed, int *n, npy_complex64 *x) nogil
+cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil:
+    
+    _fortran_clarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarrv "BLAS_FUNC(clarrv)"(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) nogil
+cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_clarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clartg "BLAS_FUNC(clartg)"(npy_complex64 *f, npy_complex64 *g, s *cs, npy_complex64 *sn, npy_complex64 *r) nogil
+cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil:
+    
+    _fortran_clartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clartv "BLAS_FUNC(clartv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, npy_complex64 *s, int *incc) nogil
+cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil:
+    
+    _fortran_clartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarz "BLAS_FUNC(clarz)"(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarzb "BLAS_FUNC(clarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) nogil
+cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil:
+    
+    _fortran_clarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarzt "BLAS_FUNC(clarzt)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil
+cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil:
+    
+    _fortran_clarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clascl "BLAS_FUNC(clascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claset "BLAS_FUNC(claset)"(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda) nogil
+cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil:
+    
+    _fortran_claset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clasr "BLAS_FUNC(clasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, npy_complex64 *a, int *lda) nogil
+cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil:
+    
+    _fortran_clasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_classq "BLAS_FUNC(classq)"(int *n, npy_complex64 *x, int *incx, s *scale, s *sumsq) nogil
+cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil:
+    
+    _fortran_classq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claswp "BLAS_FUNC(claswp)"(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_claswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clasyf "BLAS_FUNC(clasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) nogil
+cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_clasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatbs "BLAS_FUNC(clatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil
+cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_clatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatdf "BLAS_FUNC(clatdf)"(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil
+cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_clatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatps "BLAS_FUNC(clatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil
+cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_clatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrd "BLAS_FUNC(clatrd)"(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, s *e, npy_complex64 *tau, npy_complex64 *w, int *ldw) nogil
+cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil:
+    
+    _fortran_clatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrs "BLAS_FUNC(clatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil
+cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_clatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrz "BLAS_FUNC(clatrz)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work) nogil
+cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil:
+    
+    _fortran_clatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clauu2 "BLAS_FUNC(clauu2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clauum "BLAS_FUNC(clauum)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbcon "BLAS_FUNC(cpbcon)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbequ "BLAS_FUNC(cpbequ)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbrfs "BLAS_FUNC(cpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbstf "BLAS_FUNC(cpbstf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbsv "BLAS_FUNC(cpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbsvx "BLAS_FUNC(cpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtf2 "BLAS_FUNC(cpbtf2)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtrf "BLAS_FUNC(cpbtrf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtrs "BLAS_FUNC(cpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftrf "BLAS_FUNC(cpftrf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil
+cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_cpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftri "BLAS_FUNC(cpftri)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil
+cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_cpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftrs "BLAS_FUNC(cpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpocon "BLAS_FUNC(cpocon)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpoequ "BLAS_FUNC(cpoequ)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpoequb "BLAS_FUNC(cpoequb)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cporfs "BLAS_FUNC(cporfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cposv "BLAS_FUNC(cposv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cposvx "BLAS_FUNC(cposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotf2 "BLAS_FUNC(cpotf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotrf "BLAS_FUNC(cpotrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotri "BLAS_FUNC(cpotri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotrs "BLAS_FUNC(cpotrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppcon "BLAS_FUNC(cppcon)"(char *uplo, int *n, npy_complex64 *ap, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cppcon(uplo, n, ap, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppequ "BLAS_FUNC(cppequ)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, int *info) nogil
+cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpprfs "BLAS_FUNC(cpprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppsv "BLAS_FUNC(cppsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppsvx "BLAS_FUNC(cppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptrf "BLAS_FUNC(cpptrf)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil
+cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_cpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptri "BLAS_FUNC(cpptri)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil
+cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_cpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptrs "BLAS_FUNC(cpptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpstf2 "BLAS_FUNC(cpstf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpstrf "BLAS_FUNC(cpstrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptcon "BLAS_FUNC(cptcon)"(int *n, s *d, npy_complex64 *e, s *anorm, s *rcond, s *rwork, int *info) nogil
+cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptcon(n, d, e, anorm, rcond, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpteqr "BLAS_FUNC(cpteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil
+cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptrfs "BLAS_FUNC(cptrfs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptsv "BLAS_FUNC(cptsv)"(int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptsvx "BLAS_FUNC(cptsvx)"(char *fact, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpttrf "BLAS_FUNC(cpttrf)"(int *n, s *d, npy_complex64 *e, int *info) nogil
+cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil:
+    
+    _fortran_cpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpttrs "BLAS_FUNC(cpttrs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpttrs(uplo, n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptts2 "BLAS_FUNC(cptts2)"(int *iuplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb) nogil
+cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_cptts2(iuplo, n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_crot "BLAS_FUNC(crot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, npy_complex64 *s) nogil
+cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil:
+    
+    _fortran_crot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspcon "BLAS_FUNC(cspcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_cspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspmv "BLAS_FUNC(cspmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspr "BLAS_FUNC(cspr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
+cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil:
+    
+    _fortran_cspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csprfs "BLAS_FUNC(csprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_csprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspsv "BLAS_FUNC(cspsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspsvx "BLAS_FUNC(cspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptrf "BLAS_FUNC(csptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil
+cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_csptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptri "BLAS_FUNC(csptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptrs "BLAS_FUNC(csptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_csptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csrscl "BLAS_FUNC(csrscl)"(int *n, s *sa, npy_complex64 *sx, int *incx) nogil
+cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil:
+    
+    _fortran_csrscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstedc "BLAS_FUNC(cstedc)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstegr "BLAS_FUNC(cstegr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstein "BLAS_FUNC(cstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_cstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstemr "BLAS_FUNC(cstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csteqr "BLAS_FUNC(csteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil
+cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_csteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csycon "BLAS_FUNC(csycon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_csycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyconv "BLAS_FUNC(csyconv)"(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyequb "BLAS_FUNC(csyequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil
+cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil:
+    
+    _fortran_csyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csymv "BLAS_FUNC(csymv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_csymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyr "BLAS_FUNC(csyr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
+cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
+    
+    _fortran_csyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyrfs "BLAS_FUNC(csyrfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_csyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csysv "BLAS_FUNC(csysv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csysvx "BLAS_FUNC(csysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_csysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyswapr "BLAS_FUNC(csyswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil
+cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_csyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytf2 "BLAS_FUNC(csytf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_csytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrf "BLAS_FUNC(csytrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri "BLAS_FUNC(csytri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri2 "BLAS_FUNC(csytri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri2x "BLAS_FUNC(csytri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil
+cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_csytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrs "BLAS_FUNC(csytrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_csytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrs2 "BLAS_FUNC(csytrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil
+cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil:
+    
+    _fortran_csytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbcon "BLAS_FUNC(ctbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbrfs "BLAS_FUNC(ctbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbtrs "BLAS_FUNC(ctbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfsm "BLAS_FUNC(ctfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb) nogil
+cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_ctfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctftri "BLAS_FUNC(ctftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info) nogil
+cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_ctftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfttp "BLAS_FUNC(ctfttp)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info) nogil
+cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfttr "BLAS_FUNC(ctfttr)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgevc "BLAS_FUNC(ctgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgex2 "BLAS_FUNC(ctgex2)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info) nogil
+cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil:
+    
+    _fortran_ctgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgexc "BLAS_FUNC(ctgexc)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info) nogil
+cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ctgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsen "BLAS_FUNC(ctgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, s *pl, s *pr, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ctgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsja "BLAS_FUNC(ctgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info) nogil
+cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_ctgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsna "BLAS_FUNC(ctgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ctgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsy2 "BLAS_FUNC(ctgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) nogil
+cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil:
+    
+    _fortran_ctgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsyl "BLAS_FUNC(ctgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ctgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpcon "BLAS_FUNC(ctpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpmqrt "BLAS_FUNC(ctpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil
+cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil:
+    
+    _fortran_ctpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpqrt "BLAS_FUNC(ctpqrt)"(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil
+cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil:
+    
+    _fortran_ctpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpqrt2 "BLAS_FUNC(ctpqrt2)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_ctpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctprfb "BLAS_FUNC(ctprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork) nogil
+cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil:
+    
+    _fortran_ctprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctprfs "BLAS_FUNC(ctprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctptri "BLAS_FUNC(ctptri)"(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info) nogil
+cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctptrs "BLAS_FUNC(ctptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpttf "BLAS_FUNC(ctpttf)"(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info) nogil
+cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil:
+    
+    _fortran_ctpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpttr "BLAS_FUNC(ctpttr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrcon "BLAS_FUNC(ctrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrevc "BLAS_FUNC(ctrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrexc "BLAS_FUNC(ctrexc)"(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info) nogil
+cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ctrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrrfs "BLAS_FUNC(ctrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsen "BLAS_FUNC(ctrsen)"(char *job, char *compq, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, s *s, s *sep, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ctrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsna "BLAS_FUNC(ctrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, s *rwork, int *info) nogil
+cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsyl "BLAS_FUNC(ctrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *scale, int *info) nogil
+cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil:
+    
+    _fortran_ctrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrti2 "BLAS_FUNC(ctrti2)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrtri "BLAS_FUNC(ctrtri)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrtrs "BLAS_FUNC(ctrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrttf "BLAS_FUNC(ctrttf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info) nogil
+cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil:
+    
+    _fortran_ctrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrttp "BLAS_FUNC(ctrttp)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info) nogil
+cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctzrzf "BLAS_FUNC(ctzrzf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ctzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunbdb "BLAS_FUNC(cunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, s *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cuncsd "BLAS_FUNC(cuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) nogil
+cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_cuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cung2l "BLAS_FUNC(cung2l)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cung2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cung2r "BLAS_FUNC(cung2r)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cung2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungbr "BLAS_FUNC(cungbr)"(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunghr "BLAS_FUNC(cunghr)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungl2 "BLAS_FUNC(cungl2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cungl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunglq "BLAS_FUNC(cunglq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungql "BLAS_FUNC(cungql)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungqr "BLAS_FUNC(cungqr)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungr2 "BLAS_FUNC(cungr2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cungr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungrq "BLAS_FUNC(cungrq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungtr "BLAS_FUNC(cungtr)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunm2l "BLAS_FUNC(cunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunm2r "BLAS_FUNC(cunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmbr "BLAS_FUNC(cunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmhr "BLAS_FUNC(cunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunml2 "BLAS_FUNC(cunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmlq "BLAS_FUNC(cunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmql "BLAS_FUNC(cunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmqr "BLAS_FUNC(cunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmr2 "BLAS_FUNC(cunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmr3 "BLAS_FUNC(cunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmrq "BLAS_FUNC(cunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmrz "BLAS_FUNC(cunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmtr "BLAS_FUNC(cunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cupgtr "BLAS_FUNC(cupgtr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil
+cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil:
+    
+    _fortran_cupgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cupmtr "BLAS_FUNC(cupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbbcsd "BLAS_FUNC(dbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) nogil
+cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbdsdc "BLAS_FUNC(dbdsdc)"(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) nogil
+cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbdsqr "BLAS_FUNC(dbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) nogil
+cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ddisna "BLAS_FUNC(ddisna)"(char *job, int *m, int *n, d *d, d *sep, int *info) nogil
+cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil:
+    
+    _fortran_ddisna(job, m, n, d, sep, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbbrd "BLAS_FUNC(dgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) nogil
+cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbcon "BLAS_FUNC(dgbcon)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbequ "BLAS_FUNC(dgbequ)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbequb "BLAS_FUNC(dgbequb)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbrfs "BLAS_FUNC(dgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbsv "BLAS_FUNC(dgbsv)"(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbsvx "BLAS_FUNC(dgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtf2 "BLAS_FUNC(dgbtf2)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtrf "BLAS_FUNC(dgbtrf)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtrs "BLAS_FUNC(dgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebak "BLAS_FUNC(dgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) nogil
+cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_dgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebal "BLAS_FUNC(dgebal)"(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil
+cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil:
+    
+    _fortran_dgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebd2 "BLAS_FUNC(dgebd2)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) nogil
+cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebrd "BLAS_FUNC(dgebrd)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) nogil
+cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgecon "BLAS_FUNC(dgecon)"(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeequ "BLAS_FUNC(dgeequ)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeequb "BLAS_FUNC(dgeequb)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgees "BLAS_FUNC(dgees)"(char *jobvs, char *sort, _dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) nogil
+cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dgees(jobvs, sort, <_dselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeesx "BLAS_FUNC(dgeesx)"(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dgeesx(jobvs, sort, <_dselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeev "BLAS_FUNC(dgeev)"(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) nogil
+cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeevx "BLAS_FUNC(dgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgehd2 "BLAS_FUNC(dgehd2)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgehrd "BLAS_FUNC(dgehrd)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgejsv "BLAS_FUNC(dgejsv)"(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelq2 "BLAS_FUNC(dgelq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelqf "BLAS_FUNC(dgelqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgels "BLAS_FUNC(dgels)"(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) nogil
+cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelsd "BLAS_FUNC(dgelsd)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelss "BLAS_FUNC(dgelss)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) nogil
+cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelsy "BLAS_FUNC(dgelsy)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) nogil
+cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgemqrt "BLAS_FUNC(dgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) nogil
+cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeql2 "BLAS_FUNC(dgeql2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqlf "BLAS_FUNC(dgeqlf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqp3 "BLAS_FUNC(dgeqp3)"(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqr2 "BLAS_FUNC(dgeqr2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqr2p "BLAS_FUNC(dgeqr2p)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrf "BLAS_FUNC(dgeqrf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrfp "BLAS_FUNC(dgeqrfp)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt "BLAS_FUNC(dgeqrt)"(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) nogil
+cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt2 "BLAS_FUNC(dgeqrt2)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil
+cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt3 "BLAS_FUNC(dgeqrt3)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil
+cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerfs "BLAS_FUNC(dgerfs)"(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerq2 "BLAS_FUNC(dgerq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerqf "BLAS_FUNC(dgerqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesc2 "BLAS_FUNC(dgesc2)"(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) nogil
+cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil:
+    
+    _fortran_dgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesdd "BLAS_FUNC(dgesdd)"(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesv "BLAS_FUNC(dgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvd "BLAS_FUNC(dgesvd)"(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) nogil
+cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvj "BLAS_FUNC(dgesvj)"(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) nogil
+cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvx "BLAS_FUNC(dgesvx)"(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetc2 "BLAS_FUNC(dgetc2)"(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_dgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetf2 "BLAS_FUNC(dgetf2)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetrf "BLAS_FUNC(dgetrf)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetri "BLAS_FUNC(dgetri)"(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetrs "BLAS_FUNC(dgetrs)"(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggbak "BLAS_FUNC(dggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) nogil
+cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_dggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggbal "BLAS_FUNC(dggbal)"(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) nogil
+cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil:
+    
+    _fortran_dggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgges "BLAS_FUNC(dgges)"(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) nogil
+cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dgges(jobvsl, jobvsr, sort, <_dselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggesx "BLAS_FUNC(dggesx)"(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dggesx(jobvsl, jobvsr, sort, <_dselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggev "BLAS_FUNC(dggev)"(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) nogil
+cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggevx "BLAS_FUNC(dggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) nogil
+cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggglm "BLAS_FUNC(dggglm)"(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) nogil
+cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgghrd "BLAS_FUNC(dgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) nogil
+cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_dgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgglse "BLAS_FUNC(dgglse)"(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) nogil
+cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggqrf "BLAS_FUNC(dggqrf)"(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) nogil
+cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggrqf "BLAS_FUNC(dggrqf)"(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) nogil
+cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgsvj0 "BLAS_FUNC(dgsvj0)"(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) nogil
+cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgsvj1 "BLAS_FUNC(dgsvj1)"(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) nogil
+cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtcon "BLAS_FUNC(dgtcon)"(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtrfs "BLAS_FUNC(dgtrfs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtsv "BLAS_FUNC(dgtsv)"(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) nogil
+cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtsvx "BLAS_FUNC(dgtsvx)"(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgttrf "BLAS_FUNC(dgttrf)"(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) nogil
+cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgttrs "BLAS_FUNC(dgttrs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtts2 "BLAS_FUNC(dgtts2)"(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) nogil
+cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhgeqz "BLAS_FUNC(dhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhsein "BLAS_FUNC(dhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) nogil
+cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_dhsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhseqr "BLAS_FUNC(dhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dhseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    bint _fortran_disnan "BLAS_FUNC(disnan)"(d *din) nogil
+cdef bint disnan(d *din) noexcept nogil:
+    
+    return _fortran_disnan(din)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlabad "BLAS_FUNC(dlabad)"(d *small, d *large) nogil
+cdef void dlabad(d *small, d *large) noexcept nogil:
+    
+    _fortran_dlabad(small, large)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlabrd "BLAS_FUNC(dlabrd)"(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) nogil
+cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil:
+    
+    _fortran_dlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacn2 "BLAS_FUNC(dlacn2)"(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) nogil
+cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_dlacn2(n, v, x, isgn, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacon "BLAS_FUNC(dlacon)"(int *n, d *v, d *x, int *isgn, d *est, int *kase) nogil
+cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil:
+    
+    _fortran_dlacon(n, v, x, isgn, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacpy "BLAS_FUNC(dlacpy)"(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dlacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dladiv "BLAS_FUNC(dladiv)"(d *a, d *b, d *c, d *d, d *p, d *q) nogil
+cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil:
+    
+    _fortran_dladiv(a, b, c, d, p, q)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlae2 "BLAS_FUNC(dlae2)"(d *a, d *b, d *c, d *rt1, d *rt2) nogil
+cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil:
+    
+    _fortran_dlae2(a, b, c, rt1, rt2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaebz "BLAS_FUNC(dlaebz)"(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) nogil
+cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed0 "BLAS_FUNC(dlaed0)"(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) nogil
+cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed1 "BLAS_FUNC(dlaed1)"(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) nogil
+cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed2 "BLAS_FUNC(dlaed2)"(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) nogil
+cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_dlaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed3 "BLAS_FUNC(dlaed3)"(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) nogil
+cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil:
+    
+    _fortran_dlaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed4 "BLAS_FUNC(dlaed4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) nogil
+cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil:
+    
+    _fortran_dlaed4(n, i, d, z, delta, rho, dlam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed5 "BLAS_FUNC(dlaed5)"(int *i, d *d, d *z, d *delta, d *rho, d *dlam) nogil
+cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil:
+    
+    _fortran_dlaed5(i, d, z, delta, rho, dlam)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed6 "BLAS_FUNC(dlaed6)"(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) nogil
+cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dlaed6(kniter, orgati, rho, d, z, finit, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed7 "BLAS_FUNC(dlaed7)"(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) nogil
+cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed8 "BLAS_FUNC(dlaed8)"(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) nogil
+cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil:
+    
+    _fortran_dlaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed9 "BLAS_FUNC(dlaed9)"(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) nogil
+cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil:
+    
+    _fortran_dlaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaeda "BLAS_FUNC(dlaeda)"(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) nogil
+cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil:
+    
+    _fortran_dlaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaein "BLAS_FUNC(dlaein)"(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) nogil
+cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil:
+    
+    _fortran_dlaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaev2 "BLAS_FUNC(dlaev2)"(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) nogil
+cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil:
+    
+    _fortran_dlaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaexc "BLAS_FUNC(dlaexc)"(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) nogil
+cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlag2 "BLAS_FUNC(dlag2)"(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) nogil
+cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil:
+    
+    _fortran_dlag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlag2s "BLAS_FUNC(dlag2s)"(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil
+cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_dlag2s(m, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlags2 "BLAS_FUNC(dlags2)"(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) nogil
+cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil:
+    
+    _fortran_dlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagtf "BLAS_FUNC(dlagtf)"(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) nogil
+cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil:
+    
+    _fortran_dlagtf(n, a, lambda_, b, c, tol, d, in_, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagtm "BLAS_FUNC(dlagtm)"(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) nogil
+cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagts "BLAS_FUNC(dlagts)"(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) nogil
+cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil:
+    
+    _fortran_dlagts(job, n, a, b, c, d, in_, y, tol, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagv2 "BLAS_FUNC(dlagv2)"(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) nogil
+cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil:
+    
+    _fortran_dlagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlahqr "BLAS_FUNC(dlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) nogil
+cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_dlahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlahr2 "BLAS_FUNC(dlahr2)"(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) nogil
+cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil:
+    
+    _fortran_dlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaic1 "BLAS_FUNC(dlaic1)"(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) nogil
+cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil:
+    
+    _fortran_dlaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaln2 "BLAS_FUNC(dlaln2)"(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) nogil
+cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil:
+    
+    _fortran_dlaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlals0 "BLAS_FUNC(dlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) nogil
+cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlalsa "BLAS_FUNC(dlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) nogil
+cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlalsd "BLAS_FUNC(dlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) nogil
+cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlamch "BLAS_FUNC(dlamch)"(char *cmach) nogil
+cdef d dlamch(char *cmach) noexcept nogil:
+    
+    return _fortran_dlamch(cmach)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlamrg "BLAS_FUNC(dlamrg)"(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) nogil
+cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil:
+    
+    _fortran_dlamrg(n1, n2, a, dtrd1, dtrd2, index_bn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_dlaneg "BLAS_FUNC(dlaneg)"(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) nogil
+cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil:
+    
+    return _fortran_dlaneg(n, d, lld, sigma, pivmin, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlangb "BLAS_FUNC(dlangb)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) nogil
+cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlange "BLAS_FUNC(dlange)"(char *norm, int *m, int *n, d *a, int *lda, d *work) nogil
+cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlangt "BLAS_FUNC(dlangt)"(char *norm, int *n, d *dl, d *d_, d *du) nogil
+cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil:
+    
+    return _fortran_dlangt(norm, n, dl, d_, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlanhs "BLAS_FUNC(dlanhs)"(char *norm, int *n, d *a, int *lda, d *work) nogil
+cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansb "BLAS_FUNC(dlansb)"(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) nogil
+cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansf "BLAS_FUNC(dlansf)"(char *norm, char *transr, char *uplo, int *n, d *a, d *work) nogil
+cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil:
+    
+    return _fortran_dlansf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansp "BLAS_FUNC(dlansp)"(char *norm, char *uplo, int *n, d *ap, d *work) nogil
+cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil:
+    
+    return _fortran_dlansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlanst "BLAS_FUNC(dlanst)"(char *norm, int *n, d *d_, d *e) nogil
+cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil:
+    
+    return _fortran_dlanst(norm, n, d_, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansy "BLAS_FUNC(dlansy)"(char *norm, char *uplo, int *n, d *a, int *lda, d *work) nogil
+cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantb "BLAS_FUNC(dlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) nogil
+cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantp "BLAS_FUNC(dlantp)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) nogil
+cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil:
+    
+    return _fortran_dlantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantr "BLAS_FUNC(dlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) nogil
+cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlanv2 "BLAS_FUNC(dlanv2)"(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) nogil
+cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil:
+    
+    _fortran_dlanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapll "BLAS_FUNC(dlapll)"(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) nogil
+cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil:
+    
+    _fortran_dlapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapmr "BLAS_FUNC(dlapmr)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil
+cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_dlapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapmt "BLAS_FUNC(dlapmt)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil
+cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_dlapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlapy2 "BLAS_FUNC(dlapy2)"(d *x, d *y) nogil
+cdef d dlapy2(d *x, d *y) noexcept nogil:
+    
+    return _fortran_dlapy2(x, y)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlapy3 "BLAS_FUNC(dlapy3)"(d *x, d *y, d *z) nogil
+cdef d dlapy3(d *x, d *y, d *z) noexcept nogil:
+    
+    return _fortran_dlapy3(x, y, z)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqgb "BLAS_FUNC(dlaqgb)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqge "BLAS_FUNC(dlaqge)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqp2 "BLAS_FUNC(dlaqp2)"(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) nogil
+cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil:
+    
+    _fortran_dlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqps "BLAS_FUNC(dlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) nogil
+cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil:
+    
+    _fortran_dlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr0 "BLAS_FUNC(dlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr1 "BLAS_FUNC(dlaqr1)"(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) nogil
+cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil:
+    
+    _fortran_dlaqr1(n, h, ldh, sr1, si1, sr2, si2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr2 "BLAS_FUNC(dlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) nogil
+cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil:
+    
+    _fortran_dlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr3 "BLAS_FUNC(dlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) nogil
+cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil:
+    
+    _fortran_dlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr4 "BLAS_FUNC(dlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr5 "BLAS_FUNC(dlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) nogil
+cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_dlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsb "BLAS_FUNC(dlaqsb)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsp "BLAS_FUNC(dlaqsp)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsy "BLAS_FUNC(dlaqsy)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqtr "BLAS_FUNC(dlaqtr)"(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) nogil
+cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlar1v "BLAS_FUNC(dlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) nogil
+cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil:
+    
+    _fortran_dlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlar2v "BLAS_FUNC(dlar2v)"(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) nogil
+cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil:
+    
+    _fortran_dlar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarf "BLAS_FUNC(dlarf)"(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfb "BLAS_FUNC(dlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) nogil
+cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil:
+    
+    _fortran_dlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfg "BLAS_FUNC(dlarfg)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil
+cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil:
+    
+    _fortran_dlarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfgp "BLAS_FUNC(dlarfgp)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil
+cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil:
+    
+    _fortran_dlarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarft "BLAS_FUNC(dlarft)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil
+cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil:
+    
+    _fortran_dlarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfx "BLAS_FUNC(dlarfx)"(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlargv "BLAS_FUNC(dlargv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) nogil
+cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil:
+    
+    _fortran_dlargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarnv "BLAS_FUNC(dlarnv)"(int *idist, int *iseed, int *n, d *x) nogil
+cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil:
+    
+    _fortran_dlarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarra "BLAS_FUNC(dlarra)"(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) nogil
+cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil:
+    
+    _fortran_dlarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrb "BLAS_FUNC(dlarrb)"(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) nogil
+cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil:
+    
+    _fortran_dlarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrc "BLAS_FUNC(dlarrc)"(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) nogil
+cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil:
+    
+    _fortran_dlarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrd "BLAS_FUNC(dlarrd)"(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) nogil
+cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarre "BLAS_FUNC(dlarre)"(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) nogil
+cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrf "BLAS_FUNC(dlarrf)"(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) nogil
+cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrj "BLAS_FUNC(dlarrj)"(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) nogil
+cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil:
+    
+    _fortran_dlarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrk "BLAS_FUNC(dlarrk)"(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) nogil
+cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil:
+    
+    _fortran_dlarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrr "BLAS_FUNC(dlarrr)"(int *n, d *d, d *e, int *info) nogil
+cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dlarrr(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrv "BLAS_FUNC(dlarrv)"(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) nogil
+cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartg "BLAS_FUNC(dlartg)"(d *f, d *g, d *cs, d *sn, d *r) nogil
+cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil:
+    
+    _fortran_dlartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartgp "BLAS_FUNC(dlartgp)"(d *f, d *g, d *cs, d *sn, d *r) nogil
+cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil:
+    
+    _fortran_dlartgp(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartgs "BLAS_FUNC(dlartgs)"(d *x, d *y, d *sigma, d *cs, d *sn) nogil
+cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil:
+    
+    _fortran_dlartgs(x, y, sigma, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartv "BLAS_FUNC(dlartv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) nogil
+cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil:
+    
+    _fortran_dlartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaruv "BLAS_FUNC(dlaruv)"(int *iseed, int *n, d *x) nogil
+cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil:
+    
+    _fortran_dlaruv(iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarz "BLAS_FUNC(dlarz)"(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarzb "BLAS_FUNC(dlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) nogil
+cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil:
+    
+    _fortran_dlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarzt "BLAS_FUNC(dlarzt)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil
+cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil:
+    
+    _fortran_dlarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlas2 "BLAS_FUNC(dlas2)"(d *f, d *g, d *h, d *ssmin, d *ssmax) nogil
+cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil:
+    
+    _fortran_dlas2(f, g, h, ssmin, ssmax)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlascl "BLAS_FUNC(dlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) nogil
+cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd0 "BLAS_FUNC(dlasd0)"(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) nogil
+cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd1 "BLAS_FUNC(dlasd1)"(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) nogil
+cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd2 "BLAS_FUNC(dlasd2)"(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) nogil
+cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_dlasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd3 "BLAS_FUNC(dlasd3)"(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) nogil
+cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil:
+    
+    _fortran_dlasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd4 "BLAS_FUNC(dlasd4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) nogil
+cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd4(n, i, d, z, delta, rho, sigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd5 "BLAS_FUNC(dlasd5)"(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) nogil
+cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil:
+    
+    _fortran_dlasd5(i, d, z, delta, rho, dsigma, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd6 "BLAS_FUNC(dlasd6)"(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) nogil
+cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd7 "BLAS_FUNC(dlasd7)"(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) nogil
+cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil:
+    
+    _fortran_dlasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd8 "BLAS_FUNC(dlasd8)"(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) nogil
+cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasda "BLAS_FUNC(dlasda)"(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) nogil
+cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasdq "BLAS_FUNC(dlasdq)"(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) nogil
+cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasdt "BLAS_FUNC(dlasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil
+cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil:
+    
+    _fortran_dlasdt(n, lvl, nd, inode, ndiml, ndimr, msub)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaset "BLAS_FUNC(dlaset)"(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) nogil
+cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dlaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq1 "BLAS_FUNC(dlasq1)"(int *n, d *d, d *e, d *work, int *info) nogil
+cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasq1(n, d, e, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq2 "BLAS_FUNC(dlasq2)"(int *n, d *z, int *info) nogil
+cdef void dlasq2(int *n, d *z, int *info) noexcept nogil:
+    
+    _fortran_dlasq2(n, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq3 "BLAS_FUNC(dlasq3)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) nogil
+cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil:
+    
+    _fortran_dlasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq4 "BLAS_FUNC(dlasq4)"(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) nogil
+cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil:
+    
+    _fortran_dlasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq6 "BLAS_FUNC(dlasq6)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) nogil
+cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil:
+    
+    _fortran_dlasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasr "BLAS_FUNC(dlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) nogil
+cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dlasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasrt "BLAS_FUNC(dlasrt)"(char *id, int *n, d *d, int *info) nogil
+cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil:
+    
+    _fortran_dlasrt(id, n, d, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlassq "BLAS_FUNC(dlassq)"(int *n, d *x, int *incx, d *scale, d *sumsq) nogil
+cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil:
+    
+    _fortran_dlassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasv2 "BLAS_FUNC(dlasv2)"(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) nogil
+cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil:
+    
+    _fortran_dlasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaswp "BLAS_FUNC(dlaswp)"(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_dlaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasy2 "BLAS_FUNC(dlasy2)"(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) nogil
+cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil:
+    
+    _fortran_dlasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasyf "BLAS_FUNC(dlasyf)"(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) nogil
+cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_dlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlat2s "BLAS_FUNC(dlat2s)"(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil
+cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_dlat2s(uplo, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatbs "BLAS_FUNC(dlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) nogil
+cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_dlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatdf "BLAS_FUNC(dlatdf)"(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil
+cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_dlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatps "BLAS_FUNC(dlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) nogil
+cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_dlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrd "BLAS_FUNC(dlatrd)"(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) nogil
+cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil:
+    
+    _fortran_dlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrs "BLAS_FUNC(dlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) nogil
+cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_dlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrz "BLAS_FUNC(dlatrz)"(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) nogil
+cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil:
+    
+    _fortran_dlatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlauu2 "BLAS_FUNC(dlauu2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlauum "BLAS_FUNC(dlauum)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dopgtr "BLAS_FUNC(dopgtr)"(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) nogil
+cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil:
+    
+    _fortran_dopgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dopmtr "BLAS_FUNC(dopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorbdb "BLAS_FUNC(dorbdb)"(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) nogil
+cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorcsd "BLAS_FUNC(dorcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorg2l "BLAS_FUNC(dorg2l)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorg2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorg2r "BLAS_FUNC(dorg2r)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorg2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgbr "BLAS_FUNC(dorgbr)"(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorghr "BLAS_FUNC(dorghr)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgl2 "BLAS_FUNC(dorgl2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorgl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorglq "BLAS_FUNC(dorglq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgql "BLAS_FUNC(dorgql)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgqr "BLAS_FUNC(dorgqr)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgr2 "BLAS_FUNC(dorgr2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorgr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgrq "BLAS_FUNC(dorgrq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgtr "BLAS_FUNC(dorgtr)"(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorm2l "BLAS_FUNC(dorm2l)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorm2r "BLAS_FUNC(dorm2r)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormbr "BLAS_FUNC(dormbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormhr "BLAS_FUNC(dormhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorml2 "BLAS_FUNC(dorml2)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormlq "BLAS_FUNC(dormlq)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormql "BLAS_FUNC(dormql)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormqr "BLAS_FUNC(dormqr)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormr2 "BLAS_FUNC(dormr2)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormr3 "BLAS_FUNC(dormr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormrq "BLAS_FUNC(dormrq)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormrz "BLAS_FUNC(dormrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormtr "BLAS_FUNC(dormtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbcon "BLAS_FUNC(dpbcon)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbequ "BLAS_FUNC(dpbequ)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbrfs "BLAS_FUNC(dpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbstf "BLAS_FUNC(dpbstf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbsv "BLAS_FUNC(dpbsv)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbsvx "BLAS_FUNC(dpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtf2 "BLAS_FUNC(dpbtf2)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtrf "BLAS_FUNC(dpbtrf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtrs "BLAS_FUNC(dpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftrf "BLAS_FUNC(dpftrf)"(char *transr, char *uplo, int *n, d *a, int *info) nogil
+cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftri "BLAS_FUNC(dpftri)"(char *transr, char *uplo, int *n, d *a, int *info) nogil
+cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftrs "BLAS_FUNC(dpftrs)"(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) nogil
+cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpocon "BLAS_FUNC(dpocon)"(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpoequ "BLAS_FUNC(dpoequ)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpoequb "BLAS_FUNC(dpoequb)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dporfs "BLAS_FUNC(dporfs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dposv "BLAS_FUNC(dposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dposvx "BLAS_FUNC(dposvx)"(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotf2 "BLAS_FUNC(dpotf2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotrf "BLAS_FUNC(dpotrf)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotri "BLAS_FUNC(dpotri)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotrs "BLAS_FUNC(dpotrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppcon "BLAS_FUNC(dppcon)"(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dppcon(uplo, n, ap, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppequ "BLAS_FUNC(dppequ)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) nogil
+cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpprfs "BLAS_FUNC(dpprfs)"(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppsv "BLAS_FUNC(dppsv)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppsvx "BLAS_FUNC(dppsvx)"(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptrf "BLAS_FUNC(dpptrf)"(char *uplo, int *n, d *ap, int *info) nogil
+cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptri "BLAS_FUNC(dpptri)"(char *uplo, int *n, d *ap, int *info) nogil
+cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptrs "BLAS_FUNC(dpptrs)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpstf2 "BLAS_FUNC(dpstf2)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpstrf "BLAS_FUNC(dpstrf)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptcon "BLAS_FUNC(dptcon)"(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) nogil
+cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptcon(n, d, e, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpteqr "BLAS_FUNC(dpteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptrfs "BLAS_FUNC(dptrfs)"(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) nogil
+cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptsv "BLAS_FUNC(dptsv)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil
+cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptsvx "BLAS_FUNC(dptsvx)"(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) nogil
+cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpttrf "BLAS_FUNC(dpttrf)"(int *n, d *d, d *e, int *info) nogil
+cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpttrs "BLAS_FUNC(dpttrs)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil
+cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpttrs(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptts2 "BLAS_FUNC(dptts2)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) nogil
+cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dptts2(n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_drscl "BLAS_FUNC(drscl)"(int *n, d *sa, d *sx, int *incx) nogil
+cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil:
+    
+    _fortran_drscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbev "BLAS_FUNC(dsbev)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbevd "BLAS_FUNC(dsbevd)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbevx "BLAS_FUNC(dsbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgst "BLAS_FUNC(dsbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) nogil
+cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgv "BLAS_FUNC(dsbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgvd "BLAS_FUNC(dsbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgvx "BLAS_FUNC(dsbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbtrd "BLAS_FUNC(dsbtrd)"(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) nogil
+cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsfrk "BLAS_FUNC(dsfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) nogil
+cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil:
+    
+    _fortran_dsfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsgesv "BLAS_FUNC(dsgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) nogil
+cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_dsgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspcon "BLAS_FUNC(dspcon)"(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspev "BLAS_FUNC(dspev)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dspev(jobz, uplo, n, ap, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspevd "BLAS_FUNC(dspevd)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspevx "BLAS_FUNC(dspevx)"(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgst "BLAS_FUNC(dspgst)"(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) nogil
+cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil:
+    
+    _fortran_dspgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgv "BLAS_FUNC(dspgv)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgvd "BLAS_FUNC(dspgvd)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgvx "BLAS_FUNC(dspgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsposv "BLAS_FUNC(dsposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) nogil
+cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_dsposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsprfs "BLAS_FUNC(dsprfs)"(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspsv "BLAS_FUNC(dspsv)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspsvx "BLAS_FUNC(dspsvx)"(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrd "BLAS_FUNC(dsptrd)"(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) nogil
+cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dsptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrf "BLAS_FUNC(dsptrf)"(char *uplo, int *n, d *ap, int *ipiv, int *info) nogil
+cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dsptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptri "BLAS_FUNC(dsptri)"(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) nogil
+cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrs "BLAS_FUNC(dsptrs)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstebz "BLAS_FUNC(dstebz)"(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) nogil
+cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstedc "BLAS_FUNC(dstedc)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstegr "BLAS_FUNC(dstegr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstein "BLAS_FUNC(dstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstemr "BLAS_FUNC(dstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsteqr "BLAS_FUNC(dsteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsterf "BLAS_FUNC(dsterf)"(int *n, d *d, d *e, int *info) nogil
+cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dsterf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstev "BLAS_FUNC(dstev)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dstev(jobz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevd "BLAS_FUNC(dstevd)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevr "BLAS_FUNC(dstevr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevx "BLAS_FUNC(dstevx)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsycon "BLAS_FUNC(dsycon)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyconv "BLAS_FUNC(dsyconv)"(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil
+cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyequb "BLAS_FUNC(dsyequb)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) nogil
+cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyev "BLAS_FUNC(dsyev)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) nogil
+cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsyev(jobz, uplo, n, a, lda, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevd "BLAS_FUNC(dsyevd)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevr "BLAS_FUNC(dsyevr)"(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevx "BLAS_FUNC(dsyevx)"(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygs2 "BLAS_FUNC(dsygs2)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsygs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygst "BLAS_FUNC(dsygst)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsygst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygv "BLAS_FUNC(dsygv)"(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) nogil
+cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygvd "BLAS_FUNC(dsygvd)"(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygvx "BLAS_FUNC(dsygvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyrfs "BLAS_FUNC(dsyrfs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsysv "BLAS_FUNC(dsysv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) nogil
+cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsysvx "BLAS_FUNC(dsysvx)"(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyswapr "BLAS_FUNC(dsyswapr)"(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) nogil
+cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_dsyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytd2 "BLAS_FUNC(dsytd2)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) nogil
+cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dsytd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytf2 "BLAS_FUNC(dsytf2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dsytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrd "BLAS_FUNC(dsytrd)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrf "BLAS_FUNC(dsytrf)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri "BLAS_FUNC(dsytri)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil
+cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri2 "BLAS_FUNC(dsytri2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri2x "BLAS_FUNC(dsytri2x)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) nogil
+cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_dsytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrs "BLAS_FUNC(dsytrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrs2 "BLAS_FUNC(dsytrs2)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) nogil
+cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbcon "BLAS_FUNC(dtbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbrfs "BLAS_FUNC(dtbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbtrs "BLAS_FUNC(dtbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfsm "BLAS_FUNC(dtfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) nogil
+cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dtfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtftri "BLAS_FUNC(dtftri)"(char *transr, char *uplo, char *diag, int *n, d *a, int *info) nogil
+cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dtftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfttp "BLAS_FUNC(dtfttp)"(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) nogil
+cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfttr "BLAS_FUNC(dtfttr)"(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) nogil
+cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgevc "BLAS_FUNC(dtgevc)"(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) nogil
+cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgex2 "BLAS_FUNC(dtgex2)"(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) nogil
+cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgexc "BLAS_FUNC(dtgexc)"(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) nogil
+cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsen "BLAS_FUNC(dtgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dtgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsja "BLAS_FUNC(dtgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) nogil
+cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_dtgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsna "BLAS_FUNC(dtgsna)"(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsy2 "BLAS_FUNC(dtgsy2)"(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) nogil
+cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil:
+    
+    _fortran_dtgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsyl "BLAS_FUNC(dtgsyl)"(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpcon "BLAS_FUNC(dtpcon)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpmqrt "BLAS_FUNC(dtpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) nogil
+cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpqrt "BLAS_FUNC(dtpqrt)"(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) nogil
+cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpqrt2 "BLAS_FUNC(dtpqrt2)"(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) nogil
+cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dtpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtprfb "BLAS_FUNC(dtprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) nogil
+cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil:
+    
+    _fortran_dtprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtprfs "BLAS_FUNC(dtprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtptri "BLAS_FUNC(dtptri)"(char *uplo, char *diag, int *n, d *ap, int *info) nogil
+cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtptrs "BLAS_FUNC(dtptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpttf "BLAS_FUNC(dtpttf)"(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) nogil
+cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil:
+    
+    _fortran_dtpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpttr "BLAS_FUNC(dtpttr)"(char *uplo, int *n, d *ap, d *a, int *lda, int *info) nogil
+cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrcon "BLAS_FUNC(dtrcon)"(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtrcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrevc "BLAS_FUNC(dtrevc)"(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) nogil
+cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrexc "BLAS_FUNC(dtrexc)"(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) nogil
+cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtrexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrrfs "BLAS_FUNC(dtrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsen "BLAS_FUNC(dtrsen)"(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dtrsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsna "BLAS_FUNC(dtrsna)"(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) nogil
+cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsyl "BLAS_FUNC(dtrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) nogil
+cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil:
+    
+    _fortran_dtrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrti2 "BLAS_FUNC(dtrti2)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil
+cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrtri "BLAS_FUNC(dtrtri)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil
+cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrtrs "BLAS_FUNC(dtrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrttf "BLAS_FUNC(dtrttf)"(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) nogil
+cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil:
+    
+    _fortran_dtrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrttp "BLAS_FUNC(dtrttp)"(char *uplo, int *n, d *a, int *lda, d *ap, int *info) nogil
+cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtzrzf "BLAS_FUNC(dtzrzf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dzsum1 "BLAS_FUNC(dzsum1)"(int *n, npy_complex128 *cx, int *incx) nogil
+cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil:
+    
+    return _fortran_dzsum1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_icmax1 "BLAS_FUNC(icmax1)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_icmax1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ieeeck "BLAS_FUNC(ieeeck)"(int *ispec, s *zero, s *one) nogil
+cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil:
+    
+    return _fortran_ieeeck(ispec, zero, one)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaclc "BLAS_FUNC(ilaclc)"(int *m, int *n, npy_complex64 *a, int *lda) nogil
+cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaclc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaclr "BLAS_FUNC(ilaclr)"(int *m, int *n, npy_complex64 *a, int *lda) nogil
+cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaclr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladiag "BLAS_FUNC(iladiag)"(char *diag) nogil
+cdef int iladiag(char *diag) noexcept nogil:
+    
+    return _fortran_iladiag(diag)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladlc "BLAS_FUNC(iladlc)"(int *m, int *n, d *a, int *lda) nogil
+cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil:
+    
+    return _fortran_iladlc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladlr "BLAS_FUNC(iladlr)"(int *m, int *n, d *a, int *lda) nogil
+cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil:
+    
+    return _fortran_iladlr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaprec "BLAS_FUNC(ilaprec)"(char *prec) nogil
+cdef int ilaprec(char *prec) noexcept nogil:
+    
+    return _fortran_ilaprec(prec)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaslc "BLAS_FUNC(ilaslc)"(int *m, int *n, s *a, int *lda) nogil
+cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaslc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaslr "BLAS_FUNC(ilaslr)"(int *m, int *n, s *a, int *lda) nogil
+cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaslr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilatrans "BLAS_FUNC(ilatrans)"(char *trans) nogil
+cdef int ilatrans(char *trans) noexcept nogil:
+    
+    return _fortran_ilatrans(trans)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilauplo "BLAS_FUNC(ilauplo)"(char *uplo) nogil
+cdef int ilauplo(char *uplo) noexcept nogil:
+    
+    return _fortran_ilauplo(uplo)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ilaver "BLAS_FUNC(ilaver)"(int *vers_major, int *vers_minor, int *vers_patch) nogil
+cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil:
+    
+    _fortran_ilaver(vers_major, vers_minor, vers_patch)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilazlc "BLAS_FUNC(ilazlc)"(int *m, int *n, npy_complex128 *a, int *lda) nogil
+cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilazlc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilazlr "BLAS_FUNC(ilazlr)"(int *m, int *n, npy_complex128 *a, int *lda) nogil
+cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilazlr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_izmax1 "BLAS_FUNC(izmax1)"(int *n, npy_complex128 *cx, int *incx) nogil
+cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil:
+    
+    return _fortran_izmax1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbbcsd "BLAS_FUNC(sbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) nogil
+cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbdsdc "BLAS_FUNC(sbdsdc)"(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) nogil
+cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbdsqr "BLAS_FUNC(sbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) nogil
+cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_scsum1 "BLAS_FUNC(scsum1)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_scsum1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sdisna "BLAS_FUNC(sdisna)"(char *job, int *m, int *n, s *d, s *sep, int *info) nogil
+cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil:
+    
+    _fortran_sdisna(job, m, n, d, sep, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbbrd "BLAS_FUNC(sgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) nogil
+cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbcon "BLAS_FUNC(sgbcon)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbequ "BLAS_FUNC(sgbequ)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbequb "BLAS_FUNC(sgbequb)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbrfs "BLAS_FUNC(sgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbsv "BLAS_FUNC(sgbsv)"(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbsvx "BLAS_FUNC(sgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtf2 "BLAS_FUNC(sgbtf2)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtrf "BLAS_FUNC(sgbtrf)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtrs "BLAS_FUNC(sgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebak "BLAS_FUNC(sgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) nogil
+cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_sgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebal "BLAS_FUNC(sgebal)"(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil
+cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil:
+    
+    _fortran_sgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebd2 "BLAS_FUNC(sgebd2)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) nogil
+cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebrd "BLAS_FUNC(sgebrd)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) nogil
+cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgecon "BLAS_FUNC(sgecon)"(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeequ "BLAS_FUNC(sgeequ)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeequb "BLAS_FUNC(sgeequb)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgees "BLAS_FUNC(sgees)"(char *jobvs, char *sort, _sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) nogil
+cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sgees(jobvs, sort, <_sselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeesx "BLAS_FUNC(sgeesx)"(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sgeesx(jobvs, sort, <_sselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeev "BLAS_FUNC(sgeev)"(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) nogil
+cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeevx "BLAS_FUNC(sgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgehd2 "BLAS_FUNC(sgehd2)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgehrd "BLAS_FUNC(sgehrd)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgejsv "BLAS_FUNC(sgejsv)"(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelq2 "BLAS_FUNC(sgelq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelqf "BLAS_FUNC(sgelqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgels "BLAS_FUNC(sgels)"(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) nogil
+cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelsd "BLAS_FUNC(sgelsd)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelss "BLAS_FUNC(sgelss)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) nogil
+cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelsy "BLAS_FUNC(sgelsy)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) nogil
+cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgemqrt "BLAS_FUNC(sgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) nogil
+cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeql2 "BLAS_FUNC(sgeql2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqlf "BLAS_FUNC(sgeqlf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqp3 "BLAS_FUNC(sgeqp3)"(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqr2 "BLAS_FUNC(sgeqr2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqr2p "BLAS_FUNC(sgeqr2p)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrf "BLAS_FUNC(sgeqrf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrfp "BLAS_FUNC(sgeqrfp)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt "BLAS_FUNC(sgeqrt)"(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) nogil
+cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt2 "BLAS_FUNC(sgeqrt2)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil
+cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt3 "BLAS_FUNC(sgeqrt3)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil
+cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerfs "BLAS_FUNC(sgerfs)"(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerq2 "BLAS_FUNC(sgerq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerqf "BLAS_FUNC(sgerqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesc2 "BLAS_FUNC(sgesc2)"(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) nogil
+cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil:
+    
+    _fortran_sgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesdd "BLAS_FUNC(sgesdd)"(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesv "BLAS_FUNC(sgesv)"(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvd "BLAS_FUNC(sgesvd)"(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) nogil
+cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvj "BLAS_FUNC(sgesvj)"(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) nogil
+cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvx "BLAS_FUNC(sgesvx)"(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetc2 "BLAS_FUNC(sgetc2)"(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_sgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetf2 "BLAS_FUNC(sgetf2)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetrf "BLAS_FUNC(sgetrf)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetri "BLAS_FUNC(sgetri)"(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetrs "BLAS_FUNC(sgetrs)"(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggbak "BLAS_FUNC(sggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) nogil
+cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_sggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggbal "BLAS_FUNC(sggbal)"(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) nogil
+cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil:
+    
+    _fortran_sggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgges "BLAS_FUNC(sgges)"(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) nogil
+cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sgges(jobvsl, jobvsr, sort, <_sselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggesx "BLAS_FUNC(sggesx)"(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sggesx(jobvsl, jobvsr, sort, <_sselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggev "BLAS_FUNC(sggev)"(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) nogil
+cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggevx "BLAS_FUNC(sggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) nogil
+cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggglm "BLAS_FUNC(sggglm)"(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) nogil
+cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgghrd "BLAS_FUNC(sgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) nogil
+cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_sgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgglse "BLAS_FUNC(sgglse)"(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) nogil
+cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggqrf "BLAS_FUNC(sggqrf)"(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) nogil
+cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggrqf "BLAS_FUNC(sggrqf)"(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) nogil
+cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgsvj0 "BLAS_FUNC(sgsvj0)"(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) nogil
+cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgsvj1 "BLAS_FUNC(sgsvj1)"(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) nogil
+cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtcon "BLAS_FUNC(sgtcon)"(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtrfs "BLAS_FUNC(sgtrfs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtsv "BLAS_FUNC(sgtsv)"(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) nogil
+cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtsvx "BLAS_FUNC(sgtsvx)"(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgttrf "BLAS_FUNC(sgttrf)"(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) nogil
+cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgttrs "BLAS_FUNC(sgttrs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtts2 "BLAS_FUNC(sgtts2)"(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) nogil
+cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_sgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shgeqz "BLAS_FUNC(shgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_shgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shsein "BLAS_FUNC(shsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) nogil
+cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_shsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shseqr "BLAS_FUNC(shseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_shseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slabad "BLAS_FUNC(slabad)"(s *small, s *large) nogil
+cdef void slabad(s *small, s *large) noexcept nogil:
+    
+    _fortran_slabad(small, large)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slabrd "BLAS_FUNC(slabrd)"(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) nogil
+cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil:
+    
+    _fortran_slabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacn2 "BLAS_FUNC(slacn2)"(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) nogil
+cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_slacn2(n, v, x, isgn, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacon "BLAS_FUNC(slacon)"(int *n, s *v, s *x, int *isgn, s *est, int *kase) nogil
+cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil:
+    
+    _fortran_slacon(n, v, x, isgn, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacpy "BLAS_FUNC(slacpy)"(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) nogil
+cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_slacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sladiv "BLAS_FUNC(sladiv)"(s *a, s *b, s *c, s *d, s *p, s *q) nogil
+cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil:
+    
+    _fortran_sladiv(a, b, c, d, p, q)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slae2 "BLAS_FUNC(slae2)"(s *a, s *b, s *c, s *rt1, s *rt2) nogil
+cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil:
+    
+    _fortran_slae2(a, b, c, rt1, rt2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaebz "BLAS_FUNC(slaebz)"(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) nogil
+cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed0 "BLAS_FUNC(slaed0)"(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) nogil
+cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed1 "BLAS_FUNC(slaed1)"(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) nogil
+cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed2 "BLAS_FUNC(slaed2)"(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) nogil
+cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_slaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed3 "BLAS_FUNC(slaed3)"(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) nogil
+cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil:
+    
+    _fortran_slaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed4 "BLAS_FUNC(slaed4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) nogil
+cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil:
+    
+    _fortran_slaed4(n, i, d, z, delta, rho, dlam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed5 "BLAS_FUNC(slaed5)"(int *i, s *d, s *z, s *delta, s *rho, s *dlam) nogil
+cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil:
+    
+    _fortran_slaed5(i, d, z, delta, rho, dlam)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed6 "BLAS_FUNC(slaed6)"(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) nogil
+cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil:
+    
+    _fortran_slaed6(kniter, orgati, rho, d, z, finit, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed7 "BLAS_FUNC(slaed7)"(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) nogil
+cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed8 "BLAS_FUNC(slaed8)"(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) nogil
+cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil:
+    
+    _fortran_slaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed9 "BLAS_FUNC(slaed9)"(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) nogil
+cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil:
+    
+    _fortran_slaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaeda "BLAS_FUNC(slaeda)"(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) nogil
+cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil:
+    
+    _fortran_slaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaein "BLAS_FUNC(slaein)"(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) nogil
+cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil:
+    
+    _fortran_slaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaev2 "BLAS_FUNC(slaev2)"(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) nogil
+cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil:
+    
+    _fortran_slaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaexc "BLAS_FUNC(slaexc)"(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) nogil
+cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil:
+    
+    _fortran_slaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slag2 "BLAS_FUNC(slag2)"(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) nogil
+cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil:
+    
+    _fortran_slag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slag2d "BLAS_FUNC(slag2d)"(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) nogil
+cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slag2d(m, n, sa, ldsa, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slags2 "BLAS_FUNC(slags2)"(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) nogil
+cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil:
+    
+    _fortran_slags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagtf "BLAS_FUNC(slagtf)"(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) nogil
+cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil:
+    
+    _fortran_slagtf(n, a, lambda_, b, c, tol, d, in_, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagtm "BLAS_FUNC(slagtm)"(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) nogil
+cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_slagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagts "BLAS_FUNC(slagts)"(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) nogil
+cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil:
+    
+    _fortran_slagts(job, n, a, b, c, d, in_, y, tol, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagv2 "BLAS_FUNC(slagv2)"(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) nogil
+cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil:
+    
+    _fortran_slagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slahqr "BLAS_FUNC(slahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) nogil
+cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_slahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slahr2 "BLAS_FUNC(slahr2)"(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) nogil
+cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil:
+    
+    _fortran_slahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaic1 "BLAS_FUNC(slaic1)"(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) nogil
+cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil:
+    
+    _fortran_slaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaln2 "BLAS_FUNC(slaln2)"(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) nogil
+cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil:
+    
+    _fortran_slaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slals0 "BLAS_FUNC(slals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) nogil
+cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil:
+    
+    _fortran_slals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slalsa "BLAS_FUNC(slalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) nogil
+cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slalsd "BLAS_FUNC(slalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) nogil
+cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slamch "BLAS_FUNC(slamch)"(char *cmach) nogil
+cdef s slamch(char *cmach) noexcept nogil:
+    
+    return _fortran_slamch(cmach)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slamrg "BLAS_FUNC(slamrg)"(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) nogil
+cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil:
+    
+    _fortran_slamrg(n1, n2, a, strd1, strd2, index_bn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slangb "BLAS_FUNC(slangb)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) nogil
+cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slange "BLAS_FUNC(slange)"(char *norm, int *m, int *n, s *a, int *lda, s *work) nogil
+cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slangt "BLAS_FUNC(slangt)"(char *norm, int *n, s *dl, s *d, s *du) nogil
+cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil:
+    
+    return _fortran_slangt(norm, n, dl, d, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slanhs "BLAS_FUNC(slanhs)"(char *norm, int *n, s *a, int *lda, s *work) nogil
+cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansb "BLAS_FUNC(slansb)"(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) nogil
+cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansf "BLAS_FUNC(slansf)"(char *norm, char *transr, char *uplo, int *n, s *a, s *work) nogil
+cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil:
+    
+    return _fortran_slansf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansp "BLAS_FUNC(slansp)"(char *norm, char *uplo, int *n, s *ap, s *work) nogil
+cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil:
+    
+    return _fortran_slansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slanst "BLAS_FUNC(slanst)"(char *norm, int *n, s *d, s *e) nogil
+cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil:
+    
+    return _fortran_slanst(norm, n, d, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansy "BLAS_FUNC(slansy)"(char *norm, char *uplo, int *n, s *a, int *lda, s *work) nogil
+cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantb "BLAS_FUNC(slantb)"(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) nogil
+cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantp "BLAS_FUNC(slantp)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) nogil
+cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil:
+    
+    return _fortran_slantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantr "BLAS_FUNC(slantr)"(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) nogil
+cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slanv2 "BLAS_FUNC(slanv2)"(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) nogil
+cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil:
+    
+    _fortran_slanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapll "BLAS_FUNC(slapll)"(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) nogil
+cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil:
+    
+    _fortran_slapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapmr "BLAS_FUNC(slapmr)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil
+cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_slapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapmt "BLAS_FUNC(slapmt)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil
+cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_slapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slapy2 "BLAS_FUNC(slapy2)"(s *x, s *y) nogil
+cdef s slapy2(s *x, s *y) noexcept nogil:
+    
+    return _fortran_slapy2(x, y)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slapy3 "BLAS_FUNC(slapy3)"(s *x, s *y, s *z) nogil
+cdef s slapy3(s *x, s *y, s *z) noexcept nogil:
+    
+    return _fortran_slapy3(x, y, z)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqgb "BLAS_FUNC(slaqgb)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqge "BLAS_FUNC(slaqge)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqp2 "BLAS_FUNC(slaqp2)"(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) nogil
+cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil:
+    
+    _fortran_slaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqps "BLAS_FUNC(slaqps)"(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) nogil
+cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil:
+    
+    _fortran_slaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr0 "BLAS_FUNC(slaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_slaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr1 "BLAS_FUNC(slaqr1)"(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) nogil
+cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil:
+    
+    _fortran_slaqr1(n, h, ldh, sr1, si1, sr2, si2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr2 "BLAS_FUNC(slaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) nogil
+cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil:
+    
+    _fortran_slaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr3 "BLAS_FUNC(slaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) nogil
+cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil:
+    
+    _fortran_slaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr4 "BLAS_FUNC(slaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_slaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr5 "BLAS_FUNC(slaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) nogil
+cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_slaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsb "BLAS_FUNC(slaqsb)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsp "BLAS_FUNC(slaqsp)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsy "BLAS_FUNC(slaqsy)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqtr "BLAS_FUNC(slaqtr)"(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) nogil
+cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil:
+    
+    _fortran_slaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slar1v "BLAS_FUNC(slar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) nogil
+cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil:
+    
+    _fortran_slar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slar2v "BLAS_FUNC(slar2v)"(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) nogil
+cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil:
+    
+    _fortran_slar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarf "BLAS_FUNC(slarf)"(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfb "BLAS_FUNC(slarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) nogil
+cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil:
+    
+    _fortran_slarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfg "BLAS_FUNC(slarfg)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil
+cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil:
+    
+    _fortran_slarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfgp "BLAS_FUNC(slarfgp)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil
+cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil:
+    
+    _fortran_slarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarft "BLAS_FUNC(slarft)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil
+cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil:
+    
+    _fortran_slarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfx "BLAS_FUNC(slarfx)"(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slargv "BLAS_FUNC(slargv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) nogil
+cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil:
+    
+    _fortran_slargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarnv "BLAS_FUNC(slarnv)"(int *idist, int *iseed, int *n, s *x) nogil
+cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil:
+    
+    _fortran_slarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarra "BLAS_FUNC(slarra)"(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) nogil
+cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil:
+    
+    _fortran_slarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrb "BLAS_FUNC(slarrb)"(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) nogil
+cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil:
+    
+    _fortran_slarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrc "BLAS_FUNC(slarrc)"(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) nogil
+cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil:
+    
+    _fortran_slarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrd "BLAS_FUNC(slarrd)"(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) nogil
+cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarre "BLAS_FUNC(slarre)"(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) nogil
+cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrf "BLAS_FUNC(slarrf)"(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) nogil
+cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil:
+    
+    _fortran_slarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrj "BLAS_FUNC(slarrj)"(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) nogil
+cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil:
+    
+    _fortran_slarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrk "BLAS_FUNC(slarrk)"(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) nogil
+cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil:
+    
+    _fortran_slarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrr "BLAS_FUNC(slarrr)"(int *n, s *d, s *e, int *info) nogil
+cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_slarrr(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrv "BLAS_FUNC(slarrv)"(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) nogil
+cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartg "BLAS_FUNC(slartg)"(s *f, s *g, s *cs, s *sn, s *r) nogil
+cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil:
+    
+    _fortran_slartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartgp "BLAS_FUNC(slartgp)"(s *f, s *g, s *cs, s *sn, s *r) nogil
+cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil:
+    
+    _fortran_slartgp(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartgs "BLAS_FUNC(slartgs)"(s *x, s *y, s *sigma, s *cs, s *sn) nogil
+cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil:
+    
+    _fortran_slartgs(x, y, sigma, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartv "BLAS_FUNC(slartv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) nogil
+cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil:
+    
+    _fortran_slartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaruv "BLAS_FUNC(slaruv)"(int *iseed, int *n, s *x) nogil
+cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil:
+    
+    _fortran_slaruv(iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarz "BLAS_FUNC(slarz)"(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarzb "BLAS_FUNC(slarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) nogil
+cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil:
+    
+    _fortran_slarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarzt "BLAS_FUNC(slarzt)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil
+cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil:
+    
+    _fortran_slarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slas2 "BLAS_FUNC(slas2)"(s *f, s *g, s *h, s *ssmin, s *ssmax) nogil
+cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil:
+    
+    _fortran_slas2(f, g, h, ssmin, ssmax)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slascl "BLAS_FUNC(slascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) nogil
+cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd0 "BLAS_FUNC(slasd0)"(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) nogil
+cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd1 "BLAS_FUNC(slasd1)"(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) nogil
+cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd2 "BLAS_FUNC(slasd2)"(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) nogil
+cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_slasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd3 "BLAS_FUNC(slasd3)"(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) nogil
+cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil:
+    
+    _fortran_slasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd4 "BLAS_FUNC(slasd4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) nogil
+cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd4(n, i, d, z, delta, rho, sigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd5 "BLAS_FUNC(slasd5)"(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) nogil
+cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil:
+    
+    _fortran_slasd5(i, d, z, delta, rho, dsigma, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd6 "BLAS_FUNC(slasd6)"(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) nogil
+cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd7 "BLAS_FUNC(slasd7)"(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) nogil
+cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil:
+    
+    _fortran_slasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd8 "BLAS_FUNC(slasd8)"(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) nogil
+cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasda "BLAS_FUNC(slasda)"(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) nogil
+cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasdq "BLAS_FUNC(slasdq)"(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) nogil
+cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasdt "BLAS_FUNC(slasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil
+cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil:
+    
+    _fortran_slasdt(n, lvl, nd, inode, ndiml, ndimr, msub)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaset "BLAS_FUNC(slaset)"(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) nogil
+cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil:
+    
+    _fortran_slaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq1 "BLAS_FUNC(slasq1)"(int *n, s *d, s *e, s *work, int *info) nogil
+cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasq1(n, d, e, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq2 "BLAS_FUNC(slasq2)"(int *n, s *z, int *info) nogil
+cdef void slasq2(int *n, s *z, int *info) noexcept nogil:
+    
+    _fortran_slasq2(n, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq3 "BLAS_FUNC(slasq3)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) nogil
+cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil:
+    
+    _fortran_slasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq4 "BLAS_FUNC(slasq4)"(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) nogil
+cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil:
+    
+    _fortran_slasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq6 "BLAS_FUNC(slasq6)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) nogil
+cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil:
+    
+    _fortran_slasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasr "BLAS_FUNC(slasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) nogil
+cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil:
+    
+    _fortran_slasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasrt "BLAS_FUNC(slasrt)"(char *id, int *n, s *d, int *info) nogil
+cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil:
+    
+    _fortran_slasrt(id, n, d, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slassq "BLAS_FUNC(slassq)"(int *n, s *x, int *incx, s *scale, s *sumsq) nogil
+cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil:
+    
+    _fortran_slassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasv2 "BLAS_FUNC(slasv2)"(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) nogil
+cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil:
+    
+    _fortran_slasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaswp "BLAS_FUNC(slaswp)"(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_slaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasy2 "BLAS_FUNC(slasy2)"(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) nogil
+cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil:
+    
+    _fortran_slasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasyf "BLAS_FUNC(slasyf)"(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) nogil
+cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_slasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatbs "BLAS_FUNC(slatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) nogil
+cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_slatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatdf "BLAS_FUNC(slatdf)"(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil
+cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_slatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatps "BLAS_FUNC(slatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) nogil
+cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_slatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrd "BLAS_FUNC(slatrd)"(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) nogil
+cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil:
+    
+    _fortran_slatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrs "BLAS_FUNC(slatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) nogil
+cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_slatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrz "BLAS_FUNC(slatrz)"(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) nogil
+cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil:
+    
+    _fortran_slatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slauu2 "BLAS_FUNC(slauu2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slauum "BLAS_FUNC(slauum)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sopgtr "BLAS_FUNC(sopgtr)"(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) nogil
+cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil:
+    
+    _fortran_sopgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sopmtr "BLAS_FUNC(sopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorbdb "BLAS_FUNC(sorbdb)"(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) nogil
+cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorcsd "BLAS_FUNC(sorcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorg2l "BLAS_FUNC(sorg2l)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorg2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorg2r "BLAS_FUNC(sorg2r)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorg2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgbr "BLAS_FUNC(sorgbr)"(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorghr "BLAS_FUNC(sorghr)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgl2 "BLAS_FUNC(sorgl2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorgl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorglq "BLAS_FUNC(sorglq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgql "BLAS_FUNC(sorgql)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgqr "BLAS_FUNC(sorgqr)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgr2 "BLAS_FUNC(sorgr2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorgr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgrq "BLAS_FUNC(sorgrq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgtr "BLAS_FUNC(sorgtr)"(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorm2l "BLAS_FUNC(sorm2l)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorm2r "BLAS_FUNC(sorm2r)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormbr "BLAS_FUNC(sormbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormhr "BLAS_FUNC(sormhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorml2 "BLAS_FUNC(sorml2)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormlq "BLAS_FUNC(sormlq)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormql "BLAS_FUNC(sormql)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormqr "BLAS_FUNC(sormqr)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormr2 "BLAS_FUNC(sormr2)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormr3 "BLAS_FUNC(sormr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormrq "BLAS_FUNC(sormrq)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormrz "BLAS_FUNC(sormrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormtr "BLAS_FUNC(sormtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbcon "BLAS_FUNC(spbcon)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbequ "BLAS_FUNC(spbequ)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil
+cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbrfs "BLAS_FUNC(spbrfs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbstf "BLAS_FUNC(spbstf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbsv "BLAS_FUNC(spbsv)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbsvx "BLAS_FUNC(spbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtf2 "BLAS_FUNC(spbtf2)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtrf "BLAS_FUNC(spbtrf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtrs "BLAS_FUNC(spbtrs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftrf "BLAS_FUNC(spftrf)"(char *transr, char *uplo, int *n, s *a, int *info) nogil
+cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_spftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftri "BLAS_FUNC(spftri)"(char *transr, char *uplo, int *n, s *a, int *info) nogil
+cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_spftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftrs "BLAS_FUNC(spftrs)"(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) nogil
+cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spocon "BLAS_FUNC(spocon)"(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spoequ "BLAS_FUNC(spoequ)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spoequb "BLAS_FUNC(spoequb)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sporfs "BLAS_FUNC(sporfs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sposv "BLAS_FUNC(sposv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sposvx "BLAS_FUNC(sposvx)"(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotf2 "BLAS_FUNC(spotf2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotrf "BLAS_FUNC(spotrf)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotri "BLAS_FUNC(spotri)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotrs "BLAS_FUNC(spotrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppcon "BLAS_FUNC(sppcon)"(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sppcon(uplo, n, ap, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppequ "BLAS_FUNC(sppequ)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) nogil
+cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spprfs "BLAS_FUNC(spprfs)"(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppsv "BLAS_FUNC(sppsv)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppsvx "BLAS_FUNC(sppsvx)"(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptrf "BLAS_FUNC(spptrf)"(char *uplo, int *n, s *ap, int *info) nogil
+cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_spptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptri "BLAS_FUNC(spptri)"(char *uplo, int *n, s *ap, int *info) nogil
+cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_spptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptrs "BLAS_FUNC(spptrs)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spstf2 "BLAS_FUNC(spstf2)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_spstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spstrf "BLAS_FUNC(spstrf)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_spstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptcon "BLAS_FUNC(sptcon)"(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) nogil
+cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptcon(n, d, e, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spteqr "BLAS_FUNC(spteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_spteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptrfs "BLAS_FUNC(sptrfs)"(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) nogil
+cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptsv "BLAS_FUNC(sptsv)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil
+cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptsvx "BLAS_FUNC(sptsvx)"(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) nogil
+cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spttrf "BLAS_FUNC(spttrf)"(int *n, s *d, s *e, int *info) nogil
+cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_spttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spttrs "BLAS_FUNC(spttrs)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil
+cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spttrs(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptts2 "BLAS_FUNC(sptts2)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) nogil
+cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_sptts2(n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_srscl "BLAS_FUNC(srscl)"(int *n, s *sa, s *sx, int *incx) nogil
+cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil:
+    
+    _fortran_srscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbev "BLAS_FUNC(ssbev)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbevd "BLAS_FUNC(ssbevd)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbevx "BLAS_FUNC(ssbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgst "BLAS_FUNC(ssbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) nogil
+cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgv "BLAS_FUNC(ssbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgvd "BLAS_FUNC(ssbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgvx "BLAS_FUNC(ssbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbtrd "BLAS_FUNC(ssbtrd)"(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) nogil
+cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssfrk "BLAS_FUNC(ssfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) nogil
+cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil:
+    
+    _fortran_ssfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspcon "BLAS_FUNC(sspcon)"(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspev "BLAS_FUNC(sspev)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sspev(jobz, uplo, n, ap, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspevd "BLAS_FUNC(sspevd)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspevx "BLAS_FUNC(sspevx)"(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgst "BLAS_FUNC(sspgst)"(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) nogil
+cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil:
+    
+    _fortran_sspgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgv "BLAS_FUNC(sspgv)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgvd "BLAS_FUNC(sspgvd)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgvx "BLAS_FUNC(sspgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssprfs "BLAS_FUNC(ssprfs)"(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspsv "BLAS_FUNC(sspsv)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspsvx "BLAS_FUNC(sspsvx)"(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrd "BLAS_FUNC(ssptrd)"(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) nogil
+cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil:
+    
+    _fortran_ssptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrf "BLAS_FUNC(ssptrf)"(char *uplo, int *n, s *ap, int *ipiv, int *info) nogil
+cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_ssptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptri "BLAS_FUNC(ssptri)"(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) nogil
+cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrs "BLAS_FUNC(ssptrs)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstebz "BLAS_FUNC(sstebz)"(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) nogil
+cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstedc "BLAS_FUNC(sstedc)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstegr "BLAS_FUNC(sstegr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstein "BLAS_FUNC(sstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstemr "BLAS_FUNC(sstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssteqr "BLAS_FUNC(ssteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssterf "BLAS_FUNC(ssterf)"(int *n, s *d, s *e, int *info) nogil
+cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_ssterf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstev "BLAS_FUNC(sstev)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sstev(jobz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevd "BLAS_FUNC(sstevd)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevr "BLAS_FUNC(sstevr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevx "BLAS_FUNC(sstevx)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssycon "BLAS_FUNC(ssycon)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyconv "BLAS_FUNC(ssyconv)"(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil
+cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyequb "BLAS_FUNC(ssyequb)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) nogil
+cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyev "BLAS_FUNC(ssyev)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) nogil
+cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssyev(jobz, uplo, n, a, lda, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevd "BLAS_FUNC(ssyevd)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevr "BLAS_FUNC(ssyevr)"(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevx "BLAS_FUNC(ssyevx)"(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygs2 "BLAS_FUNC(ssygs2)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssygs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygst "BLAS_FUNC(ssygst)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssygst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygv "BLAS_FUNC(ssygv)"(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) nogil
+cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygvd "BLAS_FUNC(ssygvd)"(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygvx "BLAS_FUNC(ssygvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyrfs "BLAS_FUNC(ssyrfs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssysv "BLAS_FUNC(ssysv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) nogil
+cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssysvx "BLAS_FUNC(ssysvx)"(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyswapr "BLAS_FUNC(ssyswapr)"(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) nogil
+cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_ssyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytd2 "BLAS_FUNC(ssytd2)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) nogil
+cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil:
+    
+    _fortran_ssytd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytf2 "BLAS_FUNC(ssytf2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_ssytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrd "BLAS_FUNC(ssytrd)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) nogil
+cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrf "BLAS_FUNC(ssytrf)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri "BLAS_FUNC(ssytri)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil
+cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri2 "BLAS_FUNC(ssytri2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri2x "BLAS_FUNC(ssytri2x)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) nogil
+cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_ssytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrs "BLAS_FUNC(ssytrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrs2 "BLAS_FUNC(ssytrs2)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) nogil
+cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbcon "BLAS_FUNC(stbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbrfs "BLAS_FUNC(stbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbtrs "BLAS_FUNC(stbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_stbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfsm "BLAS_FUNC(stfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) nogil
+cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_stfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stftri "BLAS_FUNC(stftri)"(char *transr, char *uplo, char *diag, int *n, s *a, int *info) nogil
+cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_stftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfttp "BLAS_FUNC(stfttp)"(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) nogil
+cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil:
+    
+    _fortran_stfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfttr "BLAS_FUNC(stfttr)"(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) nogil
+cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_stfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgevc "BLAS_FUNC(stgevc)"(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) nogil
+cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil:
+    
+    _fortran_stgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgex2 "BLAS_FUNC(stgex2)"(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) nogil
+cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgexc "BLAS_FUNC(stgexc)"(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) nogil
+cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsen "BLAS_FUNC(stgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_stgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsja "BLAS_FUNC(stgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) nogil
+cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_stgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsna "BLAS_FUNC(stgsna)"(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsy2 "BLAS_FUNC(stgsy2)"(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) nogil
+cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil:
+    
+    _fortran_stgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsyl "BLAS_FUNC(stgsyl)"(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpcon "BLAS_FUNC(stpcon)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpmqrt "BLAS_FUNC(stpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) nogil
+cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil:
+    
+    _fortran_stpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpqrt "BLAS_FUNC(stpqrt)"(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) nogil
+cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil:
+    
+    _fortran_stpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpqrt2 "BLAS_FUNC(stpqrt2)"(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) nogil
+cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_stpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stprfb "BLAS_FUNC(stprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) nogil
+cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil:
+    
+    _fortran_stprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stprfs "BLAS_FUNC(stprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stptri "BLAS_FUNC(stptri)"(char *uplo, char *diag, int *n, s *ap, int *info) nogil
+cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_stptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stptrs "BLAS_FUNC(stptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_stptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpttf "BLAS_FUNC(stpttf)"(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) nogil
+cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil:
+    
+    _fortran_stpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpttr "BLAS_FUNC(stpttr)"(char *uplo, int *n, s *ap, s *a, int *lda, int *info) nogil
+cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_stpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strcon "BLAS_FUNC(strcon)"(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_strcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strevc "BLAS_FUNC(strevc)"(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) nogil
+cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil:
+    
+    _fortran_strevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strexc "BLAS_FUNC(strexc)"(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) nogil
+cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil:
+    
+    _fortran_strexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strrfs "BLAS_FUNC(strrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_strrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsen "BLAS_FUNC(strsen)"(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_strsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsna "BLAS_FUNC(strsna)"(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) nogil
+cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_strsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsyl "BLAS_FUNC(strsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) nogil
+cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil:
+    
+    _fortran_strsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strti2 "BLAS_FUNC(strti2)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil
+cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_strti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strtri "BLAS_FUNC(strtri)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil
+cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_strtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strtrs "BLAS_FUNC(strtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_strtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strttf "BLAS_FUNC(strttf)"(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) nogil
+cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil:
+    
+    _fortran_strttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strttp "BLAS_FUNC(strttp)"(char *uplo, int *n, s *a, int *lda, s *ap, int *info) nogil
+cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil:
+    
+    _fortran_strttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stzrzf "BLAS_FUNC(stzrzf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_xerbla_array "BLAS_FUNC(xerbla_array)"(char *srname_array, int *srname_len, int *info) nogil
+cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil:
+    
+    _fortran_xerbla_array(srname_array, srname_len, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zbbcsd "BLAS_FUNC(zbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) nogil
+cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil:
+    
+    _fortran_zbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zbdsqr "BLAS_FUNC(zbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, d *rwork, int *info) nogil
+cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zcgesv "BLAS_FUNC(zcgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) nogil
+cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_zcgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, rwork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zcposv "BLAS_FUNC(zcposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) nogil
+cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_zcposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, rwork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zdrscl "BLAS_FUNC(zdrscl)"(int *n, d *sa, npy_complex128 *sx, int *incx) nogil
+cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil:
+    
+    _fortran_zdrscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbbrd "BLAS_FUNC(zgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbcon "BLAS_FUNC(zgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbequ "BLAS_FUNC(zgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbequb "BLAS_FUNC(zgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbrfs "BLAS_FUNC(zgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbsv "BLAS_FUNC(zgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbsvx "BLAS_FUNC(zgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtf2 "BLAS_FUNC(zgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtrf "BLAS_FUNC(zgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtrs "BLAS_FUNC(zgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebak "BLAS_FUNC(zgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, npy_complex128 *v, int *ldv, int *info) nogil
+cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_zgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebal "BLAS_FUNC(zgebal)"(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil
+cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil:
+    
+    _fortran_zgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebd2 "BLAS_FUNC(zgebd2)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info) nogil
+cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebrd "BLAS_FUNC(zgebrd)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgecon "BLAS_FUNC(zgecon)"(char *norm, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeequ "BLAS_FUNC(zgeequ)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeequb "BLAS_FUNC(zgeequb)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgees "BLAS_FUNC(zgees)"(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil
+cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zgees(jobvs, sort, <_zselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeesx "BLAS_FUNC(zgeesx)"(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil
+cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zgeesx(jobvs, sort, <_zselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeev "BLAS_FUNC(zgeev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeevx "BLAS_FUNC(zgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgehd2 "BLAS_FUNC(zgehd2)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgehrd "BLAS_FUNC(zgehrd)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelq2 "BLAS_FUNC(zgelq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelqf "BLAS_FUNC(zgelqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgels "BLAS_FUNC(zgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelsd "BLAS_FUNC(zgelsd)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) nogil
+cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelss "BLAS_FUNC(zgelss)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelsy "BLAS_FUNC(zgelsy)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgemqrt "BLAS_FUNC(zgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeql2 "BLAS_FUNC(zgeql2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqlf "BLAS_FUNC(zgeqlf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqp3 "BLAS_FUNC(zgeqp3)"(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqr2 "BLAS_FUNC(zgeqr2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqr2p "BLAS_FUNC(zgeqr2p)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrf "BLAS_FUNC(zgeqrf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrfp "BLAS_FUNC(zgeqrfp)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt "BLAS_FUNC(zgeqrt)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil
+cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt2 "BLAS_FUNC(zgeqrt2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt3 "BLAS_FUNC(zgeqrt3)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerfs "BLAS_FUNC(zgerfs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerq2 "BLAS_FUNC(zgerq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerqf "BLAS_FUNC(zgerqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesc2 "BLAS_FUNC(zgesc2)"(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, d *scale) nogil
+cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil:
+    
+    _fortran_zgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesdd "BLAS_FUNC(zgesdd)"(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) nogil
+cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesv "BLAS_FUNC(zgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesvd "BLAS_FUNC(zgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesvx "BLAS_FUNC(zgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetc2 "BLAS_FUNC(zgetc2)"(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_zgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetf2 "BLAS_FUNC(zgetf2)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetrf "BLAS_FUNC(zgetrf)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetri "BLAS_FUNC(zgetri)"(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetrs "BLAS_FUNC(zgetrs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggbak "BLAS_FUNC(zggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, npy_complex128 *v, int *ldv, int *info) nogil
+cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_zggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggbal "BLAS_FUNC(zggbal)"(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) nogil
+cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil:
+    
+    _fortran_zggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgges "BLAS_FUNC(zgges)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil
+cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zgges(jobvsl, jobvsr, sort, <_zselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggesx "BLAS_FUNC(zggesx)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zggesx(jobvsl, jobvsr, sort, <_zselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggev "BLAS_FUNC(zggev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggevx "BLAS_FUNC(zggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) nogil
+cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggglm "BLAS_FUNC(zggglm)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgghrd "BLAS_FUNC(zgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info) nogil
+cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_zgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgglse "BLAS_FUNC(zgglse)"(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggqrf "BLAS_FUNC(zggqrf)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggrqf "BLAS_FUNC(zggrqf)"(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtcon "BLAS_FUNC(zgtcon)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtrfs "BLAS_FUNC(zgtrfs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtsv "BLAS_FUNC(zgtsv)"(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtsvx "BLAS_FUNC(zgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgttrf "BLAS_FUNC(zgttrf)"(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info) nogil
+cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgttrs "BLAS_FUNC(zgttrs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtts2 "BLAS_FUNC(zgtts2)"(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb) nogil
+cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbev "BLAS_FUNC(zhbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbevd "BLAS_FUNC(zhbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbevx "BLAS_FUNC(zhbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgst "BLAS_FUNC(zhbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgv "BLAS_FUNC(zhbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgvd "BLAS_FUNC(zhbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgvx "BLAS_FUNC(zhbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbtrd "BLAS_FUNC(zhbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil
+cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhecon "BLAS_FUNC(zhecon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhecon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheequb "BLAS_FUNC(zheequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil
+cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil:
+    
+    _fortran_zheequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheev "BLAS_FUNC(zheev)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevd "BLAS_FUNC(zheevd)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevr "BLAS_FUNC(zheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevx "BLAS_FUNC(zheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegs2 "BLAS_FUNC(zhegs2)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhegs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegst "BLAS_FUNC(zhegst)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhegst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegv "BLAS_FUNC(zhegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegvd "BLAS_FUNC(zhegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegvx "BLAS_FUNC(zhegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zherfs "BLAS_FUNC(zherfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhesv "BLAS_FUNC(zhesv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhesvx "BLAS_FUNC(zhesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheswapr "BLAS_FUNC(zheswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil
+cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_zheswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetd2 "BLAS_FUNC(zhetd2)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, int *info) nogil
+cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil:
+    
+    _fortran_zhetd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetf2 "BLAS_FUNC(zhetf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zhetf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrd "BLAS_FUNC(zhetrd)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrf "BLAS_FUNC(zhetrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri "BLAS_FUNC(zhetri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhetri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri2 "BLAS_FUNC(zhetri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri2x "BLAS_FUNC(zhetri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil
+cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_zhetri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrs "BLAS_FUNC(zhetrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrs2 "BLAS_FUNC(zhetrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil
+cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhfrk "BLAS_FUNC(zhfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c) nogil
+cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil:
+    
+    _fortran_zhfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhgeqz "BLAS_FUNC(zhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpcon "BLAS_FUNC(zhpcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpev "BLAS_FUNC(zhpev)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpevd "BLAS_FUNC(zhpevd)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpevx "BLAS_FUNC(zhpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgst "BLAS_FUNC(zhpgst)"(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info) nogil
+cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil:
+    
+    _fortran_zhpgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgv "BLAS_FUNC(zhpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgvd "BLAS_FUNC(zhpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgvx "BLAS_FUNC(zhpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhprfs "BLAS_FUNC(zhprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpsv "BLAS_FUNC(zhpsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpsvx "BLAS_FUNC(zhpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrd "BLAS_FUNC(zhptrd)"(char *uplo, int *n, npy_complex128 *ap, d *d, d *e, npy_complex128 *tau, int *info) nogil
+cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil:
+    
+    _fortran_zhptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrf "BLAS_FUNC(zhptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil
+cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zhptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptri "BLAS_FUNC(zhptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrs "BLAS_FUNC(zhptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhsein "BLAS_FUNC(zhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *ifaill, int *ifailr, int *info) nogil
+cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_zhsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhseqr "BLAS_FUNC(zhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlabrd "BLAS_FUNC(zlabrd)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy) nogil
+cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil:
+    
+    _fortran_zlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacgv "BLAS_FUNC(zlacgv)"(int *n, npy_complex128 *x, int *incx) nogil
+cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil:
+    
+    _fortran_zlacgv(n, x, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacn2 "BLAS_FUNC(zlacn2)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase, int *isave) nogil
+cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_zlacn2(n, v, x, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacon "BLAS_FUNC(zlacon)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase) nogil
+cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil:
+    
+    _fortran_zlacon(n, v, x, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacp2 "BLAS_FUNC(zlacp2)"(char *uplo, int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlacp2(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacpy "BLAS_FUNC(zlacpy)"(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacrm "BLAS_FUNC(zlacrm)"(int *m, int *n, npy_complex128 *a, int *lda, d *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil
+cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil:
+    
+    _fortran_zlacrm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacrt "BLAS_FUNC(zlacrt)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s) nogil
+cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil:
+    
+    _fortran_zlacrt(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zladiv "F_FUNC(zladivwrp,ZLADIVWRP)"(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y) nogil
+cdef z zladiv(z *x, z *y) noexcept nogil:
+    cdef z out
+    _fortran_zladiv(&out, x, y)
+    return out
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed0 "BLAS_FUNC(zlaed0)"(int *qsiz, int *n, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, d *rwork, int *iwork, int *info) nogil
+cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlaed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed7 "BLAS_FUNC(zlaed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, npy_complex128 *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, npy_complex128 *work, d *rwork, int *iwork, int *info) nogil
+cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlaed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed8 "BLAS_FUNC(zlaed8)"(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, npy_complex128 *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) nogil
+cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil:
+    
+    _fortran_zlaed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaein "BLAS_FUNC(zlaein)"(bint *rightv, bint *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) nogil
+cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil:
+    
+    _fortran_zlaein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaesy "BLAS_FUNC(zlaesy)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1) nogil
+cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil:
+    
+    _fortran_zlaesy(a, b, c, rt1, rt2, evscal, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaev2 "BLAS_FUNC(zlaev2)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, d *rt1, d *rt2, d *cs1, npy_complex128 *sn1) nogil
+cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil:
+    
+    _fortran_zlaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlag2c "BLAS_FUNC(zlag2c)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil
+cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_zlag2c(m, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlags2 "BLAS_FUNC(zlags2)"(bint *upper, d *a1, npy_complex128 *a2, d *a3, d *b1, npy_complex128 *b2, d *b3, d *csu, npy_complex128 *snu, d *csv, npy_complex128 *snv, d *csq, npy_complex128 *snq) nogil
+cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil:
+    
+    _fortran_zlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlagtm "BLAS_FUNC(zlagtm)"(char *trans, int *n, int *nrhs, d *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, d *beta, npy_complex128 *b, int *ldb) nogil
+cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahef "BLAS_FUNC(zlahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) nogil
+cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_zlahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahqr "BLAS_FUNC(zlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info) nogil
+cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_zlahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahr2 "BLAS_FUNC(zlahr2)"(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy) nogil
+cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil:
+    
+    _fortran_zlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaic1 "BLAS_FUNC(zlaic1)"(int *job, int *j, npy_complex128 *x, d *sest, npy_complex128 *w, npy_complex128 *gamma, d *sestpr, npy_complex128 *s, npy_complex128 *c) nogil
+cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil:
+    
+    _fortran_zlaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlals0 "BLAS_FUNC(zlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) nogil
+cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlalsa "BLAS_FUNC(zlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) nogil
+cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlalsd "BLAS_FUNC(zlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, npy_complex128 *b, int *ldb, d *rcond, int *rank, npy_complex128 *work, d *rwork, int *iwork, int *info) nogil
+cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlangb "BLAS_FUNC(zlangb)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlange "BLAS_FUNC(zlange)"(char *norm, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlangt "BLAS_FUNC(zlangt)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du) nogil
+cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil:
+    
+    return _fortran_zlangt(norm, n, dl, d_, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhb "BLAS_FUNC(zlanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlanhb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhe "BLAS_FUNC(zlanhe)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlanhe(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhf "BLAS_FUNC(zlanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, d *work) nogil
+cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil:
+    
+    return _fortran_zlanhf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhp "BLAS_FUNC(zlanhp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlanhp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhs "BLAS_FUNC(zlanhs)"(char *norm, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanht "BLAS_FUNC(zlanht)"(char *norm, int *n, d *d_, npy_complex128 *e) nogil
+cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil:
+    
+    return _fortran_zlanht(norm, n, d_, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansb "BLAS_FUNC(zlansb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansp "BLAS_FUNC(zlansp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansy "BLAS_FUNC(zlansy)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantb "BLAS_FUNC(zlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantp "BLAS_FUNC(zlantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantr "BLAS_FUNC(zlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapll "BLAS_FUNC(zlapll)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *ssmin) nogil
+cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil:
+    
+    _fortran_zlapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapmr "BLAS_FUNC(zlapmr)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil
+cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_zlapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapmt "BLAS_FUNC(zlapmt)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil
+cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_zlapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqgb "BLAS_FUNC(zlaqgb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqge "BLAS_FUNC(zlaqge)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhb "BLAS_FUNC(zlaqhb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhe "BLAS_FUNC(zlaqhe)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhe(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhp "BLAS_FUNC(zlaqhp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqp2 "BLAS_FUNC(zlaqp2)"(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *work) nogil
+cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil:
+    
+    _fortran_zlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqps "BLAS_FUNC(zlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf) nogil
+cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil:
+    
+    _fortran_zlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr0 "BLAS_FUNC(zlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr1 "BLAS_FUNC(zlaqr1)"(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v) nogil
+cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil:
+    
+    _fortran_zlaqr1(n, h, ldh, s1, s2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr2 "BLAS_FUNC(zlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) nogil
+cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil:
+    
+    _fortran_zlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr3 "BLAS_FUNC(zlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) nogil
+cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil:
+    
+    _fortran_zlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr4 "BLAS_FUNC(zlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr5 "BLAS_FUNC(zlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh) nogil
+cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_zlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsb "BLAS_FUNC(zlaqsb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsp "BLAS_FUNC(zlaqsp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsy "BLAS_FUNC(zlaqsy)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlar1v "BLAS_FUNC(zlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, npy_complex128 *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) nogil
+cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil:
+    
+    _fortran_zlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlar2v "BLAS_FUNC(zlar2v)"(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, d *c, npy_complex128 *s, int *incc) nogil
+cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil:
+    
+    _fortran_zlar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarcm "BLAS_FUNC(zlarcm)"(int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil
+cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil:
+    
+    _fortran_zlarcm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarf "BLAS_FUNC(zlarf)"(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfb "BLAS_FUNC(zlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) nogil
+cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil:
+    
+    _fortran_zlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfg "BLAS_FUNC(zlarfg)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil
+cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil:
+    
+    _fortran_zlarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfgp "BLAS_FUNC(zlarfgp)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil
+cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil:
+    
+    _fortran_zlarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarft "BLAS_FUNC(zlarft)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil
+cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil:
+    
+    _fortran_zlarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfx "BLAS_FUNC(zlarfx)"(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlargv "BLAS_FUNC(zlargv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, int *incc) nogil
+cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil:
+    
+    _fortran_zlargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarnv "BLAS_FUNC(zlarnv)"(int *idist, int *iseed, int *n, npy_complex128 *x) nogil
+cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil:
+    
+    _fortran_zlarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarrv "BLAS_FUNC(zlarrv)"(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) nogil
+cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlartg "BLAS_FUNC(zlartg)"(npy_complex128 *f, npy_complex128 *g, d *cs, npy_complex128 *sn, npy_complex128 *r) nogil
+cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil:
+    
+    _fortran_zlartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlartv "BLAS_FUNC(zlartv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, npy_complex128 *s, int *incc) nogil
+cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil:
+    
+    _fortran_zlartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarz "BLAS_FUNC(zlarz)"(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarzb "BLAS_FUNC(zlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) nogil
+cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil:
+    
+    _fortran_zlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarzt "BLAS_FUNC(zlarzt)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil
+cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil:
+    
+    _fortran_zlarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlascl "BLAS_FUNC(zlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaset "BLAS_FUNC(zlaset)"(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda) nogil
+cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zlaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlasr "BLAS_FUNC(zlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, npy_complex128 *a, int *lda) nogil
+cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zlasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlassq "BLAS_FUNC(zlassq)"(int *n, npy_complex128 *x, int *incx, d *scale, d *sumsq) nogil
+cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil:
+    
+    _fortran_zlassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaswp "BLAS_FUNC(zlaswp)"(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_zlaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlasyf "BLAS_FUNC(zlasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) nogil
+cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_zlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlat2c "BLAS_FUNC(zlat2c)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil
+cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_zlat2c(uplo, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatbs "BLAS_FUNC(zlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil
+cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_zlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatdf "BLAS_FUNC(zlatdf)"(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil
+cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_zlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatps "BLAS_FUNC(zlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil
+cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_zlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrd "BLAS_FUNC(zlatrd)"(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, d *e, npy_complex128 *tau, npy_complex128 *w, int *ldw) nogil
+cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil:
+    
+    _fortran_zlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrs "BLAS_FUNC(zlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil
+cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_zlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrz "BLAS_FUNC(zlatrz)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work) nogil
+cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil:
+    
+    _fortran_zlatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlauu2 "BLAS_FUNC(zlauu2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlauum "BLAS_FUNC(zlauum)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbcon "BLAS_FUNC(zpbcon)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbequ "BLAS_FUNC(zpbequ)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbrfs "BLAS_FUNC(zpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbstf "BLAS_FUNC(zpbstf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbsv "BLAS_FUNC(zpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbsvx "BLAS_FUNC(zpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtf2 "BLAS_FUNC(zpbtf2)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtrf "BLAS_FUNC(zpbtrf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtrs "BLAS_FUNC(zpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftrf "BLAS_FUNC(zpftrf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil
+cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_zpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftri "BLAS_FUNC(zpftri)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil
+cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_zpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftrs "BLAS_FUNC(zpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpocon "BLAS_FUNC(zpocon)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpoequ "BLAS_FUNC(zpoequ)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpoequb "BLAS_FUNC(zpoequb)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zporfs "BLAS_FUNC(zporfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zposv "BLAS_FUNC(zposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zposvx "BLAS_FUNC(zposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotf2 "BLAS_FUNC(zpotf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotrf "BLAS_FUNC(zpotrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotri "BLAS_FUNC(zpotri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotrs "BLAS_FUNC(zpotrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppcon "BLAS_FUNC(zppcon)"(char *uplo, int *n, npy_complex128 *ap, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zppcon(uplo, n, ap, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppequ "BLAS_FUNC(zppequ)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, int *info) nogil
+cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpprfs "BLAS_FUNC(zpprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppsv "BLAS_FUNC(zppsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppsvx "BLAS_FUNC(zppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptrf "BLAS_FUNC(zpptrf)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil
+cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_zpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptri "BLAS_FUNC(zpptri)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil
+cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_zpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptrs "BLAS_FUNC(zpptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpstf2 "BLAS_FUNC(zpstf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpstrf "BLAS_FUNC(zpstrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptcon "BLAS_FUNC(zptcon)"(int *n, d *d, npy_complex128 *e, d *anorm, d *rcond, d *rwork, int *info) nogil
+cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptcon(n, d, e, anorm, rcond, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpteqr "BLAS_FUNC(zpteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil
+cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptrfs "BLAS_FUNC(zptrfs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptsv "BLAS_FUNC(zptsv)"(int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptsvx "BLAS_FUNC(zptsvx)"(char *fact, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpttrf "BLAS_FUNC(zpttrf)"(int *n, d *d, npy_complex128 *e, int *info) nogil
+cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil:
+    
+    _fortran_zpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpttrs "BLAS_FUNC(zpttrs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpttrs(uplo, n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptts2 "BLAS_FUNC(zptts2)"(int *iuplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb) nogil
+cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zptts2(iuplo, n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zrot "BLAS_FUNC(zrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, npy_complex128 *s) nogil
+cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil:
+    
+    _fortran_zrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspcon "BLAS_FUNC(zspcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspmv "BLAS_FUNC(zspmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspr "BLAS_FUNC(zspr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
+cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil:
+    
+    _fortran_zspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsprfs "BLAS_FUNC(zsprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspsv "BLAS_FUNC(zspsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspsvx "BLAS_FUNC(zspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptrf "BLAS_FUNC(zsptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil
+cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zsptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptri "BLAS_FUNC(zsptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptrs "BLAS_FUNC(zsptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstedc "BLAS_FUNC(zstedc)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstegr "BLAS_FUNC(zstegr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstein "BLAS_FUNC(zstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstemr "BLAS_FUNC(zstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsteqr "BLAS_FUNC(zsteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil
+cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_zsteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsycon "BLAS_FUNC(zsycon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyconv "BLAS_FUNC(zsyconv)"(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyequb "BLAS_FUNC(zsyequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil
+cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsymv "BLAS_FUNC(zsymv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyr "BLAS_FUNC(zsyr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
+cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zsyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyrfs "BLAS_FUNC(zsyrfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsysv "BLAS_FUNC(zsysv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsysvx "BLAS_FUNC(zsysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyswapr "BLAS_FUNC(zsyswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil
+cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_zsyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytf2 "BLAS_FUNC(zsytf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zsytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrf "BLAS_FUNC(zsytrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri "BLAS_FUNC(zsytri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri2 "BLAS_FUNC(zsytri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri2x "BLAS_FUNC(zsytri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil
+cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_zsytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrs "BLAS_FUNC(zsytrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrs2 "BLAS_FUNC(zsytrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil
+cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbcon "BLAS_FUNC(ztbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbrfs "BLAS_FUNC(ztbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbtrs "BLAS_FUNC(ztbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfsm "BLAS_FUNC(ztfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb) nogil
+cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_ztfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztftri "BLAS_FUNC(ztftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info) nogil
+cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_ztftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfttp "BLAS_FUNC(ztfttp)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info) nogil
+cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfttr "BLAS_FUNC(ztfttr)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgevc "BLAS_FUNC(ztgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgex2 "BLAS_FUNC(ztgex2)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info) nogil
+cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil:
+    
+    _fortran_ztgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgexc "BLAS_FUNC(ztgexc)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info) nogil
+cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ztgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsen "BLAS_FUNC(ztgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, d *pl, d *pr, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ztgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsja "BLAS_FUNC(ztgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info) nogil
+cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_ztgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsna "BLAS_FUNC(ztgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ztgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsy2 "BLAS_FUNC(ztgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) nogil
+cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil:
+    
+    _fortran_ztgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsyl "BLAS_FUNC(ztgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ztgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpcon "BLAS_FUNC(ztpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpmqrt "BLAS_FUNC(ztpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil
+cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil:
+    
+    _fortran_ztpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpqrt "BLAS_FUNC(ztpqrt)"(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil
+cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil:
+    
+    _fortran_ztpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpqrt2 "BLAS_FUNC(ztpqrt2)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_ztpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztprfb "BLAS_FUNC(ztprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork) nogil
+cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil:
+    
+    _fortran_ztprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztprfs "BLAS_FUNC(ztprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztptri "BLAS_FUNC(ztptri)"(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info) nogil
+cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztptrs "BLAS_FUNC(ztptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpttf "BLAS_FUNC(ztpttf)"(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info) nogil
+cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil:
+    
+    _fortran_ztpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpttr "BLAS_FUNC(ztpttr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrcon "BLAS_FUNC(ztrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrevc "BLAS_FUNC(ztrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrexc "BLAS_FUNC(ztrexc)"(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info) nogil
+cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ztrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrrfs "BLAS_FUNC(ztrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsen "BLAS_FUNC(ztrsen)"(char *job, char *compq, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, d *s, d *sep, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ztrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsna "BLAS_FUNC(ztrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, d *rwork, int *info) nogil
+cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsyl "BLAS_FUNC(ztrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *scale, int *info) nogil
+cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil:
+    
+    _fortran_ztrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrti2 "BLAS_FUNC(ztrti2)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrtri "BLAS_FUNC(ztrtri)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrtrs "BLAS_FUNC(ztrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrttf "BLAS_FUNC(ztrttf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info) nogil
+cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil:
+    
+    _fortran_ztrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrttp "BLAS_FUNC(ztrttp)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info) nogil
+cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztzrzf "BLAS_FUNC(ztzrzf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ztzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunbdb "BLAS_FUNC(zunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, d *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zuncsd "BLAS_FUNC(zuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) nogil
+cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zung2l "BLAS_FUNC(zung2l)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zung2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zung2r "BLAS_FUNC(zung2r)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zung2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungbr "BLAS_FUNC(zungbr)"(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunghr "BLAS_FUNC(zunghr)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungl2 "BLAS_FUNC(zungl2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zungl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunglq "BLAS_FUNC(zunglq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungql "BLAS_FUNC(zungql)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungqr "BLAS_FUNC(zungqr)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungr2 "BLAS_FUNC(zungr2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zungr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungrq "BLAS_FUNC(zungrq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungtr "BLAS_FUNC(zungtr)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunm2l "BLAS_FUNC(zunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunm2r "BLAS_FUNC(zunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmbr "BLAS_FUNC(zunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmhr "BLAS_FUNC(zunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunml2 "BLAS_FUNC(zunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmlq "BLAS_FUNC(zunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmql "BLAS_FUNC(zunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmqr "BLAS_FUNC(zunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmr2 "BLAS_FUNC(zunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmr3 "BLAS_FUNC(zunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmrq "BLAS_FUNC(zunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmrz "BLAS_FUNC(zunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmtr "BLAS_FUNC(zunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zupgtr "BLAS_FUNC(zupgtr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil
+cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil:
+    
+    _fortran_zupgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zupmtr "BLAS_FUNC(zupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+
+# Python accessible wrappers for testing:
+
+def _test_dlamch(cmach):
+    # This conversion is necessary to handle Python 3 strings.
+    cmach_bytes = bytes(cmach)
+    # Now that it is a bytes representation, a non-temporary variable
+    # must be passed as a part of the function call.
+    cdef char* cmach_char = cmach_bytes
+    return dlamch(cmach_char)
+
+def _test_slamch(cmach):
+    # This conversion is necessary to handle Python 3 strings.
+    cmach_bytes = bytes(cmach)
+    # Now that it is a bytes representation, a non-temporary variable
+    # must be passed as a part of the function call.
+    cdef char* cmach_char = cmach_bytes
+    return slamch(cmach_char)
+
+cpdef double complex _test_zladiv(double complex zx, double complex zy) noexcept nogil:
+    return zladiv(&zx, &zy)
+
+cpdef float complex _test_cladiv(float complex cx, float complex cy) noexcept nogil:
+    return cladiv(&cx, &cy)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/decomp.py b/venv/lib/python3.10/site-packages/scipy/linalg/decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d82ab157ce3be763f63e453c9a6fee064557c85
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/decomp.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'eig', 'eigvals', 'eigh', 'eigvalsh',
+    'eig_banded', 'eigvals_banded',
+    'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf',
+    'LinAlgError', 'norm', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp",
+                                   private_modules=["_decomp"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..92545a5c6af5fe7a4de13f8746b96696d68b5bd2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+    'cho_solve_banded', 'LinAlgError', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky",
+                                   private_modules=["_decomp_cholesky"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d5d9a98a04a689fb735f81299e129dc7f307590
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'lu', 'lu_solve', 'lu_factor',
+    'LinAlgWarning', 'get_lapack_funcs',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_lu",
+                                   private_modules=["_decomp_lu"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ef58729412ce2c83310b7817a143d14b8f28c19
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'qr', 'qr_multiply', 'rq', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_qr",
+                                   private_modules=["_decomp_qr"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3c6cc494db9b35dce8e4007c8c30d823b03881f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'schur', 'rsf2csf', 'norm', 'LinAlgError', 'get_lapack_funcs', 'eigvals',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_schur",
+                                   private_modules=["_decomp_schur"], all=__all__,
+                                   attribute=name)
+
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..64d0ce8562f06a3837df050f0ea6b8b15a2b359e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space',
+    'LinAlgError', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_svd",
+                                   private_modules=["_decomp_svd"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py b/venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..38070863aa515266b0b130dbbdbd3d645da4aa0c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py
@@ -0,0 +1,989 @@
+#  ******************************************************************************
+#   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.
+#  ******************************************************************************
+
+r"""
+======================================================================
+Interpolative matrix decomposition (:mod:`scipy.linalg.interpolative`)
+======================================================================
+
+.. versionadded:: 0.13
+
+.. versionchanged:: 1.15.0
+    The underlying algorithms have been ported to Python from the original Fortran77
+    code. See references below for more details.
+
+.. currentmodule:: scipy.linalg.interpolative
+
+An interpolative decomposition (ID) of a matrix :math:`A \in
+\mathbb{C}^{m \times n}` of rank :math:`k \leq \min \{ m, n \}` is a
+factorization
+
+.. math::
+  A \Pi =
+  \begin{bmatrix}
+   A \Pi_{1} & A \Pi_{2}
+  \end{bmatrix} =
+  A \Pi_{1}
+  \begin{bmatrix}
+   I & T
+  \end{bmatrix},
+
+where :math:`\Pi = [\Pi_{1}, \Pi_{2}]` is a permutation matrix with
+:math:`\Pi_{1} \in \{ 0, 1 \}^{n \times k}`, i.e., :math:`A \Pi_{2} =
+A \Pi_{1} T`. This can equivalently be written as :math:`A = BP`,
+where :math:`B = A \Pi_{1}` and :math:`P = [I, T] \Pi^{\mathsf{T}}`
+are the *skeleton* and *interpolation matrices*, respectively.
+
+If :math:`A` does not have exact rank :math:`k`, then there exists an
+approximation in the form of an ID such that :math:`A = BP + E`, where
+:math:`\| E \| \sim \sigma_{k + 1}` is on the order of the :math:`(k +
+1)`-th largest singular value of :math:`A`. Note that :math:`\sigma_{k
++ 1}` is the best possible error for a rank-:math:`k` approximation
+and, in fact, is achieved by the singular value decomposition (SVD)
+:math:`A \approx U S V^{*}`, where :math:`U \in \mathbb{C}^{m \times
+k}` and :math:`V \in \mathbb{C}^{n \times k}` have orthonormal columns
+and :math:`S = \mathop{\mathrm{diag}} (\sigma_{i}) \in \mathbb{C}^{k
+\times k}` is diagonal with nonnegative entries. The principal
+advantages of using an ID over an SVD are that:
+
+- it is cheaper to construct;
+- it preserves the structure of :math:`A`; and
+- it is more efficient to compute with in light of the identity submatrix of :math:`P`.
+
+Routines
+========
+
+Main functionality:
+
+.. autosummary::
+   :toctree: generated/
+
+   interp_decomp
+   reconstruct_matrix_from_id
+   reconstruct_interp_matrix
+   reconstruct_skel_matrix
+   id_to_svd
+   svd
+   estimate_spectral_norm
+   estimate_spectral_norm_diff
+   estimate_rank
+
+Following support functions are deprecated and will be removed in SciPy 1.17.0:
+
+.. autosummary::
+   :toctree: generated/
+
+   seed
+   rand
+
+
+References
+==========
+
+This module uses the algorithms found in ID software package [1]_ by Martinsson,
+Rokhlin, Shkolnisky, and Tygert, which is a Fortran library for computing IDs using
+various algorithms, including the rank-revealing QR approach of [2]_ and the more
+recent randomized methods described in [3]_, [4]_, and [5]_.
+
+We advise the user to consult also the documentation for the `ID package
+`_.
+
+.. [1] P.G. Martinsson, V. Rokhlin, Y. Shkolnisky, M. Tygert. "ID: a
+    software package for low-rank approximation of matrices via interpolative
+    decompositions, version 0.2." http://tygert.com/id_doc.4.pdf.
+
+.. [2] H. Cheng, Z. Gimbutas, P.G. Martinsson, V. Rokhlin. "On the
+    compression of low rank matrices." *SIAM J. Sci. Comput.* 26 (4): 1389--1404,
+    2005. :doi:`10.1137/030602678`.
+
+.. [3] E. Liberty, F. Woolfe, P.G. Martinsson, V. Rokhlin, M.
+    Tygert. "Randomized algorithms for the low-rank approximation of matrices."
+    *Proc. Natl. Acad. Sci. U.S.A.* 104 (51): 20167--20172, 2007.
+    :doi:`10.1073/pnas.0709640104`.
+
+.. [4] P.G. Martinsson, V. Rokhlin, M. Tygert. "A randomized
+    algorithm for the decomposition of matrices." *Appl. Comput. Harmon. Anal.* 30
+    (1): 47--68,  2011. :doi:`10.1016/j.acha.2010.02.003`.
+
+.. [5] F. Woolfe, E. Liberty, V. Rokhlin, M. Tygert. "A fast
+    randomized algorithm for the approximation of matrices." *Appl. Comput.
+    Harmon. Anal.* 25 (3): 335--366, 2008. :doi:`10.1016/j.acha.2007.12.002`.
+
+
+Tutorial
+========
+
+Initializing
+------------
+
+The first step is to import :mod:`scipy.linalg.interpolative` by issuing the
+command:
+
+>>> import scipy.linalg.interpolative as sli
+
+Now let's build a matrix. For this, we consider a Hilbert matrix, which is well
+know to have low rank:
+
+>>> from scipy.linalg import hilbert
+>>> n = 1000
+>>> A = hilbert(n)
+
+We can also do this explicitly via:
+
+>>> import numpy as np
+>>> n = 1000
+>>> A = np.empty((n, n), order='F')
+>>> for j in range(n):
+...     for i in range(n):
+...         A[i,j] = 1. / (i + j + 1)
+
+Note the use of the flag ``order='F'`` in :func:`numpy.empty`. This
+instantiates the matrix in Fortran-contiguous order and is important for
+avoiding data copying when passing to the backend.
+
+We then define multiplication routines for the matrix by regarding it as a
+:class:`scipy.sparse.linalg.LinearOperator`:
+
+>>> from scipy.sparse.linalg import aslinearoperator
+>>> L = aslinearoperator(A)
+
+This automatically sets up methods describing the action of the matrix and its
+adjoint on a vector.
+
+Computing an ID
+---------------
+
+We have several choices of algorithm to compute an ID. These fall largely
+according to two dichotomies:
+
+1. how the matrix is represented, i.e., via its entries or via its action on a
+   vector; and
+2. whether to approximate it to a fixed relative precision or to a fixed rank.
+
+We step through each choice in turn below.
+
+In all cases, the ID is represented by three parameters:
+
+1. a rank ``k``;
+2. an index array ``idx``; and
+3. interpolation coefficients ``proj``.
+
+The ID is specified by the relation
+``np.dot(A[:,idx[:k]], proj) == A[:,idx[k:]]``.
+
+From matrix entries
+...................
+
+We first consider a matrix given in terms of its entries.
+
+To compute an ID to a fixed precision, type:
+
+>>> eps = 1e-3
+>>> k, idx, proj = sli.interp_decomp(A, eps)
+
+where ``eps < 1`` is the desired precision.
+
+To compute an ID to a fixed rank, use:
+
+>>> idx, proj = sli.interp_decomp(A, k)
+
+where ``k >= 1`` is the desired rank.
+
+Both algorithms use random sampling and are usually faster than the
+corresponding older, deterministic algorithms, which can be accessed via the
+commands:
+
+>>> k, idx, proj = sli.interp_decomp(A, eps, rand=False)
+
+and:
+
+>>> idx, proj = sli.interp_decomp(A, k, rand=False)
+
+respectively.
+
+From matrix action
+..................
+
+Now consider a matrix given in terms of its action on a vector as a
+:class:`scipy.sparse.linalg.LinearOperator`.
+
+To compute an ID to a fixed precision, type:
+
+>>> k, idx, proj = sli.interp_decomp(L, eps)
+
+To compute an ID to a fixed rank, use:
+
+>>> idx, proj = sli.interp_decomp(L, k)
+
+These algorithms are randomized.
+
+Reconstructing an ID
+--------------------
+
+The ID routines above do not output the skeleton and interpolation matrices
+explicitly but instead return the relevant information in a more compact (and
+sometimes more useful) form. To build these matrices, write:
+
+>>> B = sli.reconstruct_skel_matrix(A, k, idx)
+
+for the skeleton matrix and:
+
+>>> P = sli.reconstruct_interp_matrix(idx, proj)
+
+for the interpolation matrix. The ID approximation can then be computed as:
+
+>>> C = np.dot(B, P)
+
+This can also be constructed directly using:
+
+>>> C = sli.reconstruct_matrix_from_id(B, idx, proj)
+
+without having to first compute ``P``.
+
+Alternatively, this can be done explicitly as well using:
+
+>>> B = A[:,idx[:k]]
+>>> P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)]
+>>> C = np.dot(B, P)
+
+Computing an SVD
+----------------
+
+An ID can be converted to an SVD via the command:
+
+>>> U, S, V = sli.id_to_svd(B, idx, proj)
+
+The SVD approximation is then:
+
+>>> approx = U @ np.diag(S) @ V.conj().T
+
+The SVD can also be computed "fresh" by combining both the ID and conversion
+steps into one command. Following the various ID algorithms above, there are
+correspondingly various SVD algorithms that one can employ.
+
+From matrix entries
+...................
+
+We consider first SVD algorithms for a matrix given in terms of its entries.
+
+To compute an SVD to a fixed precision, type:
+
+>>> U, S, V = sli.svd(A, eps)
+
+To compute an SVD to a fixed rank, use:
+
+>>> U, S, V = sli.svd(A, k)
+
+Both algorithms use random sampling; for the deterministic versions, issue the
+keyword ``rand=False`` as above.
+
+From matrix action
+..................
+
+Now consider a matrix given in terms of its action on a vector.
+
+To compute an SVD to a fixed precision, type:
+
+>>> U, S, V = sli.svd(L, eps)
+
+To compute an SVD to a fixed rank, use:
+
+>>> U, S, V = sli.svd(L, k)
+
+Utility routines
+----------------
+
+Several utility routines are also available.
+
+To estimate the spectral norm of a matrix, use:
+
+>>> snorm = sli.estimate_spectral_norm(A)
+
+This algorithm is based on the randomized power method and thus requires only
+matrix-vector products. The number of iterations to take can be set using the
+keyword ``its`` (default: ``its=20``). The matrix is interpreted as a
+:class:`scipy.sparse.linalg.LinearOperator`, but it is also valid to supply it
+as a :class:`numpy.ndarray`, in which case it is trivially converted using
+:func:`scipy.sparse.linalg.aslinearoperator`.
+
+The same algorithm can also estimate the spectral norm of the difference of two
+matrices ``A1`` and ``A2`` as follows:
+
+>>> A1, A2 = A**2, A
+>>> diff = sli.estimate_spectral_norm_diff(A1, A2)
+
+This is often useful for checking the accuracy of a matrix approximation.
+
+Some routines in :mod:`scipy.linalg.interpolative` require estimating the rank
+of a matrix as well. This can be done with either:
+
+>>> k = sli.estimate_rank(A, eps)
+
+or:
+
+>>> k = sli.estimate_rank(L, eps)
+
+depending on the representation. The parameter ``eps`` controls the definition
+of the numerical rank.
+
+Finally, the random number generation required for all randomized routines can
+be controlled via providing NumPy pseudo-random generators with a fixed seed. See
+:class:`numpy.random.Generator` and :func:`numpy.random.default_rng` for more details.
+
+Remarks
+-------
+
+The above functions all automatically detect the appropriate interface and work
+with both real and complex data types, passing input arguments to the proper
+backend routine.
+
+"""
+
+import scipy.linalg._decomp_interpolative as _backend
+import numpy as np
+import warnings
+
+__all__ = [
+    'estimate_rank',
+    'estimate_spectral_norm',
+    'estimate_spectral_norm_diff',
+    'id_to_svd',
+    'interp_decomp',
+    'rand',
+    'reconstruct_interp_matrix',
+    'reconstruct_matrix_from_id',
+    'reconstruct_skel_matrix',
+    'seed',
+    'svd',
+]
+
+_DTYPE_ERROR = ValueError("invalid input dtype (input must be float64 or complex128)")
+_TYPE_ERROR = TypeError("invalid input type (must be array or LinearOperator)")
+
+
+def _C_contiguous_copy(A):
+    """
+    Same as np.ascontiguousarray, but ensure a copy
+    """
+    A = np.asarray(A)
+    if A.flags.c_contiguous:
+        A = A.copy()
+    else:
+        A = np.ascontiguousarray(A)
+    return A
+
+
+def _is_real(A):
+    try:
+        if A.dtype == np.complex128:
+            return False
+        elif A.dtype == np.float64:
+            return True
+        else:
+            raise _DTYPE_ERROR
+    except AttributeError as e:
+        raise _TYPE_ERROR from e
+
+
+def seed(seed=None):
+    """
+    This function, historically, used to set the seed of the randomization algorithms
+    used in the `scipy.linalg.interpolative` functions written in Fortran77.
+
+    The library has been ported to Python and now the functions use the native NumPy
+    generators and this function has no content and returns None. Thus this function
+    should not be used and will be removed in SciPy version 1.17.0.
+    """
+    warnings.warn("`scipy.linalg.interpolative.seed` is deprecated and will be "
+                  "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
+
+
+def rand(*shape):
+    """
+    This function, historically, used to generate uniformly distributed random number
+    for the randomization algorithms used in the `scipy.linalg.interpolative` functions
+    written in Fortran77.
+
+    The library has been ported to Python and now the functions use the native NumPy
+    generators. Thus this function should not be used and will be removed in the
+    SciPy version 1.17.0.
+
+    If pseudo-random numbers are needed, NumPy pseudo-random generators should be used
+    instead.
+
+    Parameters
+    ----------
+    *shape
+        Shape of output array
+
+    """
+    warnings.warn("`scipy.linalg.interpolative.rand` is deprecated and will be "
+                  "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
+    rng = np.random.default_rng()
+    return rng.uniform(low=0., high=1.0, size=shape)
+
+
+def interp_decomp(A, eps_or_k, rand=True, rng=None):
+    """
+    Compute ID of a matrix.
+
+    An ID of a matrix `A` is a factorization defined by a rank `k`, a column
+    index array `idx`, and interpolation coefficients `proj` such that::
+
+        numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]]
+
+    The original matrix can then be reconstructed as::
+
+        numpy.hstack([A[:,idx[:k]],
+                                    numpy.dot(A[:,idx[:k]], proj)]
+                                )[:,numpy.argsort(idx)]
+
+    or via the routine :func:`reconstruct_matrix_from_id`. This can
+    equivalently be written as::
+
+        numpy.dot(A[:,idx[:k]],
+                            numpy.hstack([numpy.eye(k), proj])
+                          )[:,np.argsort(idx)]
+
+    in terms of the skeleton and interpolation matrices::
+
+        B = A[:,idx[:k]]
+
+    and::
+
+        P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)]
+
+    respectively. See also :func:`reconstruct_interp_matrix` and
+    :func:`reconstruct_skel_matrix`.
+
+    The ID can be computed to any relative precision or rank (depending on the
+    value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then
+    this function has the output signature::
+
+        k, idx, proj = interp_decomp(A, eps_or_k)
+
+    Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output
+    signature is::
+
+        idx, proj = interp_decomp(A, eps_or_k)
+
+    ..  This function automatically detects the form of the input parameters
+        and passes them to the appropriate backend. For details, see
+        :func:`_backend.iddp_id`, :func:`_backend.iddp_aid`,
+        :func:`_backend.iddp_rid`, :func:`_backend.iddr_id`,
+        :func:`_backend.iddr_aid`, :func:`_backend.iddr_rid`,
+        :func:`_backend.idzp_id`, :func:`_backend.idzp_aid`,
+        :func:`_backend.idzp_rid`, :func:`_backend.idzr_id`,
+        :func:`_backend.idzr_aid`, and :func:`_backend.idzr_rid`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec`
+        Matrix to be factored
+    eps_or_k : float or int
+        Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of
+        approximation.
+    rand : bool, optional
+        Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
+        (randomized algorithms are always used if `A` is of type
+        :class:`scipy.sparse.linalg.LinearOperator`).
+    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``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    k : int
+        Rank required to achieve specified relative precision if
+        ``eps_or_k < 1``.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+    """  # numpy/numpydoc#87  # noqa: E501
+    from scipy.sparse.linalg import LinearOperator
+    rng = np.random.default_rng(rng)
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if rand:
+                if real:
+                    k, idx, proj = _backend.iddp_aid(A, eps, rng=rng)
+                else:
+                    k, idx, proj = _backend.idzp_aid(A, eps, rng=rng)
+            else:
+                if real:
+                    k, idx, proj = _backend.iddp_id(A, eps)
+                else:
+                    k, idx, proj = _backend.idzp_id(A, eps)
+            return k, idx, proj
+        else:
+            k = int(eps_or_k)
+            if rand:
+                if real:
+                    idx, proj = _backend.iddr_aid(A, k, rng=rng)
+                else:
+                    idx, proj = _backend.idzr_aid(A, k, rng=rng)
+            else:
+                if real:
+                    idx, proj = _backend.iddr_id(A, k)
+                else:
+                    idx, proj = _backend.idzr_id(A, k)
+            return idx, proj
+    elif isinstance(A, LinearOperator):
+
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if real:
+                k, idx, proj = _backend.iddp_rid(A, eps, rng=rng)
+            else:
+                k, idx, proj = _backend.idzp_rid(A, eps, rng=rng)
+            return k, idx, proj
+        else:
+            k = int(eps_or_k)
+            if real:
+                idx, proj = _backend.iddr_rid(A, k, rng=rng)
+            else:
+                idx, proj = _backend.idzr_rid(A, k, rng=rng)
+            return idx, proj
+    else:
+        raise _TYPE_ERROR
+
+
+def reconstruct_matrix_from_id(B, idx, proj):
+    """
+    Reconstruct matrix from its ID.
+
+    A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx`
+    and `proj`, respectively, can be reconstructed as::
+
+        numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
+
+    See also :func:`reconstruct_interp_matrix` and
+    :func:`reconstruct_skel_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_reconid` and
+        :func:`_backend.idz_reconid`.
+
+    Parameters
+    ----------
+    B : :class:`numpy.ndarray`
+        Skeleton matrix.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Reconstructed matrix.
+    """
+    if _is_real(B):
+        return _backend.idd_reconid(B, idx, proj)
+    else:
+        return _backend.idz_reconid(B, idx, proj)
+
+
+def reconstruct_interp_matrix(idx, proj):
+    """
+    Reconstruct interpolation matrix from ID.
+
+    The interpolation matrix can be reconstructed from the ID indices and
+    coefficients `idx` and `proj`, respectively, as::
+
+        P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)]
+
+    The original matrix can then be reconstructed from its skeleton matrix ``B``
+    via ``A = B @ P``
+
+    See also :func:`reconstruct_matrix_from_id` and
+    :func:`reconstruct_skel_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_reconint` and
+        :func:`_backend.idz_reconint`.
+
+    Parameters
+    ----------
+    idx : :class:`numpy.ndarray`
+        1D column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Interpolation matrix.
+    """
+    n, krank = len(idx), proj.shape[0]
+    if _is_real(proj):
+        p = np.zeros([krank, n], dtype=np.float64)
+    else:
+        p = np.zeros([krank, n], dtype=np.complex128)
+
+    for ci in range(krank):
+        p[ci, idx[ci]] = 1.0
+    p[:, idx[krank:]] = proj[:, :]
+
+    return p
+
+
+def reconstruct_skel_matrix(A, k, idx):
+    """
+    Reconstruct skeleton matrix from ID.
+
+    The skeleton matrix can be reconstructed from the original matrix `A` and its
+    ID rank and indices `k` and `idx`, respectively, as::
+
+        B = A[:,idx[:k]]
+
+    The original matrix can then be reconstructed via::
+
+        numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
+
+    See also :func:`reconstruct_matrix_from_id` and
+    :func:`reconstruct_interp_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_copycols` and
+        :func:`_backend.idz_copycols`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray`
+        Original matrix.
+    k : int
+        Rank of ID.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Skeleton matrix.
+    """
+    return A[:, idx[:k]]
+
+
+def id_to_svd(B, idx, proj):
+    """
+    Convert ID to SVD.
+
+    The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and
+    coefficients `idx` and `proj`, respectively, is::
+
+        U, S, V = id_to_svd(B, idx, proj)
+        A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))
+
+    See also :func:`svd`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_id2svd` and
+        :func:`_backend.idz_id2svd`.
+
+    Parameters
+    ----------
+    B : :class:`numpy.ndarray`
+        Skeleton matrix.
+    idx : :class:`numpy.ndarray`
+        1D column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    U : :class:`numpy.ndarray`
+        Left singular vectors.
+    S : :class:`numpy.ndarray`
+        Singular values.
+    V : :class:`numpy.ndarray`
+        Right singular vectors.
+    """
+    B = _C_contiguous_copy(B)
+    if _is_real(B):
+        U, S, V = _backend.idd_id2svd(B, idx, proj)
+    else:
+        U, S, V = _backend.idz_id2svd(B, idx, proj)
+
+    return U, S, V
+
+
+def estimate_spectral_norm(A, its=20, rng=None):
+    """
+    Estimate spectral norm of a matrix by the randomized power method.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_snorm` and
+        :func:`_backend.idz_snorm`.
+
+    Parameters
+    ----------
+    A : :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
+        `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    its : int, optional
+        Number of power method 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``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    float
+        Spectral norm estimate.
+    """
+    from scipy.sparse.linalg import aslinearoperator
+    rng = np.random.default_rng(rng)
+    A = aslinearoperator(A)
+
+    if _is_real(A):
+        return _backend.idd_snorm(A, its=its, rng=rng)
+    else:
+        return _backend.idz_snorm(A, its=its, rng=rng)
+
+
+def estimate_spectral_norm_diff(A, B, its=20, rng=None):
+    """
+    Estimate spectral norm of the difference of two matrices by the randomized
+    power method.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_diffsnorm` and
+        :func:`_backend.idz_diffsnorm`.
+
+    Parameters
+    ----------
+    A : :class:`scipy.sparse.linalg.LinearOperator`
+        First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
+        `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    B : :class:`scipy.sparse.linalg.LinearOperator`
+        Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with
+        the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    its : int, optional
+        Number of power method 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``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    float
+        Spectral norm estimate of matrix difference.
+    """
+    from scipy.sparse.linalg import aslinearoperator
+    rng = np.random.default_rng(rng)
+    A = aslinearoperator(A)
+    B = aslinearoperator(B)
+
+    if _is_real(A):
+        return _backend.idd_diffsnorm(A, B, its=its, rng=rng)
+    else:
+        return _backend.idz_diffsnorm(A, B, its=its, rng=rng)
+
+
+def svd(A, eps_or_k, rand=True, rng=None):
+    """
+    Compute SVD of a matrix via an ID.
+
+    An SVD of a matrix `A` is a factorization::
+
+        A = U @ np.diag(S) @ V.conj().T
+
+    where `U` and `V` have orthonormal columns and `S` is nonnegative.
+
+    The SVD can be computed to any relative precision or rank (depending on the
+    value of `eps_or_k`).
+
+    See also :func:`interp_decomp` and :func:`id_to_svd`.
+
+    ..  This function automatically detects the form of the input parameters and
+        passes them to the appropriate backend. For details, see
+        :func:`_backend.iddp_svd`, :func:`_backend.iddp_asvd`,
+        :func:`_backend.iddp_rsvd`, :func:`_backend.iddr_svd`,
+        :func:`_backend.iddr_asvd`, :func:`_backend.iddr_rsvd`,
+        :func:`_backend.idzp_svd`, :func:`_backend.idzp_asvd`,
+        :func:`_backend.idzp_rsvd`, :func:`_backend.idzr_svd`,
+        :func:`_backend.idzr_asvd`, and :func:`_backend.idzr_rsvd`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix to be factored, given as either a :class:`numpy.ndarray` or a
+        :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and
+        `rmatvec` methods (to apply the matrix and its adjoint).
+    eps_or_k : float or int
+        Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of
+        approximation.
+    rand : bool, optional
+        Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
+        (randomized algorithms are always used if `A` is of type
+        :class:`scipy.sparse.linalg.LinearOperator`).
+    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``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    U : :class:`numpy.ndarray`
+        2D array of left singular vectors.
+    S : :class:`numpy.ndarray`
+        1D array of singular values.
+    V : :class:`numpy.ndarray`
+        2D array right singular vectors.
+    """
+    from scipy.sparse.linalg import LinearOperator
+    rng = np.random.default_rng(rng)
+
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if rand:
+                if real:
+                    U, S, V = _backend.iddp_asvd(A, eps, rng=rng)
+                else:
+                    U, S, V = _backend.idzp_asvd(A, eps, rng=rng)
+            else:
+                if real:
+                    U, S, V = _backend.iddp_svd(A, eps)
+                    V = V.T.conj()
+                else:
+                    U, S, V = _backend.idzp_svd(A, eps)
+                    V = V.T.conj()
+        else:
+            k = int(eps_or_k)
+            if k > min(A.shape):
+                raise ValueError(f"Approximation rank {k} exceeds min(A.shape) = "
+                                 f" {min(A.shape)} ")
+            if rand:
+                if real:
+                    U, S, V = _backend.iddr_asvd(A, k, rng=rng)
+                else:
+                    U, S, V = _backend.idzr_asvd(A, k, rng=rng)
+            else:
+                if real:
+                    U, S, V = _backend.iddr_svd(A, k)
+                    V = V.T.conj()
+                else:
+                    U, S, V = _backend.idzr_svd(A, k)
+                    V = V.T.conj()
+    elif isinstance(A, LinearOperator):
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if real:
+                U, S, V = _backend.iddp_rsvd(A, eps, rng=rng)
+            else:
+                U, S, V = _backend.idzp_rsvd(A, eps, rng=rng)
+        else:
+            k = int(eps_or_k)
+            if real:
+                U, S, V = _backend.iddr_rsvd(A, k, rng=rng)
+            else:
+                U, S, V = _backend.idzr_rsvd(A, k, rng=rng)
+    else:
+        raise _TYPE_ERROR
+    return U, S, V
+
+
+def estimate_rank(A, eps, rng=None):
+    """
+    Estimate matrix rank to a specified relative precision using randomized
+    methods.
+
+    The matrix `A` can be given as either a :class:`numpy.ndarray` or a
+    :class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used
+    for each case. If `A` is of type :class:`numpy.ndarray`, then the output
+    rank is typically about 8 higher than the actual numerical rank.
+
+    ..  This function automatically detects the form of the input parameters and
+        passes them to the appropriate backend. For details,
+        see :func:`_backend.idd_estrank`, :func:`_backend.idd_findrank`,
+        :func:`_backend.idz_estrank`, and :func:`_backend.idz_findrank`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix whose rank is to be estimated, given as either a
+        :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator`
+        with the `rmatvec` method (to apply the matrix adjoint).
+    eps : float
+        Relative error for numerical rank definition.
+    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``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    int
+        Estimated matrix rank.
+    """
+    from scipy.sparse.linalg import LinearOperator
+
+    rng = np.random.default_rng(rng)
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if real:
+            rank, _ = _backend.idd_estrank(A, eps, rng=rng)
+        else:
+            rank, _ = _backend.idz_estrank(A, eps, rng=rng)
+        if rank == 0:
+            # special return value for nearly full rank
+            rank = min(A.shape)
+        return rank
+    elif isinstance(A, LinearOperator):
+        if real:
+            return _backend.idd_findrank(A, eps, rng=rng)[0]
+        else:
+            return _backend.idz_findrank(A, eps, rng=rng)[0]
+    else:
+        raise _TYPE_ERROR
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/lapack.py b/venv/lib/python3.10/site-packages/scipy/linalg/lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d15cf4d72d19f4b7949cd80bc77aa31553841c1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/lapack.py
@@ -0,0 +1,1061 @@
+"""
+Low-level LAPACK functions (:mod:`scipy.linalg.lapack`)
+=======================================================
+
+This module contains low-level functions from the LAPACK library.
+
+.. versionadded:: 0.12.0
+
+.. note::
+
+    The common ``overwrite_<>`` option in many routines, allows the
+    input arrays to be overwritten to avoid extra memory allocation.
+    However this requires the array to satisfy two conditions
+    which are memory order and the data type to match exactly the
+    order and the type expected by the routine.
+
+    As an example, if you pass a double precision float array to any
+    ``S....`` routine which expects single precision arguments, f2py
+    will create an intermediate array to match the argument types and
+    overwriting will be performed on that intermediate array.
+
+    Similarly, if a C-contiguous array is passed, f2py will pass a
+    FORTRAN-contiguous array internally. Please make sure that these
+    details are satisfied. More information can be found in the f2py
+    documentation.
+
+.. warning::
+
+   These functions do little to no error checking.
+   It is possible to cause crashes by mis-using them,
+   so prefer using the higher-level routines in `scipy.linalg`.
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_lapack_funcs
+
+All functions
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbsv
+   dgbsv
+   cgbsv
+   zgbsv
+
+   sgbtrf
+   dgbtrf
+   cgbtrf
+   zgbtrf
+
+   sgbtrs
+   dgbtrs
+   cgbtrs
+   zgbtrs
+
+   sgebal
+   dgebal
+   cgebal
+   zgebal
+
+   sgecon
+   dgecon
+   cgecon
+   zgecon
+
+   sgeequ
+   dgeequ
+   cgeequ
+   zgeequ
+
+   sgeequb
+   dgeequb
+   cgeequb
+   zgeequb
+
+   sgees
+   dgees
+   cgees
+   zgees
+
+   sgeev
+   dgeev
+   cgeev
+   zgeev
+
+   sgeev_lwork
+   dgeev_lwork
+   cgeev_lwork
+   zgeev_lwork
+
+   sgehrd
+   dgehrd
+   cgehrd
+   zgehrd
+
+   sgehrd_lwork
+   dgehrd_lwork
+   cgehrd_lwork
+   zgehrd_lwork
+
+   sgejsv
+   dgejsv
+
+   sgels
+   dgels
+   cgels
+   zgels
+
+   sgels_lwork
+   dgels_lwork
+   cgels_lwork
+   zgels_lwork
+
+   sgelsd
+   dgelsd
+   cgelsd
+   zgelsd
+
+   sgelsd_lwork
+   dgelsd_lwork
+   cgelsd_lwork
+   zgelsd_lwork
+
+   sgelss
+   dgelss
+   cgelss
+   zgelss
+
+   sgelss_lwork
+   dgelss_lwork
+   cgelss_lwork
+   zgelss_lwork
+
+   sgelsy
+   dgelsy
+   cgelsy
+   zgelsy
+
+   sgelsy_lwork
+   dgelsy_lwork
+   cgelsy_lwork
+   zgelsy_lwork
+
+   sgeqp3
+   dgeqp3
+   cgeqp3
+   zgeqp3
+
+   sgeqrf
+   dgeqrf
+   cgeqrf
+   zgeqrf
+
+   sgeqrf_lwork
+   dgeqrf_lwork
+   cgeqrf_lwork
+   zgeqrf_lwork
+
+   sgeqrfp
+   dgeqrfp
+   cgeqrfp
+   zgeqrfp
+
+   sgeqrfp_lwork
+   dgeqrfp_lwork
+   cgeqrfp_lwork
+   zgeqrfp_lwork
+
+   sgerqf
+   dgerqf
+   cgerqf
+   zgerqf
+
+   sgesdd
+   dgesdd
+   cgesdd
+   zgesdd
+
+   sgesdd_lwork
+   dgesdd_lwork
+   cgesdd_lwork
+   zgesdd_lwork
+
+   sgesv
+   dgesv
+   cgesv
+   zgesv
+
+   sgesvd
+   dgesvd
+   cgesvd
+   zgesvd
+
+   sgesvd_lwork
+   dgesvd_lwork
+   cgesvd_lwork
+   zgesvd_lwork
+
+   sgesvx
+   dgesvx
+   cgesvx
+   zgesvx
+
+   sgetrf
+   dgetrf
+   cgetrf
+   zgetrf
+
+   sgetc2
+   dgetc2
+   cgetc2
+   zgetc2
+
+   sgetri
+   dgetri
+   cgetri
+   zgetri
+
+   sgetri_lwork
+   dgetri_lwork
+   cgetri_lwork
+   zgetri_lwork
+
+   sgetrs
+   dgetrs
+   cgetrs
+   zgetrs
+
+   sgesc2
+   dgesc2
+   cgesc2
+   zgesc2
+
+   sgges
+   dgges
+   cgges
+   zgges
+
+   sggev
+   dggev
+   cggev
+   zggev
+
+   sgglse
+   dgglse
+   cgglse
+   zgglse
+
+   sgglse_lwork
+   dgglse_lwork
+   cgglse_lwork
+   zgglse_lwork
+
+   sgtsv
+   dgtsv
+   cgtsv
+   zgtsv
+
+   sgtsvx
+   dgtsvx
+   cgtsvx
+   zgtsvx
+
+   chbevd
+   zhbevd
+
+   chbevx
+   zhbevx
+
+   checon
+   zhecon
+
+   cheequb
+   zheequb
+
+   cheev
+   zheev
+
+   cheev_lwork
+   zheev_lwork
+
+   cheevd
+   zheevd
+
+   cheevd_lwork
+   zheevd_lwork
+
+   cheevr
+   zheevr
+
+   cheevr_lwork
+   zheevr_lwork
+
+   cheevx
+   zheevx
+
+   cheevx_lwork
+   zheevx_lwork
+
+   chegst
+   zhegst
+
+   chegv
+   zhegv
+
+   chegv_lwork
+   zhegv_lwork
+
+   chegvd
+   zhegvd
+
+   chegvx
+   zhegvx
+
+   chegvx_lwork
+   zhegvx_lwork
+
+   chesv
+   zhesv
+
+   chesv_lwork
+   zhesv_lwork
+
+   chesvx
+   zhesvx
+
+   chesvx_lwork
+   zhesvx_lwork
+
+   chetrd
+   zhetrd
+
+   chetrd_lwork
+   zhetrd_lwork
+
+   chetrf
+   zhetrf
+
+   chetrf_lwork
+   zhetrf_lwork
+
+   chetrs
+   zhetrs
+
+   chfrk
+   zhfrk
+
+   slamch
+   dlamch
+
+   slange
+   dlange
+   clange
+   zlange
+
+   slantr
+   dlantr
+   clantr
+   zlantr
+
+   slarf
+   dlarf
+   clarf
+   zlarf
+
+   slarfg
+   dlarfg
+   clarfg
+   zlarfg
+
+   slartg
+   dlartg
+   clartg
+   zlartg
+
+   slasd4
+   dlasd4
+
+   slaswp
+   dlaswp
+   claswp
+   zlaswp
+
+   slauum
+   dlauum
+   clauum
+   zlauum
+
+   sorcsd
+   dorcsd
+   sorcsd_lwork
+   dorcsd_lwork
+
+   sorghr
+   dorghr
+   sorghr_lwork
+   dorghr_lwork
+
+   sorgqr
+   dorgqr
+
+   sorgrq
+   dorgrq
+
+   sormqr
+   dormqr
+
+   sormrz
+   dormrz
+
+   sormrz_lwork
+   dormrz_lwork
+
+   spbsv
+   dpbsv
+   cpbsv
+   zpbsv
+
+   spbtrf
+   dpbtrf
+   cpbtrf
+   zpbtrf
+
+   spbtrs
+   dpbtrs
+   cpbtrs
+   zpbtrs
+
+   spftrf
+   dpftrf
+   cpftrf
+   zpftrf
+
+   spftri
+   dpftri
+   cpftri
+   zpftri
+
+   spftrs
+   dpftrs
+   cpftrs
+   zpftrs
+
+   spocon
+   dpocon
+   cpocon
+   zpocon
+
+   spstrf
+   dpstrf
+   cpstrf
+   zpstrf
+
+   spstf2
+   dpstf2
+   cpstf2
+   zpstf2
+
+   sposv
+   dposv
+   cposv
+   zposv
+
+   sposvx
+   dposvx
+   cposvx
+   zposvx
+
+   spotrf
+   dpotrf
+   cpotrf
+   zpotrf
+
+   spotri
+   dpotri
+   cpotri
+   zpotri
+
+   spotrs
+   dpotrs
+   cpotrs
+   zpotrs
+
+   sppcon
+   dppcon
+   cppcon
+   zppcon
+
+   sppsv
+   dppsv
+   cppsv
+   zppsv
+
+   spptrf
+   dpptrf
+   cpptrf
+   zpptrf
+
+   spptri
+   dpptri
+   cpptri
+   zpptri
+
+   spptrs
+   dpptrs
+   cpptrs
+   zpptrs
+
+   sptsv
+   dptsv
+   cptsv
+   zptsv
+
+   sptsvx
+   dptsvx
+   cptsvx
+   zptsvx
+
+   spttrf
+   dpttrf
+   cpttrf
+   zpttrf
+
+   spttrs
+   dpttrs
+   cpttrs
+   zpttrs
+
+   spteqr
+   dpteqr
+   cpteqr
+   zpteqr
+
+   crot
+   zrot
+
+   ssbev
+   dsbev
+
+   ssbevd
+   dsbevd
+
+   ssbevx
+   dsbevx
+
+   ssfrk
+   dsfrk
+
+   sstebz
+   dstebz
+
+   sstein
+   dstein
+
+   sstemr
+   dstemr
+
+   sstemr_lwork
+   dstemr_lwork
+
+   ssterf
+   dsterf
+
+   sstev
+   dstev
+
+   ssycon
+   dsycon
+   csycon
+   zsycon
+
+   ssyconv
+   dsyconv
+   csyconv
+   zsyconv
+
+   ssyequb
+   dsyequb
+   csyequb
+   zsyequb
+
+   ssyev
+   dsyev
+
+   ssyev_lwork
+   dsyev_lwork
+
+   ssyevd
+   dsyevd
+
+   ssyevd_lwork
+   dsyevd_lwork
+
+   ssyevr
+   dsyevr
+
+   ssyevr_lwork
+   dsyevr_lwork
+
+   ssyevx
+   dsyevx
+
+   ssyevx_lwork
+   dsyevx_lwork
+
+   ssygst
+   dsygst
+
+   ssygv
+   dsygv
+
+   ssygv_lwork
+   dsygv_lwork
+
+   ssygvd
+   dsygvd
+
+   ssygvx
+   dsygvx
+
+   ssygvx_lwork
+   dsygvx_lwork
+
+   ssysv
+   dsysv
+   csysv
+   zsysv
+
+   ssysv_lwork
+   dsysv_lwork
+   csysv_lwork
+   zsysv_lwork
+
+   ssysvx
+   dsysvx
+   csysvx
+   zsysvx
+
+   ssysvx_lwork
+   dsysvx_lwork
+   csysvx_lwork
+   zsysvx_lwork
+
+   ssytf2
+   dsytf2
+   csytf2
+   zsytf2
+
+   ssytrd
+   dsytrd
+
+   ssytrd_lwork
+   dsytrd_lwork
+
+   ssytrf
+   dsytrf
+   csytrf
+   zsytrf
+
+   ssytrf_lwork
+   dsytrf_lwork
+   csytrf_lwork
+   zsytrf_lwork
+
+   ssytrs
+   dsytrs
+   csytrs
+   zsytrs
+
+   stbtrs
+   dtbtrs
+   ctbtrs
+   ztbtrs
+
+   stfsm
+   dtfsm
+   ctfsm
+   ztfsm
+
+   stfttp
+   dtfttp
+   ctfttp
+   ztfttp
+
+   stfttr
+   dtfttr
+   ctfttr
+   ztfttr
+
+   stgexc
+   dtgexc
+   ctgexc
+   ztgexc
+
+   stgsen
+   dtgsen
+   ctgsen
+   ztgsen
+
+   stgsen_lwork
+   dtgsen_lwork
+   ctgsen_lwork
+   ztgsen_lwork
+
+   stgsyl
+   dtgsyl
+
+   stpttf
+   dtpttf
+   ctpttf
+   ztpttf
+
+   stpttr
+   dtpttr
+   ctpttr
+   ztpttr
+
+   strcon
+   dtrcon
+   ctrcon
+   ztrcon
+
+   strexc
+   dtrexc
+   ctrexc
+   ztrexc
+
+   strsen
+   dtrsen
+   ctrsen
+   ztrsen
+
+   strsen_lwork
+   dtrsen_lwork
+   ctrsen_lwork
+   ztrsen_lwork
+
+   strsyl
+   dtrsyl
+   ctrsyl
+   ztrsyl
+
+   strtri
+   dtrtri
+   ctrtri
+   ztrtri
+
+   strtrs
+   dtrtrs
+   ctrtrs
+   ztrtrs
+
+   strttf
+   dtrttf
+   ctrttf
+   ztrttf
+
+   strttp
+   dtrttp
+   ctrttp
+   ztrttp
+
+   stzrzf
+   dtzrzf
+   ctzrzf
+   ztzrzf
+
+   stzrzf_lwork
+   dtzrzf_lwork
+   ctzrzf_lwork
+   ztzrzf_lwork
+
+   cunghr
+   zunghr
+
+   cunghr_lwork
+   zunghr_lwork
+
+   cungqr
+   zungqr
+
+   cungrq
+   zungrq
+
+   cunmqr
+   zunmqr
+
+   sgeqrt
+   dgeqrt
+   cgeqrt
+   zgeqrt
+
+   sgemqrt
+   dgemqrt
+   cgemqrt
+   zgemqrt
+
+   sgttrf
+   dgttrf
+   cgttrf
+   zgttrf
+
+   sgttrs
+   dgttrs
+   cgttrs
+   zgttrs
+
+   sgtcon
+   dgtcon
+   cgtcon
+   zgtcon
+
+   stpqrt
+   dtpqrt
+   ctpqrt
+   ztpqrt
+
+   stpmqrt
+   dtpmqrt
+   ctpmqrt
+   ztpmqrt
+
+   cuncsd
+   zuncsd
+
+   cuncsd_lwork
+   zuncsd_lwork
+
+   cunmrz
+   zunmrz
+
+   cunmrz_lwork
+   zunmrz_lwork
+
+   ilaver
+
+"""
+#
+# Author: Pearu Peterson, March 2002
+#
+
+import numpy as np
+from .blas import _get_funcs, _memoize_get_funcs
+from scipy.linalg import _flapack
+from re import compile as regex_compile
+try:
+    from scipy.linalg import _clapack
+except ImportError:
+    _clapack = None
+
+try:
+    from scipy.linalg import _flapack_64
+    HAS_ILP64 = True
+except ImportError:
+    HAS_ILP64 = False
+    _flapack_64 = None
+
+
+# Expose all functions (only flapack --- clapack is an implementation detail)
+empty_module = None
+from scipy.linalg._flapack import *  # noqa: E402, F403
+del empty_module
+
+__all__ = ['get_lapack_funcs']
+
+# some convenience alias for complex functions
+_lapack_alias = {
+    'corghr': 'cunghr', 'zorghr': 'zunghr',
+    'corghr_lwork': 'cunghr_lwork', 'zorghr_lwork': 'zunghr_lwork',
+    'corgqr': 'cungqr', 'zorgqr': 'zungqr',
+    'cormqr': 'cunmqr', 'zormqr': 'zunmqr',
+    'corgrq': 'cungrq', 'zorgrq': 'zungrq',
+}
+
+
+# Place guards against docstring rendering issues with special characters
+p1 = regex_compile(r'with bounds (?P.*?)( and (?P.*?) storage){0,1}\n')
+p2 = regex_compile(r'Default: (?P.*?)\n')
+
+
+def backtickrepl(m):
+    if m.group('s'):
+        return (f"with bounds ``{m.group('b')}`` with ``{m.group('s')}`` storage\n")
+    else:
+        return f"with bounds ``{m.group('b')}``\n"
+
+
+for routine in [ssyevr, dsyevr, cheevr, zheevr,
+                ssyevx, dsyevx, cheevx, zheevx,
+                ssygvd, dsygvd, chegvd, zhegvd]:
+    if routine.__doc__:
+        routine.__doc__ = p1.sub(backtickrepl, routine.__doc__)
+        routine.__doc__ = p2.sub('Default ``\\1``\n', routine.__doc__)
+    else:
+        continue
+
+del regex_compile, p1, p2, backtickrepl
+
+
+@_memoize_get_funcs
+def get_lapack_funcs(names, arrays=(), dtype=None, ilp64=False):
+    """Return available LAPACK function objects from names.
+
+    Arrays are used to determine the optimal prefix of LAPACK routines.
+
+    Parameters
+    ----------
+    names : str or sequence of str
+        Name(s) of LAPACK functions without type prefix.
+
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of LAPACK
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    ilp64 : {True, False, 'preferred'}, optional
+        Whether to return ILP64 routine variant.
+        Choosing 'preferred' returns ILP64 routine if available, and
+        otherwise the 32-bit routine. Default: False
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+    Notes
+    -----
+    This routine automatically chooses between Fortran/C
+    interfaces. Fortran code is used whenever possible for arrays with
+    column major order. In all other cases, C code is preferred.
+
+    In LAPACK, the naming convention is that all functions start with a
+    type prefix, which depends on the type of the principal
+    matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy
+    types {float32, float64, complex64, complex128} respectively, and
+    are stored in attribute ``typecode`` of the returned functions.
+
+    Examples
+    --------
+    Suppose we would like to use '?lange' routine which computes the selected
+    norm of an array. We pass our array in order to get the correct 'lange'
+    flavor.
+
+    >>> import numpy as np
+    >>> import scipy.linalg as LA
+    >>> rng = np.random.default_rng()
+
+    >>> a = rng.random((3,2))
+    >>> x_lange = LA.get_lapack_funcs('lange', (a,))
+    >>> x_lange.typecode
+    'd'
+    >>> x_lange = LA.get_lapack_funcs('lange',(a*1j,))
+    >>> x_lange.typecode
+    'z'
+
+    Several LAPACK routines work best when its internal WORK array has
+    the optimal size (big enough for fast computation and small enough to
+    avoid waste of memory). This size is determined also by a dedicated query
+    to the function which is often wrapped as a standalone function and
+    commonly denoted as ``###_lwork``. Below is an example for ``?sysv``
+
+    >>> a = rng.random((1000, 1000))
+    >>> b = rng.random((1000, 1)) * 1j
+    >>> # We pick up zsysv and zsysv_lwork due to b array
+    ... xsysv, xlwork = LA.get_lapack_funcs(('sysv', 'sysv_lwork'), (a, b))
+    >>> opt_lwork, _ = xlwork(a.shape[0])  # returns a complex for 'z' prefix
+    >>> udut, ipiv, x, info = xsysv(a, b, lwork=int(opt_lwork.real))
+
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError("Invalid value for 'ilp64'")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack, _clapack,
+                          "flapack", "clapack", _lapack_alias,
+                          ilp64=False)
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("LAPACK ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit BLAS")
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack_64, None,
+                          "flapack_64", None, _lapack_alias,
+                          ilp64=True)
+
+
+_int32_max = np.iinfo(np.int32).max
+_int64_max = np.iinfo(np.int64).max
+
+
+def _compute_lwork(routine, *args, **kwargs):
+    """
+    Round floating-point lwork returned by lapack to integer.
+
+    Several LAPACK routines compute optimal values for LWORK, which
+    they return in a floating-point variable. However, for large
+    values of LWORK, single-precision floating point is not sufficient
+    to hold the exact value --- some LAPACK versions (<= 3.5.0 at
+    least) truncate the returned integer to single precision and in
+    some cases this can be smaller than the required value.
+
+    Examples
+    --------
+    >>> from scipy.linalg import lapack
+    >>> n = 5000
+    >>> s_r, s_lw = lapack.get_lapack_funcs(('sysvx', 'sysvx_lwork'))
+    >>> lwork = lapack._compute_lwork(s_lw, n)
+    >>> lwork
+    32000
+
+    """
+    dtype = getattr(routine, 'dtype', None)
+    int_dtype = getattr(routine, 'int_dtype', None)
+    ret = routine(*args, **kwargs)
+    if ret[-1] != 0:
+        raise ValueError("Internal work array size computation failed: "
+                         "%d" % (ret[-1],))
+
+    if len(ret) == 2:
+        return _check_work_float(ret[0].real, dtype, int_dtype)
+    else:
+        return tuple(_check_work_float(x.real, dtype, int_dtype)
+                     for x in ret[:-1])
+
+
+def _check_work_float(value, dtype, int_dtype):
+    """
+    Convert LAPACK-returned work array size float to integer,
+    carefully for single-precision types.
+    """
+
+    if dtype == np.float32 or dtype == np.complex64:
+        # Single-precision routine -- take next fp value to work
+        # around possible truncation in LAPACK code
+        value = np.nextafter(value, np.inf, dtype=np.float32)
+
+    value = int(value)
+    if int_dtype.itemsize == 4:
+        if value < 0 or value > _int32_max:
+            raise ValueError("Too large work array required -- computation "
+                             "cannot be performed with standard 32-bit"
+                             " LAPACK.")
+    elif int_dtype.itemsize == 8:
+        if value < 0 or value > _int64_max:
+            raise ValueError("Too large work array required -- computation"
+                             " cannot be performed with standard 64-bit"
+                             " LAPACK.")
+    return value
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py b/venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ec8123b3ad8df096d5791c29bb28cce8271d4ad
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm',
+    'tanhm', 'logm', 'funm', 'signm', 'sqrtm',
+    'expm_frechet', 'expm_cond', 'fractional_matrix_power',
+    'khatri_rao', 'norm', 'solve', 'inv', 'svd', 'schur', 'rsf2csf'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="matfuncs",
+                                   private_modules=["_matfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/misc.py b/venv/lib/python3.10/site-packages/scipy/linalg/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fad087489c6a24c8e33df54b811b6c37a3a46d4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/misc.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'LinAlgError', 'LinAlgWarning', 'norm', 'get_blas_funcs',
+    'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="misc",
+                                   private_modules=["_misc"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py b/venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..a881ce765dfa3a3c4c2853c405f8129aafc615b5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.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.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'toeplitz', 'circulant', 'hankel',
+    'hadamard', 'leslie', 'kron', 'block_diag', 'companion',
+    'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+    'fiedler', 'fiedler_companion', 'convolution_matrix'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="special_matrices",
+                                   private_modules=["_special_matrices"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d17ef52b5d4bb0369003f021594c922d7ba8795
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9377174be6332abd0c1266530d7ce626db04b74
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cae5c9efd38cfd94aac3848403c3db0e6a8d9da5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f63298c9fdb67790ed2b6fc9032a0fff579340b7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b50ccf4233efd17fc6a8046ebaa5a5be8ab3896
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6980b04f69098a39e3228cb75df7a0bd4daaf2cb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..705483b844ffff4fef3758e8f132f27ada5653eb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1c4f93fa72730974307403eb5d98ae25f25f081
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3dd23eb8392fca86722257039f6d67e5f13ce4f9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fcf3e580dfa7c14a615c97d56bdb37e556dd577
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46ba6bde5faab04c35b71bead06d42129032dddf
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36befa1c7f883d78af81e5bebd72e239d79e96a7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bdced5e102eadaa33facaa44514e63089891c5b4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_extending.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_extending.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..14fd0ddc2dcd8933d960c06c2a9fb2e9d36fa66f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_extending.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..386939143e6a0f3b8cfe7f8346f03a762419fcbb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e48582de5450d386e6c713d3c189121406e6117
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2856ea8af84911949a3000427a27b09885346656
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7e6adaf896d2cd0172246cf04e1834095cd8d16
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..026c1961559b749bea513f4fcfa30e51362ca143
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..feb8258005a8132d947d527720b2f8142ba6287d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f98b4537cd7f16221c9757556f144f9f8f01589f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8e4a3ecfdd877afb42629aba495eb091908f8c0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..433fc79e96425c9b6d65f8f2f4bc8bafdc6d3e12
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cbaabd938c78a6c6d1be89fecf443e66c17b421
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx b/venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..3954d08791cceb3a2b66669fe3c0ec4180089208
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+
+cimport scipy.linalg
+from scipy.linalg.cython_blas cimport cdotu
+from scipy.linalg.cython_lapack cimport dgtsv
+
+cpdef tridiag(double[:] a, double[:] b, double[:] c, double[:] x):
+    """ Solve the system A y = x for y where A is the tridiagonal matrix with
+    subdiagonal 'a', diagonal 'b', and superdiagonal 'c'. """
+    cdef int n=b.shape[0], nrhs=1, info
+    # Solution is written over the values in x.
+    dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info)
+
+cpdef float complex complex_dot(float complex[:] cx, float complex[:] cy):
+    """ Take dot product of two complex vectors """
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build b/venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..88f23170ac0bbe382d8470bd22a42a92d9473008
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build
@@ -0,0 +1,27 @@
+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.0.8')
+  error('tests requires Cython >= 3.0.8')
+endif
+
+py3.extension_module(
+  'extending',
+  'extending.pyx',
+  install: false,
+  c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+  'extending_cpp',
+  extending_cpp,
+  install: false,
+  override_options : ['cython_language=cpp'],
+  cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe51dcc21824ae122a17376940d43e34ec9ac22c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py
@@ -0,0 +1,2059 @@
+import itertools
+
+import numpy as np
+from numpy import (arange, array, dot, zeros, identity, conjugate, transpose,
+                   float32)
+from numpy.random import random
+
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_array_almost_equal, assert_allclose,
+                           assert_array_equal, suppress_warnings)
+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
+
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+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.thread_unsafe  # due to Cython fused types, see cython#6506
+    @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 setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.thread_unsafe
+    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):
+        n = 2
+        A = random([n, n])+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):
+
+        n = 20
+        a = random([n, n])
+        for i in range(n):
+            a[i, i] = 20*(.1+a[i, i])
+        for i in range(4):
+            b = random([n, 3])
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_complex(self):
+        n = 20
+        a = random([n, n]) + 1j * random([n, n])
+        for i in range(n):
+            a[i, i] = 20*(.1+a[i, i])
+        for i in range(2):
+            b = random([n, 3])
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_sym(self):
+        n = 20
+        a = 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 = random([n])
+            x = solve(a, b, assume_a="pos")
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_sym_complex(self):
+        n = 20
+        a = random([n, n])
+        a = a + 1j*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 = random([n])+2j*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]]))
+
+    def test_hermitian(self):
+        # An upper triangular matrix will be used for 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]])
+        res = np.array([[2.+1j, -8+6j],
+                        [3.-2j, 7-2j],
+                        [-1+2j, -1+5j],
+                        [1.-1j, 3-4j]])
+        x = solve(a, b, assume_a='her')
+        assert_array_almost_equal(x, res)
+        # Also conjugate a and test for lower triangular data
+        x = solve(a.conj().T, b, assume_a='her', lower=True)
+        assert_array_almost_equal(x, res)
+
+    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.thread_unsafe
+    @pytest.mark.parametrize('structure',
+                             ('diagonal', 'tridiagonal', 'lower triangular',
+                              'upper triangular', 'symmetric', 'hermitian',
+                              'positive definite', 'general', 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..."
+        with pytest.warns(LinAlgWarning, match=message):
+            solve(A, b, assume_a=structure)
+
+    def test_multiple_rhs(self):
+        a = np.eye(2)
+        b = np.random.rand(2, 3, 4)
+        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])
+
+    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.skip(reason="Failure on OS X (gh-7500), "
+                             "crash on Windows (gh-8064)")
+    def test_all_type_size_routine_combinations(self):
+        sizes = [10, 100]
+        assume_as = ['gen', 'sym', 'pos', 'her']
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+        for size, assume_a, dtype in itertools.product(sizes, assume_as,
+                                                       dtypes):
+            is_complex = dtype in (np.complex64, np.complex128)
+            if assume_a == 'her' and not is_complex:
+                continue
+
+            err_msg = (f"Failed for size: {size}, assume_a: {assume_a},"
+                       f"dtype: {dtype}")
+
+            a = np.random.randn(size, size).astype(dtype)
+            b = np.random.randn(size).astype(dtype)
+            if is_complex:
+                a = a + (1j*np.random.randn(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.conj().T.dot(a) + 0.1*np.eye(size)
+
+            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.dot(x), b,
+                            atol=tol * size,
+                            rtol=tol * size,
+                            err_msg=err_msg)
+
+            if assume_a == 'sym' and dtype not in (np.complex64,
+                                                   np.complex128):
+                x = solve(a, b, assume_a=assume_a, transposed=True)
+                assert_allclose(a.dot(x), b,
+                                atol=tol * size,
+                                rtol=tol * size,
+                                err_msg=err_msg)
+
+    @pytest.mark.thread_unsafe
+    @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
+
+    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])
+    # "pos" and "positive definite" need to be added
+    @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded',
+                                          'lower triangular', 'upper triangular',
+                                          '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
+            A += np.diag(A.sum(axis=1))
+
+        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_equal(solve(A_copy, b_copy, transposed=transposed), res)
+
+        # Check that overwrite was respected
+        if not overwrite:
+            assert_equal(A, A_copy)
+            assert_equal(b, b_copy)
+
+
+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 setup_method(self):
+        np.random.seed(1234)
+
+    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):
+        n = 20
+        for i in range(4):
+            a = 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):
+        n = 20
+        for i in range(4):
+            a = random([n, n])+2j*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
+
+
+class TestDet:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1680305949878959)
+
+    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):
+        a = self.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 = self.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):
+        a = self.rng.uniform(-1., 1., size=shape)
+        d1, d2 = det(a), np.linalg.det(a)
+        assert_allclose(d1, d2)
+
+        b = self.rng.uniform(-1., 1., size=shape)*1j
+        b += self.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'])
+    def test_sample_compatible_dtype_input(self, typ):
+        n = 4
+        a = self.rng.random([n, n]).astype(typ)  # value is not important
+        assert isinstance(det(a), (np.float64 | np.complex128))
+
+    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)
+
+
+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}")
+
+    @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 suppress_warnings() as sup:
+            # On (some) OSX this tests triggers a warning (gh-7538)
+            sup.filter(RuntimeWarning,
+                       "internal gelsd driver lwork query error,.*"
+                       "Falling back to 'gelss' driver.")
+
+        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
+
+
+class TestPinv:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    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):
+        n = 12
+        # get a random ortho matrix for shuffling
+        q, _ = qr(np.random.rand(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=5.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 setup_method(self):
+        np.random.seed(1234)
+
+    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):
+        n = 12
+        # get a random ortho matrix for shuffling
+        q, _ = qr(np.random.rand(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:
+
+    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.
+        np.random.seed(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 * np.random.randn(n, m).astype(t)
+                if np.issubdtype(A.dtype, np.complexfloating):
+                    A = (A + 10j * np.random.randn(n, m)).astype(t)
+                    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)
+        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.randn(50)
+        b = rng.randn(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:
+
+    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
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6645d0ad5d967ca00a2a5193d51e7ee74b8ad73
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
@@ -0,0 +1,1127 @@
+#
+# Created by: Pearu Peterson, April 2002
+#
+
+import math
+import pytest
+import numpy as np
+import numpy.random
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from numpy import float32, float64, complex64, complex128, arange, triu, \
+                  tril, zeros, tril_indices, ones, mod, diag, append, eye, \
+                  nonzero
+
+import scipy
+from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve
+
+try:
+    from scipy.linalg import _cblas as cblas
+except ImportError:
+    cblas = None
+
+REAL_DTYPES = [float32, float64]
+COMPLEX_DTYPES = [complex64, 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')
+    if cblas is not None:
+        assert_equal(f1.module_name, 'cblas')
+        assert_equal(f2.module_name, 'cblas')
+
+    # 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_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
+
+
+class TestCBLAS1Simple:
+
+    def test_axpy(self):
+        for p in 'sd':
+            f = getattr(cblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+                                      [7, 9, 18])
+        for p in 'cz':
+            f = getattr(cblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+                                      [7, 10j-1, 18])
+
+
+class TestFBLAS1Simple:
+
+    def test_axpy(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+                                      [7, 9, 18])
+        for p in 'cz':
+            f = getattr(fblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+                                      [7, 10j-1, 18])
+
+    def test_copy(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'copy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
+        for p in 'cz':
+            f = getattr(fblas, p+'copy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
+
+    def test_asum(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'asum', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5]), 12)
+        for p in ['sc', 'dz']:
+            f = getattr(fblas, p+'asum', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j]), 14)
+
+    def test_dot(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'dot', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
+
+    def test_complex_dotu(self):
+        for p in 'cz':
+            f = getattr(fblas, p+'dotu', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
+
+    def test_complex_dotc(self):
+        for p in 'cz':
+            f = getattr(fblas, p+'dotc', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
+
+    def test_nrm2(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'nrm2', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
+        for p in ['c', 'z', 'sc', 'dz']:
+            f = getattr(fblas, p+'nrm2', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
+
+    def test_scal(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
+        for p in 'cz':
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j])
+        for p in ['cs', 'zd']:
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
+
+    def test_swap(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'swap', None)
+            if f is None:
+                continue
+            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)
+        for p in 'cz':
+            f = getattr(fblas, p+'swap', None)
+            if f is None:
+                continue
+            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)
+
+    def test_amax(self):
+        for p in 'sd':
+            f = getattr(fblas, 'i'+p+'amax')
+            assert_equal(f([-2, 4, 3]), 1)
+        for p in 'cz':
+            f = getattr(fblas, 'i'+p+'amax')
+            assert_equal(f([-5, 4+3j, 6]), 1)
+    # XXX: need tests for rot,rotm,rotg,rotmg
+
+
+class TestFBLAS2Simple:
+
+    def test_gemv(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'gemv', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
+            assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
+        for p in 'cz':
+            f = getattr(fblas, p+'gemv', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
+            assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
+                                      [-48-21j])
+
+    # All of these *ger* functions are segfaulting when called from multiple
+    # threads under free-threaded CPython, see gh-21936.
+    @pytest.mark.thread_unsafe
+    def test_ger(self):
+
+        for p in 'sd':
+            f = getattr(fblas, p+'ger', None)
+            if f is None:
+                continue
+            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]])
+
+        for p in 'cz':
+            f = getattr(fblas, p+'geru', None)
+            if f is None:
+                continue
+            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]])
+
+        for p in 'cz':
+            for name in ('ger', 'gerc'):
+                f = getattr(fblas, p+name, None)
+                if f is None:
+                    continue
+                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]])
+
+    def test_syr_her(self):
+        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])
+        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()
+
+        for p, rtol in zip('sd', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr', None)
+            if f is None:
+                continue
+            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)
+
+            a = np.zeros((4, 4), 'f' if p == 's' else 'd', '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'))
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr', None)
+            if f is None:
+                continue
+            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), 'F' if p == 'c' else 'D', '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)
+
+            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'))
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'her', None)
+            if f is None:
+                continue
+            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), 'F' if p == 'c' else 'D', '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'))
+
+    def test_syr2(self):
+        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)
+
+        for p, rtol in zip('sd', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr2', None)
+            if f is None:
+                continue
+            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), 'f' if p == 's' else 'd', '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'))
+
+    def test_her2(self):
+        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()
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'her2', None)
+            if f is None:
+                continue
+            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), 'F' if p == 'c' else 'D', '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'))
+
+    def test_gbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            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, = get_blas_funcs(('gbmv',), dtype=dtype)
+            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)
+
+    def test_sbmv_hbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            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)
+            A = A + A.T if ind < 2 else A + A.conj().T
+            Ab[-1, :] = diag(A)
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            alpha, beta = dtype(1.25), dtype(3)
+
+            if ind > 1:
+                func, = get_blas_funcs(('hbmv',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('sbmv',), dtype=dtype)
+            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)
+
+    def test_spmv_hpmv(self):
+        rng = np.random.default_rng(12345698)
+        for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 4 else A + 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)
+
+            if ind > 3:
+                func, = get_blas_funcs(('hpmv',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('spmv',), dtype=dtype)
+            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])
+
+    def test_spr_hpr(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 4 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5)
+
+            if ind > 3:
+                func, = get_blas_funcs(('hpr',), dtype=dtype)
+                y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
+            else:
+                func, = get_blas_funcs(('spr',), dtype=dtype)
+                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 ind > 3 else y1
+            assert_array_almost_equal(y1f, y2)
+
+    def test_spr2_hpr2(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 2 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            alpha = dtype(2)
+
+            if ind > 1:
+                func, = get_blas_funcs(('hpr2',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('spr2',), dtype=dtype)
+
+            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)
+
+    def test_tbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            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 ind > 1:
+                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, = get_blas_funcs(('tbmv',), dtype=dtype)
+
+            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)
+
+    def test_tbsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            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 ind > 1:
+                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, = get_blas_funcs(('tbsv',), dtype=dtype)
+
+            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)
+
+    def test_tpmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            x = rng.random(n).astype(dtype)
+            # Upper triangular array
+            if ind < 2:
+                A = triu(rng.random((n, n)))
+            else:
+                A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+
+            # Form the packed storage
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            func, = get_blas_funcs(('tpmv',), dtype=dtype)
+
+            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)
+
+    def test_tpsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            x = rng.random(n).astype(dtype)
+            # Upper triangular array
+            if ind < 2:
+                A = triu(rng.random((n, n)))
+            else:
+                A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+            A += eye(n)
+            # Form the packed storage
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            func, = get_blas_funcs(('tpsv',), dtype=dtype)
+
+            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)
+
+    def test_trmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 3
+            A = (rng.random((n, n))+eye(n)).astype(dtype)
+            x = rng.random(3).astype(dtype)
+            func, = get_blas_funcs(('trmv',), dtype=dtype)
+
+            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)
+
+    def test_trsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 15
+            A = (rng.random((n, n))+eye(n)).astype(dtype)
+            x = rng.random(n).astype(dtype)
+            func, = get_blas_funcs(('trsv',), dtype=dtype)
+
+            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:
+
+    def test_gemm(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'gemm', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
+            assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
+        for p in 'cz':
+            f = getattr(fblas, p+'gemm', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
+            assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
+
+
+def _get_func(func, ps='sdzc'):
+    """Just a helper: return a specified BLAS function w/typecode."""
+    for p in ps:
+        f = getattr(fblas, p+func, None)
+        if f is None:
+            continue
+        yield f
+
+
+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.]])
+
+    def test_symm(self):
+        for f in _get_func('symm'):
+            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)
+
+    def test_summ_wrong_side(self):
+        f = getattr(fblas, 'dsymm', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a, 'b': self.b,
+                                           'alpha': 1, 'side': 1})
+            # `side=1` means C <- B*A, hence shapes of A and B are to be
+            #  compatible. Otherwise, f2py exception is raised
+
+    def test_symm_wrong_uplo(self):
+        """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.
+        """
+        f = getattr(fblas, 'dsymm', None)
+        if f is not None:
+            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.]])
+
+    def test_syrk(self):
+        for f in _get_func('syrk'):
+            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?
+    # FIXME: how to catch the _fblas.error?
+    def test_syrk_wrong_c(self):
+        f = getattr(fblas, 'dsyrk', None)
+        if f is not None:
+            assert_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]])
+
+    def test_syr2k(self):
+        for f in _get_func('syr2k'):
+            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?
+    def test_syr2k_wrong_c(self):
+        f = getattr(fblas, 'dsyr2k', None)
+        if f is not None:
+            assert_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.]])
+
+    def test_symm_zc(self):
+        for f in _get_func('symm', 'zc'):
+            # 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]))
+
+    def test_hemm_zc(self):
+        for f in _get_func('hemm', 'zc'):
+            # 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]))
+
+    def test_syrk_zr(self):
+        for f in _get_func('syrk', 'zc'):
+            res = f(a=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
+
+    def test_herk_zr(self):
+        for f in _get_func('herk', 'zc'):
+            res = f(a=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+    def test_syr2k_zr(self):
+        for f in _get_func('syr2k', 'zc'):
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
+
+    def test_her2k_zr(self):
+        for f in _get_func('her2k', 'zc'):
+            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 dtrmm."""
+
+    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")
+
+    @pytest.mark.parametrize("dtype_", DTYPES)
+    def test_side(self, dtype_):
+        trmm = get_blas_funcs("trmm", dtype=dtype_)
+        # 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)
+
+    def test_ab(self):
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            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)
+
+    def test_ab_lower(self):
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            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)
+
+    def test_b_overwrites(self):
+        # BLAS dtrmm modifies B argument in-place.
+        # Here the default is to copy, but this can be overridden
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            for overwr in [True, False]:
+                bcopy = self.b.copy()
+                result = f(1., self.a, bcopy, overwrite_b=overwr)
+                # C-contiguous arrays are copied
+                assert_(bcopy.flags.f_contiguous is False and
+                        np.may_share_memory(bcopy, result) is False)
+                assert_equal(bcopy, self.b)
+
+            bcopy = np.asfortranarray(self.b.copy())  # or just transpose it
+            result = f(1., self.a, bcopy, overwrite_b=True)
+            assert_(bcopy.flags.f_contiguous is True and
+                    np.may_share_memory(bcopy, result) is True)
+            assert_array_almost_equal(bcopy, result)
+
+
+def test_trsm():
+    rng = np.random.default_rng(1234)
+    for ind, dtype in enumerate(DTYPES):
+        tol = np.finfo(dtype).eps*1000
+        func, = get_blas_funcs(('trsm',), dtype=dtype)
+
+        # 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 ind < 2:
+            A = rng.random((m, m)) + eye(m)
+        else:
+            A = (rng.random((m, m)) + rng.random((m, m))*1j) + 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)
+
+
+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
+    with assert_raises(fblas.__fblas_error):
+        scipy.linalg.blas.dnrm2(x, 5, 3, incx)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..284e214d38ed331cf0493d1e3bba6e1214939b2c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
@@ -0,0 +1,118 @@
+import numpy as np
+from numpy.testing import (assert_allclose,
+                           assert_equal)
+import scipy.linalg.cython_blas as blas
+
+class TestDGEMM:
+    
+    def test_transposes(self):
+
+        a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2]
+        b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2]
+        c = np.empty((2, 4))[: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='d').reshape((3, 2))
+        b = np.arange(-6, 2, dtype='d').reshape((2, 4))
+        c = np.empty((3, 4))
+
+        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.10/site-packages/scipy/linalg/tests/test_cython_lapack.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4e7b34b62042efdb0ce0f8ee61ce0189320995
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
@@ -0,0 +1,22 @@
+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):
+        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):
+        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)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d52c93950b6398c010b8bb8e5312153b3102fdf4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
@@ -0,0 +1,132 @@
+import numpy as np
+from scipy.linalg import bandwidth, issymmetric, ishermitian
+import pytest
+from pytest import raises
+
+
+def test_bandwidth_dtypes():
+    n = 5
+    for t in np.typecodes['All']:
+        A = np.zeros([n, n], dtype=t)
+        if t in 'eUVOMm':
+            raises(TypeError, bandwidth, A)
+        elif t == 'G':  # No-op test. On win these pass on others fail.
+            pass
+        else:
+            _ = bandwidth(A)
+
+
+def test_bandwidth_non2d_input():
+    A = np.array([1, 2, 3])
+    raises(ValueError, bandwidth, A)
+    A = np.array([[[1, 2, 3], [4, 5, 6]]])
+    raises(ValueError, bandwidth, A)
+
+
+@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
+                               if x not in 'eGUVOMm'])
+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)
+
+
+@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
+                               if x not in 'eGUVOMm'])
+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)
+
+
+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.10/site-packages/scipy/linalg/tests/test_decomp.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..605496721f8eec7a522fbba0a77ed33d6c1fdeaf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
@@ -0,0 +1,3152 @@
+import itertools
+import platform
+import sys
+
+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 (dgbtrf, dgbtrs, zgbtrf, zgbtrs, dsbev,
+                                 dsbevd, dsbevx, zhbevd, zhbevx)
+
+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
+try:
+    from scipy.__config__ import CONFIG
+except ImportError:
+    CONFIG = None
+
+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"
+    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_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(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 np.testing.suppress_warnings() as sup:
+            # isclose chokes on inf/nan values
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            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
+
+
+
+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."""
+        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."""
+        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)
+        # 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."""
+        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)
+        # 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."""
+        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)
+        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."""
+
+        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."""
+
+        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', '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'):
+            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', '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 setup_class(self):
+        np.random.seed(1234)
+
+    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)
+
+    def test_eigh_of_sparse(self):
+        # This tests the rejection of inputs that eigh cannot currently handle.
+        import scipy.sparse
+        a = scipy.sparse.identity(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
+
+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.fail_slow(10)
+def test_svd_gesdd_nofegfault():
+    # svd(a) with {U,VT}.size > INT_MAX does not segfault
+    # cf https://github.com/scipy/scipy/issues/14001
+    df=np.ones((4799, 53130), dtype=np.float64)
+    with assert_raises(ValueError):
+        svd(df)
+
+
+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):
+        np.random.seed(1234)
+        a = np.random.rand(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
+        q, r = qr(a, lwork=None)
+
+        # Test against minimum valid lwork
+        q2, r2 = qr(a, lwork=3)
+        assert_array_almost_equal(q2, q)
+        assert_array_almost_equal(r2, r)
+
+        # Test against larger lwork
+        q3, r3 = qr(a, lwork=10)
+        assert_array_almost_equal(q3, q)
+        assert_array_almost_equal(r3, r)
+
+        # Test against explicit lwork=-1
+        q4, r4 = qr(a, lwork=-1)
+        assert_array_almost_equal(q4, q)
+        assert_array_almost_equal(r4, r)
+
+        # Test against invalid lwork
+        assert_raises(Exception, qr, (a,), {'lwork': 0})
+        assert_raises(Exception, 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.int32)
+
+        r, *other = qr(a, mode='r', pivoting=pivoting)
+        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.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.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.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)))
+
+
+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
+if CONFIG is not 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.shape = 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.shape = 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.shape = 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.shape = 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)
+    R.shape = 10, 10
+    S = np.arange(20000, dtype=np.uint8)
+    S = np.frombuffer(S.data, offset=4, count=100, dtype=float)
+    S.shape = 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)
+
+    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):
+        # cannot test M == 0 due to bug in old numpy
+        for M in range(1, 7):
+            np.random.seed(999999999)
+            X = np.random.rand(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):
+        # cannot test M == 0 due to bug in old numpy
+        for M in range(1, 7):
+            X = np.random.rand(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.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..61bbc7e544f10fc834034fbadd7141f6deb1d423
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
@@ -0,0 +1,268 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+from pytest import raises as assert_raises
+
+from numpy import array, transpose, dot, conjugate, zeros_like, empty
+from numpy.random import random
+from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded,
+     cho_factor, cho_solve)
+
+from scipy.linalg._testutils import assert_no_overwrite
+
+
+class TestCholesky:
+
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+        c = cholesky(a)
+        assert_array_almost_equal(dot(transpose(c), c), a)
+        c = transpose(c)
+        a = dot(c, transpose(c))
+        assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+        c = cholesky(a, check_finite=False)
+        assert_array_almost_equal(dot(transpose(c), c), a)
+        c = transpose(c)
+        a = dot(c, transpose(c))
+        assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c)
+
+    def test_simple_complex(self):
+        m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]])
+        a = dot(transpose(conjugate(m)), m)
+        c = cholesky(a)
+        a1 = dot(transpose(conjugate(c)), c)
+        assert_array_almost_equal(a, a1)
+        c = transpose(c)
+        a = dot(c, transpose(conjugate(c)))
+        assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_random(self):
+        n = 20
+        for k in range(2):
+            m = random([n, n])
+            for i in range(n):
+                m[i, i] = 20*(.1+m[i, i])
+            a = dot(transpose(m), m)
+            c = cholesky(a)
+            a1 = dot(transpose(c), c)
+            assert_array_almost_equal(a, a1)
+            c = transpose(c)
+            a = dot(c, transpose(c))
+            assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_random_complex(self):
+        n = 20
+        for k in range(2):
+            m = random([n, n])+1j*random([n, n])
+            for i in range(n):
+                m[i, i] = 20*(.1+abs(m[i, i]))
+            a = dot(transpose(conjugate(m)), m)
+            c = cholesky(a)
+            a1 = dot(transpose(conjugate(c)), c)
+            assert_array_almost_equal(a, a1)
+            c = transpose(c)
+            a = dot(c, transpose(conjugate(c)))
+            assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    @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)
+
+
+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_array_almost_equal(a, dot(ufac.T, ufac))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, False), b, check_finite=False)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    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_array_almost_equal(a, dot(ufac.T, ufac))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, False), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    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_array_almost_equal(a, dot(ufac.conj().T, ufac))
+
+        b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0])
+        x = cho_solve_banded((c, False), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    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_array_almost_equal(a, dot(lfac, lfac.T))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, True), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    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_array_almost_equal(a, dot(lfac, lfac.conj().T))
+
+        b = array([0.0, 0.5j, 3.8j, 3.8])
+        x = cho_solve_banded((c, True), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0])
+
+    @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
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..df112f0e4cf75d03d2787c24306665b7027967ee
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
@@ -0,0 +1,300 @@
+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_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.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d74a746b4dd7bb6367500b4c893aa9f767de51f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py
@@ -0,0 +1,137 @@
+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.random import rand, randint, seed
+from scipy.linalg import ldl
+from scipy._lib._util import ComplexWarning
+import pytest
+from pytest import raises as assert_raises, warns
+
+
+@pytest.mark.thread_unsafe
+def test_args():
+    A = eye(3)
+    # Nonsquare array
+    assert_raises(ValueError, ldl, A[:, :2])
+    # Complex matrix with imaginary diagonal entries with "hermitian=True"
+    with 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():
+    seed(1234)
+    for _ in range(10):
+        n = randint(1, 100)
+        # Random real/complex array
+        x = rand(n, n) if randint(2) else rand(n, n) + rand(n, n)*1j
+        x = x + x.conj().T
+        x += eye(n)*randint(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):
+    seed(1234)
+    msg = (f"Failed for size: {n}, dtype: {dtype}")
+
+    x = rand(n, n).astype(dtype)
+    x = x + x.T
+    x += eye(n, dtype=dtype)*dtype(randint(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):
+    seed(1234)
+    msg1 = (f"Her failed for size: {n}, dtype: {dtype}")
+    msg2 = (f"Sym failed for size: {n}, dtype: {dtype}")
+
+    # Complex hermitian upper/lower
+    x = (rand(n, n)+1j*rand(n, n)).astype(dtype)
+    x = x+x.conj().T
+    x += eye(n, dtype=dtype)*dtype(randint(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 = (rand(n, n)+1j*rand(n, n)).astype(dtype)
+    x = x+x.T
+    x += eye(n, dtype=dtype)*dtype(randint(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.10/site-packages/scipy/linalg/tests/test_decomp_lu.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..da0beccf1f0e66baf4ac4ec80d7ff7129b2df345
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py
@@ -0,0 +1,308 @@
+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
+
+
+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)
+
+    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.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.10/site-packages/scipy/linalg/tests/test_decomp_polar.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..607238842b3cc643d9665e40f29e41b15d8951a1
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/linalg/tests/test_decomp_update.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..7553e21d61ceaa774d24c48d9d4bc2e3a8e3cc00
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
@@ -0,0 +1,1701 @@
+import itertools
+
+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'):
+        np.random.seed(29382)
+        shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
+                 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type]
+        a = np.random.random(shape)
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = np.random.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)
+
+    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.RandomState(1234)
+
+        # super call set the seed...
+        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:
+            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')
+
+    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)
+
+        # super call set the seed...
+        if p == 1:
+            u = np.random.random(q.shape[0])
+            v = np.random.random(r.shape[1])
+        else:
+            u = np.random.random((q.shape[0], p))
+            v = np.random.random((r.shape[1], p))
+
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = np.random.random(u.shape)
+            u = u + 1j * b
+
+            c = np.random.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:])
+
+    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):
+    np.random.seed(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 = np.random.random(q_shape)
+        u = np.random.random(u_shape)
+    elif dtype.char in 'FD':
+        q = np.random.random(q_shape) + 1j*np.random.random(q_shape)
+        u = np.random.random(u_shape) + 1j*np.random.random(u_shape)
+    else:
+        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.10/site-packages/scipy/linalg/tests/test_extending.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..36e4692cd9717a221cc683a663e8ee23a81aa5b6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py
@@ -0,0 +1,46 @@
+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 cdotu  # type: ignore[attr-defined]
+from scipy.linalg.lapack import dgtsv  # type: ignore[attr-defined]
+
+
+@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)
+    _, _, _, 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)
+    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))
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c5ada830043af0eecb6d04bf39aef13d29d777c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py
@@ -0,0 +1,607 @@
+# 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 numpy import float32, float64, complex64, complex128, arange, array, \
+                  zeros, shape, transpose, newaxis, common_type, conjugate
+
+from scipy.linalg import _fblas as fblas
+
+from numpy.testing import assert_array_equal, \
+    assert_allclose, assert_array_almost_equal, assert_
+
+import pytest
+
+# 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):
+        mult = array(1, dtype=self.dtype)
+        if self.dtype in [complex64, complex128]:
+            mult = array(1+1j, dtype=self.dtype)
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1., dtype=self.dtype) * mult
+        beta = array(1., dtype=self.dtype) * mult
+        a = 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
+
+        def test_sgemv_on_osx(self):
+            from itertools import product
+            import sys
+            import numpy as np
+
+            if sys.platform != 'darwin':
+                return
+
+            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'))
+            for align, m, n, a_order in testdata:
+                A_d = np.random.rand(m, n)
+                X_d = np.random.rand(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):
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1., dtype = self.dtype)
+        a = 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):
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1+1j, dtype = self.dtype)
+        a = normal(0.,1.,(3,3)).astype(self.dtype)
+        a = a + normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype)
+        x = normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype)
+        x = x + x * array(1j, dtype = self.dtype)
+        y = 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.10/site-packages/scipy/linalg/tests/test_interpolative.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e1cc5496eafe19ced81ea546e3bad386148ae7b
--- /dev/null
+++ b/venv/lib/python3.10/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
+
+        # fixed precision
+        A = np.random.rand(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.10/site-packages/scipy/linalg/tests/test_lapack.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..86555d6c19916c8ae1f6a796fb009a6b803b2159
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py
@@ -0,0 +1,3508 @@
+#
+# Created by: Pearu Peterson, September 2002
+#
+
+from functools import reduce
+import random
+
+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 numpy.random import rand, randint, seed
+
+from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky,
+                          solve, ldl, norm, block_diag, qr, eigh, qz)
+
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+
+import scipy.sparse as sps
+try:
+    from scipy.__config__ import CONFIG
+except ImportError:
+    CONFIG = None
+
+try:
+    from scipy.linalg import _clapack as clapack
+except ImportError:
+    clapack = None
+from scipy.linalg.lapack import get_lapack_funcs
+from scipy.linalg.blas import get_blas_funcs
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+blas_provider = blas_version = None
+if CONFIG is not None:
+    blas_provider = CONFIG['Build Dependencies']['blas']['name']
+    blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+
+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",
+        "clapack",
+        "division",
+        "find_best_lapack_type",
+        "flapack",
+        "print_function",
+        "HAS_ILP64",
+        "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'
+
+
+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 p in 'sdzc':
+            f = getattr(flapack, p+'gebal', None)
+            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 p in 'd':
+            f = getattr(flapack, p+'gehrd', None)
+            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 TestLapack:
+
+    def test_flapack(self):
+        if hasattr(flapack, 'empty_module'):
+            # flapack module is empty
+            pass
+
+    def test_clapack(self):
+        if hasattr(clapack, 'empty_module'):
+            # clapack module is empty
+            pass
+
+
+class TestLeastSquaresSolvers:
+
+    def test_gels(self):
+        seed(1234)
+        # Test fat/tall matrix argument handling - gh-issue #8329
+        for ind, dtype in enumerate(DTYPES):
+            m = 10
+            n = 20
+            nrhs = 1
+            a1 = rand(m, n).astype(dtype)
+            b1 = rand(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:
+    def test_gh_2691(self):
+        # 'lower' argument of dportf/dpotri
+        for lower in [True, False]:
+            for clean in [True, False]:
+                np.random.seed(42)
+                x = np.random.normal(size=(3, 3))
+                a = x.dot(x.T)
+
+                dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, ))
+
+                c, info = 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), "LAPACK root finding dlasd4 failed to find \
+                                    the singular value %i" % 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 = sps.diags(bands, 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)
+        ab = rand(4, 2)
+        b = rand(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`) integer seed based on arguments
+    random.seed(f"{dtype}{norm}{uplo}{diag}{n}")
+    rng = np.random.default_rng(random.randint(0, 9999999999999))
+
+    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.abs(A).sum(axis=0).max()
+        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():
+    np.random.seed(1234)
+    a0 = np.random.random((4, 4))
+    a0 = a0.T.dot(a0)
+
+    a0j = np.random.random((4, 4)) + 1j*np.random.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',
+                             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():
+    seed(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 = (rand(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 = (rand(n, n) + rand(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():
+    seed(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 = rand(n, n).astype(dtype)
+        A = (A + A.T)/2
+        # B must be positive definite
+        B = rand(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():
+    seed(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 = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype)
+        A = (A + A.conj().T)/2
+        # B must be positive definite
+        B = rand(n, n).astype(dtype) + 1j * rand(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.rand(qm, qn).astype(dtype))
+            C = rng.rand(cn, cn).astype(dtype)
+            orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'),
+                                                     dtype=dtype)
+        else:
+            A = triu((rng.rand(qm, qn) + rng.rand(qm, qn)*1j).astype(dtype))
+            C = (rng.rand(cn, cn) + rand(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', range(6))  # 'C', 'E', 'F', 'G', 'A', 'R'
+@pytest.mark.parametrize('jobu', range(4))  # 'U', 'F', 'W', 'N'
+@pytest.mark.parametrize('jobv', 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 = np.random.rand(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.abs(A).sum(axis=0).max()
+
+    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",
+                         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",
+                         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",
+                         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",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", 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.
+    '''
+    seed(42)
+    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",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_error_non_spd(dtype, realtype, compute_z):
+    seed(42)
+    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",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z):
+    seed(42)
+    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",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_error_singular(dtype, realtype, compute_z):
+    seed(42)
+    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):
+    seed(1234)
+    p = randint(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", 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", 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", 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)
+    assert info == 0
+    x, info = trs(a=ldu, ipiv=ipiv, b=b)
+    assert info == 0
+    eps = np.finfo(dtype).eps
+    assert_allclose(A@x, b, 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)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e87333c40b64d3f54024779dfb959be7a599178
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py
@@ -0,0 +1,1063 @@
+#
+# Created by: Pearu Peterson, March 2002
+#
+""" Test functions for linalg.matfuncs module
+
+"""
+import functools
+
+import numpy as np
+from numpy import array, identity, dot, sqrt
+from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_,
+                           assert_array_less, assert_array_equal, assert_warns)
+import pytest
+
+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 import pick_pade_structure
+from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning
+import scipy.linalg._expm_frechet
+
+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, disp=False)
+        #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, disp=False)
+        #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, disp=False)
+        #XXX: what would be the correct result?
+
+
+class TestLogM:
+
+    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, disp=False)
+        #XXX: what would be the correct result?
+
+    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, info = logm(A, disp=False)
+        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, info = funm(A, np.log, disp=False)
+        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):
+        np.random.seed(1234)
+        for n in range(1, 6):
+            M_unscaled = np.random.randn(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, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+                # Check logm round trip.
+                M_logm, info = logm(M, disp=False)
+                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):
+        np.random.seed(1234)
+        for n in range(1, 6):
+            M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_logm, info = logm(M, disp=False)
+                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, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char not in complex_dtype_chars)
+
+            # check complex type preservation
+            A = np.array(matrix_as_list, dtype=complex)
+            A_logm, info = logm(A, disp=False)
+            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, info = logm(A, disp=False)
+            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, info = logm(X, disp=False)
+            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, disp=False)
+                assert_(np.issubdtype(A_logm.dtype, np.complexfloating))
+
+    @pytest.mark.thread_unsafe
+    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:
+            expected_warning = _matfuncs_inv_ssq.LogmExactlySingularWarning
+            L, info = assert_warns(expected_warning, logm, M, disp=False)
+            E = expm(L)
+            assert_allclose(E, M, atol=1e-14)
+
+    @pytest.mark.thread_unsafe
+    def test_nearly_singular(self):
+        M = np.array([[1e-100]])
+        expected_warning = _matfuncs_inv_ssq.LogmNearlySingularWarning
+        L, info = assert_warns(expected_warning, logm, M, disp=False)
+        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.thread_unsafe
+    @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.RandomState(1234)
+        for n in range(1, 6):
+            M_unscaled = rng.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_sqrtm, info = sqrtm(M, disp=False)
+                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.RandomState(1234)
+        for n in range(1, 6):
+            M_unscaled = rng.randn(n, n) + 1j * rng.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_sqrtm, info = sqrtm(M, disp=False)
+                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]])
+        n = a.shape[0]
+        assert_array_almost_equal(dot(sa,sa),a)
+        # Check default sqrtm.
+        esa = sqrtm(a, disp=False, blocksize=n)[0]
+        assert_array_almost_equal(dot(esa,esa),a)
+        # Check sqrtm with 2x2 blocks.
+        esa = sqrtm(a, disp=False, blocksize=2)[0]
+        assert_array_almost_equal(dot(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))
+
+            # check float type preservation
+            A = np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char not in complex_dtype_chars)
+
+            # check complex type preservation
+            A = np.array(matrix_as_list, dtype=complex)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            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, info = sqrtm(A, disp=False)
+            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, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+            # check float->complex
+            A = np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+    def test_blocksizes(self):
+        # Make sure I do not goof up the blocksizes when they do not divide n.
+        np.random.seed(1234)
+        for n in range(1, 8):
+            A = np.random.rand(n, n) + 1j*np.random.randn(n, n)
+            A_sqrtm_default, info = sqrtm(A, disp=False, blocksize=n)
+            assert_allclose(A, np.linalg.matrix_power(A_sqrtm_default, 2))
+            for blocksize in range(1, 10):
+                A_sqrtm_new, info = sqrtm(A, disp=False, blocksize=blocksize)
+                assert_allclose(A_sqrtm_default, A_sqrtm_new)
+
+    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, info = sqrtm(A, disp=False)
+        A_round_trip = A_sqrtm.dot(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.
+        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)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(np.isnan(A_sqrtm).all())
+
+    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.dot(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_disp(self):
+        np.random.seed(1234)
+
+        A = np.random.rand(3, 3)
+        B = sqrtm(A, disp=True)
+        assert_allclose(B.dot(B), 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(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(np.dot(R, R), M, atol=1e-14)
+        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(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh7839(self):
+        M = np.zeros((2, 2))
+        R = np.zeros((2, 2))
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    @pytest.mark.xfail(reason="failing on macOS after gh-20212")
+    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_data_size_preservation_uint_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.uint8)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint16)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint32)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint64)
+        assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_int_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.int8)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int16)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int32)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 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
+
+    def test_data_size_preservation_float_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.float16)
+        assert sqrtm(M).dtype == np.float32
+        M = np.zeros((10, 10), dtype=np.float32)
+        assert sqrtm(M).dtype == np.float32
+        M = np.zeros((10, 10), dtype=np.float64)
+        assert sqrtm(M).dtype == np.float64
+        if hasattr(np, 'float128'):
+            M = np.zeros((10, 10), dtype=np.float128)
+            assert sqrtm(M).dtype == np.float64
+
+    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
+
+    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
+
+
+class TestFractionalMatrixPower:
+    def test_round_trip_random_complex(self):
+        np.random.seed(1234)
+        for p in range(1, 5):
+            for n in range(1, 5):
+                M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(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.
+        np.random.seed(1234)
+        for p in range(1, 5):
+            for n in range(1, 5):
+                M_unscaled = np.random.randn(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):
+        np.random.seed(1234)
+        for n in (2, 3, 5):
+            for i in range(10):
+                M = np.random.randn(n, n) + 1j * np.random.randn(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, info = logm(A, disp=False)
+            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, info = funm(A, np.sqrt, disp=False)
+        A_sqrtm, info = sqrtm(A, disp=False)
+        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):
+        np.random.seed(1234)
+        for a in np.random.randn(10) + 1j * np.random.randn(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.thread_unsafe
+    @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)
+        # Problem appears when m = 9
+        Am = np.empty((5, 400, 400), dtype=float)
+        Am[0] = A.copy()
+        m, s = pick_pade_structure(Am)
+        assert m == 9
+        # 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)
+
+
+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 = (
+                np.random.uniform,
+                np.random.normal,
+                np.random.standard_cauchy,
+                np.random.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
+        A = np.random.exponential(size=(n, n))
+        E = np.random.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):
+        np.random.seed(1234)
+        for n in range(1, 4):
+            A = np.random.randn(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):
+        np.random.seed(12345)
+        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 = np.random.randn(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.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f8f94fd10a5404d4013adf995bba54f76ff803
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/linalg/tests/test_procrustes.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4efa433c2cab01a4f77ef1c4f1bde3ab4d5c421b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py
@@ -0,0 +1,221 @@
+from itertools import product, permutations
+
+import numpy as np
+import pytest
+from numpy.testing import assert_array_less, assert_allclose
+from pytest import raises as assert_raises
+
+from scipy.linalg import inv, eigh, norm, svd
+from scipy.linalg import orthogonal_procrustes
+from scipy.sparse._sputils import matrix
+
+
+def test_orthogonal_procrustes_ndim_too_large():
+    rng = np.random.RandomState(1234)
+    A = rng.randn(3, 4, 5)
+    B = rng.randn(3, 4, 5)
+    assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_ndim_too_small():
+    rng = np.random.RandomState(1234)
+    A = rng.randn(3)
+    B = rng.randn(3)
+    assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_shape_mismatch():
+    rng = np.random.RandomState(1234)
+    shapes = ((3, 3), (3, 4), (4, 3), (4, 4))
+    for a, b in permutations(shapes, 2):
+        A = rng.randn(*a)
+        B = rng.randn(*b)
+        assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_checkfinite_exception():
+    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, A, B)
+
+
+def test_orthogonal_procrustes_scale_invariance():
+    rng = np.random.RandomState(1234)
+    m, n = 4, 3
+    for i in range(3):
+        A_orig = rng.randn(m, n)
+        B_orig = 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 * A_scale, B_orig * B_scale)
+                assert_allclose(R, R_orig)
+
+
+def test_orthogonal_procrustes_array_conversion():
+    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():
+    rng = np.random.RandomState(1234)
+    for m, n in ((6, 4), (4, 4), (4, 6)):
+        # Sample a random target matrix.
+        B = rng.randn(m, n)
+        # Sample a random orthogonal matrix
+        # by computing eigh of a sampled symmetric matrix.
+        X = rng.randn(n, n)
+        w, V = eigh(X.T + X)
+        assert_allclose(inv(V), V.T)
+        # Compute a matrix with a known orthogonal transformation that gives B.
+        A = np.dot(B, V.T)
+        # Check that an orthogonal transformation from A to B can be recovered.
+        R, s = orthogonal_procrustes(A, B)
+        assert_allclose(inv(R), R.T)
+        assert_allclose(A.dot(R), B)
+        # Create a perturbed input matrix.
+        A_perturbed = A + 1e-2 * 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)
+        assert_allclose(inv(R_prime), R_prime.T)
+        # Compute the naive and optimal transformations of the perturbed input.
+        naive_approx = A_perturbed.dot(R)
+        optim_approx = A_perturbed.dot(R_prime)
+        # Compute the Frobenius norm errors of the matrix approximations.
+        naive_approx_error = norm(naive_approx - B, ord='fro')
+        optim_approx_error = norm(optim_approx - B, ord='fro')
+        # Check that the orthogonal Procrustes approximation is better.
+        assert_array_less(optim_approx_error, naive_approx_error)
+
+
+def _centered(A):
+    mu = A.mean(axis=0)
+    return A - mu, mu
+
+
+def test_orthogonal_procrustes_exact_example():
+    # Check a small application.
+    # It uses translation, scaling, reflection, and rotation.
+    #
+    #         |
+    #   a  b  |
+    #         |
+    #   d  c  |        w
+    #         |
+    # --------+--- x ----- z ---
+    #         |
+    #         |        y
+    #         |
+    #
+    A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float)
+    B_orig = np.array([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=float)
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    assert_allclose(B_approx, B_orig, atol=1e-8)
+
+
+def test_orthogonal_procrustes_stretched_example():
+    # Try again with a target with a stretched y axis.
+    A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float)
+    B_orig = np.array([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=float)
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    expected = np.array([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=float)
+    assert_allclose(B_approx, expected, atol=1e-8)
+    # Check disparity symmetry.
+    expected_disparity = 0.4501246882793018
+    AB_disparity = np.square(norm(B_approx - B_orig) / norm(B))
+    assert_allclose(AB_disparity, expected_disparity)
+    R, s = orthogonal_procrustes(B, A)
+    scale = s / np.square(norm(B))
+    A_approx = scale * np.dot(B, R) + A_mu
+    BA_disparity = np.square(norm(A_approx - A_orig) / norm(A))
+    assert_allclose(BA_disparity, expected_disparity)
+
+
+def test_orthogonal_procrustes_skbio_example():
+    # This transformation is also exact.
+    # It uses translation, scaling, and reflection.
+    #
+    #   |
+    #   | a
+    #   | b
+    #   | c d
+    # --+---------
+    #   |
+    #   |       w
+    #   |
+    #   |       x
+    #   |
+    #   |   z   y
+    #   |
+    #
+    A_orig = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=float)
+    B_orig = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=float)
+    B_standardized = np.array([
+        [-0.13363062, 0.6681531],
+        [-0.13363062, 0.13363062],
+        [-0.13363062, -0.40089186],
+        [0.40089186, -0.40089186]])
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    assert_allclose(B_approx, B_orig)
+    assert_allclose(B / norm(B), B_standardized)
+
+
+def test_empty():
+    a = np.empty((0, 0))
+    r, s = orthogonal_procrustes(a, a)
+    assert_allclose(r, np.empty((0, 0)))
+
+    a = np.empty((0, 3))
+    r, s = orthogonal_procrustes(a, a)
+    assert_allclose(r, np.identity(3))
+
+
+@pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)])
+def test_unitary(shape):
+    # gh-12071 added support for unitary matrices; check that it
+    # works as intended.
+    m, n = shape
+    rng = np.random.default_rng(589234981235)
+    A = rng.random(shape) + rng.random(shape) * 1j
+    Q = rng.random((n, n)) + rng.random((n, n)) * 1j
+    Q, _ = np.linalg.qr(Q)
+    B = A @ Q
+    R, scale = orthogonal_procrustes(A, B)
+    assert_allclose(R @ R.conj().T, np.eye(n), atol=1e-14)
+    assert_allclose(A @ Q, B)
+    if shape != (4, 5):  # solution is unique
+        assert_allclose(R, Q)
+    _, s, _ = svd(A.conj().T @ B)
+    assert_allclose(scale, np.sum(s))
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fc5a8540510f57a2b00334b5e190d4ddd474d09
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py
@@ -0,0 +1,118 @@
+"""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, rand
+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]
+
+    A_dense = rng.random((n_rows, n_cols))
+    A_csc = rand(
+        n_rows, n_cols, density=density, format='csc', random_state=rng,
+    )
+    A_csr = rand(
+        n_rows, n_cols, density=density, format='csr', random_state=rng,
+    )
+    A_coo = rand(
+        n_rows, n_cols, density=density, format='coo', random_state=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)
+
+    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.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..440a73abc8c83bc32887c37c75577b790f3f1be9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
@@ -0,0 +1,150 @@
+"""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, matmul_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), (4, 3, 2)):
+            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
+
+
+@pytest.mark.parametrize('fun', [solve_toeplitz, matmul_toeplitz])
+def test_nd_FutureWarning(fun):
+    # Test future warnings with n-D `c`/`r`
+    rng = np.random.default_rng(283592436523456)
+    c = rng.random((2, 3, 4))
+    r = rng.random((2, 3, 4))
+    b_or_x = rng.random(24)
+    message = "Beginning in SciPy 1.17, multidimensional input will be..."
+    with pytest.warns(FutureWarning, match=message):
+         fun(c, b_or_x)
+    with pytest.warns(FutureWarning, match=message):
+         fun((c, r), b_or_x)
diff --git a/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4a39c5e86939bddabafaaf87c643c0a4ad570fe
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py
@@ -0,0 +1,844 @@
+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
+
+
+# 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)
+
+    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", 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", 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)
+
+
+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.10/site-packages/scipy/linalg/tests/test_special_matrices.py b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..d32e7ed4b4016924c60b3ed6287888a0372e8791
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py
@@ -0,0 +1,640 @@
+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, kron, block_diag,
+                          helmert, hilbert, invhilbert, pascal, invpascal,
+                          fiedler, fiedler_companion, eigvals,
+                          convolution_matrix)
+from numpy.linalg import cond
+
+
+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)
+
+
+class TestBlockDiag:
+    def test_basic(self):
+        x = block_diag(eye(2), [[1, 2], [3, 4], [5, 6]], [[1, 2, 3]])
+        assert_array_equal(x, [[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):
+        x = block_diag([[1.5]])
+        assert_equal(x.dtype, float)
+
+        x = block_diag([[True]])
+        assert_equal(x.dtype, bool)
+
+    def test_mixed_dtypes(self):
+        actual = block_diag([[1]], [[1j]])
+        desired = np.array([[1, 0], [0, 1j]])
+        assert_array_equal(actual, desired)
+
+    def test_scalar_and_1d_args(self):
+        a = block_diag(1)
+        assert_equal(a.shape, (1, 1))
+        assert_array_equal(a, [[1]])
+
+        a = block_diag([2, 3], 4)
+        assert_array_equal(a, [[2, 3, 0], [0, 0, 4]])
+
+    def test_bad_arg(self):
+        assert_raises(ValueError, block_diag, [[[1]]])
+
+    def test_no_args(self):
+        a = block_diag()
+        assert_equal(a.ndim, 2)
+        assert_equal(a.nbytes, 0)
+
+    def test_empty_matrix_arg(self):
+        # 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.
+        a = block_diag([[1, 0], [0, 1]],
+                       [],
+                       [[2, 3], [4, 5], [6, 7]])
+        assert_array_equal(a, [[1, 0, 0, 0],
+                               [0, 1, 0, 0],
+                               [0, 0, 0, 0],
+                               [0, 0, 2, 3],
+                               [0, 0, 4, 5],
+                               [0, 0, 6, 7]])
+
+    def test_zerosized_matrix_arg(self):
+        # 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)
+        a = block_diag([[1, 0], [0, 1]],
+                       [[]],
+                       [[2, 3], [4, 5], [6, 7]],
+                       np.zeros([0, 2], dtype='int32'))
+        assert_array_equal(a, [[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 TestKron:
+    @pytest.mark.thread_unsafe
+    def test_dep(self):
+        with pytest.deprecated_call(match="`kron`"):
+            kron(np.array([[1, 2],[3, 4]]),np.array([[1, 1, 1]]))
+
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_basic(self):
+
+        a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]]))
+        assert_array_equal(a, array([[1, 1, 1, 2, 2, 2],
+                                     [3, 3, 3, 4, 4, 4]]))
+
+        m1 = array([[1, 2], [3, 4]])
+        m2 = array([[10], [11]])
+        a = kron(m1, m2)
+        expected = array([[10, 20],
+                          [11, 22],
+                          [30, 40],
+                          [33, 44]])
+        assert_array_equal(a, expected)
+
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_empty(self):
+        m1 = np.empty((0, 2))
+        m2 = np.empty((1, 3))
+        a = kron(m1, m2)
+        assert_allclose(a, np.empty((0, 6)))
+
+
+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="n=%d  kind=%r exact=%r" %
+                                              (n, kind, exact))
+
+    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)
+
+
+def test_fiedler():
+    f = fiedler([])
+    assert_equal(f.size, 0)
+    f = fiedler([123.])
+    assert_array_equal(f, np.array([[0.]]))
+    f = fiedler(np.arange(1, 7))
+    des = np.array([[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]])
+    assert_array_equal(f, des)
+
+
+def test_fiedler_companion():
+    fc = fiedler_companion([])
+    assert_equal(fc.size, 0)
+    fc = fiedler_companion([1.])
+    assert_equal(fc.size, 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.thread_unsafe
+@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, ()),
+                                     (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 {toeplitz}:
+        message = "Beginning in SciPy 1.17, 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.10/site-packages/scipy/ndimage/__init__.py b/venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e9d9f6ff99218088fd9e693aaca00ca8a070040
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py
@@ -0,0 +1,173 @@
+"""
+=========================================================
+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
+
+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
+
+
+# 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.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..810f058cf3486261ff5a186118a3afd0f5574fb5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abd0e4b8ec14802650bf360d2f5d1fbd075441ee
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2c5e561958a51d6bfe08de1ee10557699671426
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..14cb34cc2a4e4a768051cb2690e2c1ea1cc986f7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82911c86522d4881e65ea853b46dc355271ab038
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3374041dd3f27139952b988d75d515c4480a3ab9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a880a5b42f1e841d5fc6299649795f58c6626aeb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42a7a66f7e2e78ce8dc880a3e46992a1026d12de
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a7a909588a5378082f261238e7feeaf2f19988a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..268b40d0e1f7cc407c36521a993d3b07ca14dc0e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac46e34472760b1c7fb68b8eeeb5fc28dd9ddeb7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a9a6bb01bc06516e60947387ba0d8152a7ada70
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6d5d7b37b646a8fbc7d6b2f272c1aedc7dc6cc2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..065a78425bf0687b47c031b980c7d8423a125d19
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3171a05b125918ecb8786150137da241de75ec2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..830a9ab5db899519d50c48507a1cffaecf46215a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0d05e123ba1f7f45c1f37795e7ba5cd0257018b4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..7898248eb4d089b5ffa726ff39de4d0ec4637272
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..9647ea6456426c9a62178ff277b0f35017a8310b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py
@@ -0,0 +1,297 @@
+"""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, _skip_if_int
+
+
+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, _skip_if_int(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 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.10/site-packages/scipy/ndimage/_filters.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..710ea60c03653cc80ac3bd1eefd425b4268a5246
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py
@@ -0,0 +1,1965 @@
+# 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
+
+from scipy._lib._util import normalize_axis_index
+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']
+
+
+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
+
+    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_keywords)s
+    %(extra_arguments)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.
+    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_keywords)s
+    %(extra_arguments)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_matnitude : 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.
+    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.
+
+    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.
+
+    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)
+        if input.ndim == 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``.
+
+    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.
+
+    """
+    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
+    -------
+    generic_filter : 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 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.10/site-packages/scipy/ndimage/_fourier.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/_interpolation.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e4ea94184871fe87f848532b21e2def29bd406b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py
@@ -0,0 +1,1003 @@
+# 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 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.
+
+    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:
+        warnings.warn(
+            "The behavior of affine_transform with a 1-D "
+            "array supplied for the matrix parameter has changed in "
+            "SciPy 0.18.0.",
+            stacklevel=2
+        )
+        _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 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.10/site-packages/scipy/ndimage/_measurements.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..67ec12870ccf1dfe52624da05787b197542a0253
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py
@@ -0,0 +1,1687 @@
+# 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 a 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 a 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)
+
+    # 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.
+
+    """
+    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)
+
+    # 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
+    -------
+    minimum : float or list of floats
+        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 : float or list of floats
+        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.10/site-packages/scipy/ndimage/_morphology.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..12972c09a7cd5de0ca059814281fb9d210fbd395
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py
@@ -0,0 +1,2629 @@
+# 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)
+    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 : boolean, 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 : boolean, 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 : boolean, 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 : boolean, 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 al 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 morphlogical 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
+
+    """
+    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_indicies` 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_tranform_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.shape = 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_indicies` 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_tranform_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)
+        ft.shape = 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.shape = 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_indicies` 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_tranform_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_tranform_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.10/site-packages/scipy/ndimage/_ndimage_api.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1673391726a4070af4814d04be16e29e01d9f29b
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/_ni_docstrings.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c0d977500574b73f168296645fb36d10c1320de
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py
@@ -0,0 +1,210 @@
+"""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.""")
+_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' (`d b c d | a b c d | b c a b`)
+        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.""")
+_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
+    }
+
+docfiller: Final = doccer.filldoc(docdict)
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d41d00d9edf8d347c4ffc95598210489fed5e9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py
@@ -0,0 +1,143 @@
+# 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
+
+
+def _skip_if_int(arg):
+    return None if (arg is None or isinstance(arg, int)) else arg
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..6d998aa648b493336d9871117e687e8f8d5279aa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py b/venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbb913b14c76873202fce8eaabe2d08f778abe94
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py
@@ -0,0 +1,72 @@
+import functools
+from scipy._lib._array_api import (
+    is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API
+)
+
+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 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):
+                # 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 type(result)(
+                        xp.asarray(x) if isinstance(x, np.ndarray) else x
+                        for x in result
+                    )
+        return wrapper
+    return inner
+
+# ### decorate ###
+for func_name in _ndimage_api.__all__:
+    bare_func = getattr(_ndimage_api, func_name)
+    delegator = getattr(_delegators, func_name + "_signature")
+
+    f = (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.10/site-packages/scipy/ndimage/filters.py b/venv/lib/python3.10/site-packages/scipy/ndimage/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/fourier.py b/venv/lib/python3.10/site-packages/scipy/ndimage/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c49bd52d9a446ce0fe25d9e15b8de68fbd46fb
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/interpolation.py b/venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/measurements.py b/venv/lib/python3.10/site-packages/scipy/ndimage/measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/morphology.py b/venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..e522e7df3a4b06b7e04ed8c2d0ecaff2a98b951d
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d8fd292b537a84fe48d0c8ae8bee75bab2b3353
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d89e214e19fbdfc3c74fece24b5a246179a33efb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98656523d8e305ebe9d02f3687ff3275beb775b0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf348f8cf96bdbf7b383f1b4ebc62f6adc0aa1ae
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ee25efae9de8228be8f9b6088091a81826528ed
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74eb6995b3b2c1ffd449b24476b697c68d4a994b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21b59cd8abd7bc226dc5bf259eebcac05cfc5618
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_measurements.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa04a7033b4cb7d4ffe5cc56c181d7087eda3965
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_measurements.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc1c20800dcfd9d6a0dc1ff5d9350798320455c3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8cdc148bbacf881497640d972cf4e85a55921cf
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bbaad6a2ac15f2b230058d1c5efed66156b6e94
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6c3cff3b12cec4ad050b31cc5d5c327f32784447
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/data/label_results.txt b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c239b0369c9df3e06df9a2fbf048faec2f84941f
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/data/label_strels.txt b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/test_c_api.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..61a5a0f70262ef9f21fe8593a64f155bd583cab1
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/test_datatypes.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..a82de456bb92c96d5b9a599d4b33c987e134fdc8
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/ndimage/tests/test_filters.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d5cb39f566827f41037e34a5a63ce874996c36f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py
@@ -0,0 +1,2920 @@
+''' Some tests for filters '''
+import functools
+import itertools
+import re
+
+import numpy as np
+import pytest
+from numpy.testing import suppress_warnings, 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,
+)
+from scipy._lib._array_api import is_cupy, is_numpy, is_torch, array_namespace
+from scipy.conftest import array_api_compatible
+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
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              pytest.mark.usefixtures("xfail_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy']),]
+
+
+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)
+    isdtype = array_namespace(array, kernel).isdtype
+    complex_array = isdtype(array.dtype, 'complex floating')
+    complex_kernel = 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 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 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 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)
+
+    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?")
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_kernel', types)
+    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
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    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.type == dtype_output
+
+        ndimage.convolve(array, kernel, output=output)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == dtype_output
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    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
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    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
+
+    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)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    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
+
+    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'])
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    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
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    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)
+
+    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)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    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)
+
+    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.]))
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    @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('https://github.com/cupy/cupy/issues/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)
+    @pytest.mark.thread_unsafe
+    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)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @skip_xp_backends(np_only=True,
+                      reason='output=dtype is numpy-specific',
+                      exceptions=['cupy'])
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @skip_xp_backends(np_only=True,
+                      reason="output=dtype is numpy-specific",
+                      exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    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)
+
+    @skip_xp_backends(np_only=True, reason="output=dtype is numpy-specific")
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    @pytest.mark.thread_unsafe
+    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)
+
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input_and_kernel_cval(self, dtype,
+                                                       dtype_output, xp,
+                                                       num_parallel_threads):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8405")
+
+        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)
+
+    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)
+
+    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
+
+    def test_gauss03(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8403")
+
+        # 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
+
+    def test_gauss04(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        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
+
+    def test_gauss05(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        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
+
+    def test_gauss06(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    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)
+
+    @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'),
+                             [(ndimage.gaussian_filter, (), 0, 1.0),
+                              (ndimage.uniform_filter, (), 1, 3),
+                              (ndimage.minimum_filter, (), 1, 3),
+                              (ndimage.maximum_filter, (), 1, 3),
+                              (ndimage.median_filter, (), 1, 3),
+                              (ndimage.rank_filter, (1,), 1, 3),
+                              (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):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        # 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'),
+                             [(ndimage.laplace, {}),
+                              (ndimage.gaussian_gradient_magnitude,
+                               {"sigma": 1.0}),
+                              (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),))
+    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', [ndimage.correlate, 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))
+
+    @skip_xp_backends("array_api_strict",
+         reason="fancy indexing is only available in 2024 version",
+    )
+    @pytest.mark.parametrize("filter_func, size0, size, kwargs",
+                             [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss),
+                              (ndimage.uniform_filter, 1, 3, kwargs_other),
+                              (ndimage.maximum_filter, 1, 3, kwargs_other),
+                              (ndimage.minimum_filter, 1, 3, kwargs_other),
+                              (ndimage.median_filter, 1, 3, kwargs_rank),
+                              (ndimage.rank_filter, 1, 3, kwargs_rank),
+                              (ndimage.percentile_filter, 1, 3, kwargs_rank)])
+    @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2))
+    def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp):
+
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        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)
+
+
+    @pytest.mark.parametrize("filter_func, kwargs",
+                             [(ndimage.convolve, {}),
+                              (ndimage.correlate, {}),
+                              (ndimage.minimum_filter, {}),
+                              (ndimage.maximum_filter, {}),
+                              (ndimage.median_filter, {}),
+                              (ndimage.rank_filter, {"rank": 1}),
+                              (ndimage.percentile_filter, {"percentile": 30})])
+    def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        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]])
+
+
+    @pytest.mark.parametrize(
+        'filter_func, args',
+        [(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):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        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)
+
+    @pytest.mark.parametrize(
+        'filter_func, kwargs',
+        [(ndimage.convolve, {}),
+         (ndimage.correlate, {}),
+         (ndimage.minimum_filter, {}),
+         (ndimage.maximum_filter, {}),
+         (ndimage.median_filter, {}),
+         (ndimage.rank_filter, dict(rank=3)),
+         (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):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        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)
+
+    @pytest.mark.parametrize('n_mismatch', [1, 3])
+    @pytest.mark.parametrize('filter_func, kwargs, key, val',
+                             _cases_axes_tuple_length_mismatch())
+    def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func,
+                                          kwargs, key, val, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        # 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)
+    def test_prewitt01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt02(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_prewitt03(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]:
+            pytest.xfail("uint UB? XXX")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_prewitt04(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_sobel01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.",)
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel02(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_sobel03(self, dtype, xp):
+        if is_cupy(xp) and dtype in ["uint32", "uint64"]:
+            pytest.xfail("uint UB? XXX")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_sobel04(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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"])
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only",)
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    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"])
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_generic_laplace01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    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
+
+        astype = array_namespace(expected).astype
+        expected_float = astype(expected, xp.float64) if is_int_dtype else expected
+        expected = astype(xp.sqrt(expected_float), dtype)
+        xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    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
+
+        astype = array_namespace(expected).astype
+        fl_expected = astype(expected, xp.float64) if is_int_dtype else expected
+
+        expected = astype(xp.sqrt(fl_expected), dtype)
+        xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+    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)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    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)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    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]))
+
+    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)
+
+    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)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    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)
+
+    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)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_uniform06(self, dtype_array, dtype_output, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        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
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    @pytest.mark.parametrize('dtype_array', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_uniform06_complex(self, dtype_array, dtype_output, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        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
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    @skip_xp_backends("jax.numpy", reason="assignment destination is read-only")
+    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)
+
+    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)
+
+    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'])
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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'])
+
+    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)
+
+    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)
+
+    @pytest.mark.parametrize(
+        'axes', tuple(itertools.combinations(range(-3, 3), 2))
+    )
+    @pytest.mark.parametrize(
+        'filter_func, kwargs',
+        [(ndimage.minimum_filter, {}),
+         (ndimage.maximum_filter, {}),
+         (ndimage.median_filter, {}),
+         (ndimage.rank_filter, dict(rank=3)),
+         (ndimage.percentile_filter, dict(percentile=60))]
+    )
+    def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        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]
+
+        expand_dims = array_namespace(footprint).expand_dims
+        footprint_3d = expand_dims(footprint, axis=missing_axis)
+        expected = filter_func(array, footprint=footprint_3d, **kwargs)
+        xp_assert_close(output, expected)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    @skip_xp_backends("jax.numpy",
+        reason="assignment destination is read-only",
+    )
+    def test_rank06_overlap(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8406")
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+
+        asarray = array_namespace(array).asarray
+        array_copy = 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)
+
+    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)
+
+    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)
+
+        # 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)
+    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)
+
+    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)
+
+    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)
+    def test_rank12(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_rank13(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_rank14(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+    def test_rank15(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        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)
+
+    def test_rank16(self, xp):
+        # 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)
+
+    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)
+
+    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
+
+    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, reason="off-by-ones on alt backends")
+    @pytest.mark.parametrize('dtype', types)
+    def test_generic_filter1d01(self, dtype, xp):
+        weights = xp.asarray([1.1, 2.2, 3.3])
+
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not support extra_arguments")
+
+        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)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_generic_filter01(self, dtype, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not support extra_arguments")
+        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])]
+    )
+    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])]
+    )
+    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])]
+    )
+    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])]
+    )
+    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]])]
+    )
+    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]])]
+    )
+    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])]
+    )
+    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]])]
+    )
+    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])]
+    )
+    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]])]
+    )
+    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)
+
+
+def test_ticket_701(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy raises a TypeError.")
+
+    # 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)
+
+
+def test_gaussian_kernel1d(xp):
+    if is_cupy(xp):
+        pytest.skip("This test tests a private scipy utility.")
+    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)))
+
+
+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)
+
+
+def test_valid_origins(xp):
+    """Regression test for #1311."""
+    if is_cupy(xp):
+        pytest.xfail("CuPy raises a TypeError.")
+
+    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)
+
+    for filter in [ndimage.uniform_filter, ndimage.minimum_filter,
+                   ndimage.maximum_filter, ndimage.maximum_filter1d,
+                   ndimage.median_filter, ndimage.minimum_filter1d]:
+        # This should work, since for size == 3, the valid range for origin is
+        # -1 to 1.
+        list(filter(data, 3, origin=-1))
+        list(filter(data, 3, origin=1))
+        # Just check this raises an error instead of silently accepting or
+        # segfaulting.
+        assert_raises(ValueError, filter, data, 3, origin=2)
+
+
+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])
+
+@skip_xp_backends("cupy",
+                  reason="https://github.com/cupy/cupy/pull/8430",
+)
+def test_multiple_modes(xp):
+    # 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.]])
+
+    mode1 = 'reflect'
+    mode2 = ['reflect', 'reflect']
+
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, mode=mode1),
+                 ndimage.gaussian_filter(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.prewitt(arr, mode=mode1),
+                 ndimage.prewitt(arr, mode=mode2))
+    xp_assert_equal(ndimage.sobel(arr, mode=mode1),
+                 ndimage.sobel(arr, mode=mode2))
+    xp_assert_equal(ndimage.laplace(arr, mode=mode1),
+                 ndimage.laplace(arr, mode=mode2))
+    xp_assert_equal(ndimage.gaussian_laplace(arr, 1, mode=mode1),
+                 ndimage.gaussian_laplace(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.maximum_filter(arr, size=5, mode=mode1),
+                 ndimage.maximum_filter(arr, size=5, mode=mode2))
+    xp_assert_equal(ndimage.minimum_filter(arr, size=5, mode=mode1),
+                 ndimage.minimum_filter(arr, size=5, mode=mode2))
+    xp_assert_equal(ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode1),
+                 ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.uniform_filter(arr, 5, mode=mode1),
+                 ndimage.uniform_filter(arr, 5, mode=mode2))
+
+
+@skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8430")
+@skip_xp_backends("jax.numpy", reason="output array is read-only.")
+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))
+
+
+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))
+
+
+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))
+
+
+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))
+
+
+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))
+
+
+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)
+
+@skip_xp_backends("cupy",
+                  reason="https://github.com/cupy/cupy/pull/8430",
+)
+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))
+
+
+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
+
+    nnz_kw = {'as_tuple': True} if is_torch(xp) else {}
+
+    # 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, **nnz_kw)[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, **nnz_kw)[0]
+    n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+    assert n == 15
+
+
+def test_gaussian_radius(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8402")
+
+    # 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)
+
+
+def test_gaussian_radius_invalid(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8402")
+
+    # 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)
+
+
+@skip_xp_backends("jax.numpy", reason="output array is read-only")
+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, ...])
+
+    def test_correlate1d(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        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)
+
+    def test_correlate(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        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)
+
+    def test_median_filter(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        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)
+
+    def test_uniform_filter1d(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        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)
+
+    def test_minmax_filter(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        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)
+
+
+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)
+
+
+def test_uniform_filter1d_roundoff_errors(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8401")
+    # 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)
+
+
+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)
+
+
+def test_gaussian_filter(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not raise")
+
+    if not hasattr(xp, "float16"):
+        pytest.xfail(f"{xp} does not have float16")
+
+    # Test gaussian filter with xp.float16
+    # gh-8207
+    data = xp.asarray([1], dtype=xp.float16)
+    sigma = 1.0
+    with assert_raises(RuntimeError):
+        ndimage.gaussian_filter(data, sigma)
+
+
+def test_rank_filter_noninteger_rank(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not raise")
+
+    # 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)
+
+
+def test_size_footprint_both_set(xp):
+    # test for input validation, expect user warning when
+    # size and footprint is set
+    with suppress_warnings() as sup:
+        sup.filter(UserWarning,
+                   "ignoring size because footprint is set")
+        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
+        )
+
+
+@skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+def test_byte_order_median(xp):
+    """Regression test for #413: median_filter does not handle bytes orders."""
+    a = xp.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)
+
+
+@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)
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..be544eaab9ce00b2e9802cf8f9a4819c4f1d2731
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py
@@ -0,0 +1,189 @@
+import math
+import numpy as np
+
+from scipy._lib._array_api import (
+    xp_assert_equal,
+    assert_array_almost_equal,
+    assert_almost_equal,
+    is_cupy,
+)
+
+import pytest
+
+from scipy import ndimage
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+@skip_xp_backends('jax.numpy', reason="jax-ml/jax#23827")
+class TestNdimageFourier:
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+    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)])
+    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)])
+    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)])
+    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)])
+    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)])
+    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)])
+    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)])
+    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)
+
+    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)
+
+    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',
+                             [ndimage.fourier_ellipsoid,
+                              ndimage.fourier_gaussian,
+                              ndimage.fourier_uniform])
+    def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
+        if is_cupy(xp):
+           if (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.10/site-packages/scipy/ndimage/tests/test_interpolation.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..51e8441e244f46642a07102e297b4d72513514d0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py
@@ -0,0 +1,1484 @@
+import sys
+
+import numpy as np
+from numpy.testing import suppress_warnings
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close,
+    assert_array_almost_equal,
+)
+from scipy._lib._array_api import is_cupy, is_jax, _asarray, array_namespace
+
+import pytest
+from pytest import raises as assert_raises
+import scipy.ndimage as ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+eps = 1e-12
+
+ndimage_to_numpy_mode = {
+    'mirror': 'reflect',
+    'reflect': 'symmetric',
+    'grid-mirror': 'symmetric',
+    'grid-wrap': 'wrap',
+    'nearest': 'edge',
+    'grid-constant': 'constant',
+}
+
+
+class TestBoundaries:
+
+    @skip_xp_backends("cupy", reason="CuPy does not have 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))
+
+    @skip_xp_backends("cupy", reason="CuPy does not have 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))
+
+    @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))
+        newaxis = array_namespace(x).newaxis
+        y = ndimage.map_coordinates(data, x[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)[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)
+
+
+@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, 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)
+
+
+@skip_xp_backends("cupy", reason="CuPy does not have 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)
+
+        isdtype = array_namespace(data).isdtype
+        if 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 = [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], [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]]
+
+        def mapping(x):
+            return (x[0], x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (3, 2),
+                                          order=order)
+        assert_array_almost_equal(out, [[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]]
+
+        def mapping(x):
+            return (x[0] * 2, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, (1, 4),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 2, 3, 4]])
+
+    def test_geometric_transform18(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        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, [[1, 3]])
+
+    def test_geometric_transform19(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        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]]
+
+        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]]
+
+        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 = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], 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]]
+
+        def mapping(x):
+            return (1, x[0] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (2,), order=order)
+        out = out.astype(np.int32)
+        assert_array_almost_equal(out, [5, 7])
+
+    def test_geometric_transform24(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        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, [5, 7])
+
+
+@skip_xp_backends("cupy", reason="CuPy does not have 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])
+
+
+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]])
+        isdtype = array_namespace(data).isdtype
+        if 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.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
+
+
+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)
+        isdtype = array_namespace(data).isdtype
+        if 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)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform20(self, order, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8394")
+
+        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]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform21(self, order, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8394")
+
+        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 suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            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 suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            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))
+
+        concat = array_namespace(tform_original, offset_original).concat
+        tform_h1 = concat((tform_original, offset_original), axis=1)  # hstack
+        tform_h2 = 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]]))
+
+    def test_affine_transform27(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not raise")
+
+        # test valid homogeneous transformation matrix
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        concat = array_namespace(data).concat
+        tform_h1 = concat( (xp.eye(2), -xp.ones((2, 1))) , axis=1)  # vstack
+        tform_h2 = 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 suppress_warnings() as sup:
+                sup.filter(UserWarning,
+                           'The behavior of affine_transform with a 1-D array '
+                           '.* has changed')
+                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,
+        )
+
+
+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)
+        isdtype = array_namespace(data).isdtype
+        if 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)
+
+        isdtype = array_namespace(data).isdtype
+        if 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,
+        )
+
+
+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)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            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'])
+    @pytest.mark.thread_unsafe
+    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(np_only=True, reason='inplace output= is numpy-specific')
+    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)
+
+
+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)
+        isdtype = array_namespace(data).isdtype
+        if 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)
+        permute_dims = array_namespace(data).permute_dims
+        data = 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 = 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)
+        permute_dims = array_namespace(data).permute_dims
+        data = 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)
+        permute_dims = array_namespace(data).permute_dims
+        expected = 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)
+
+    def test_rotate_exact_180(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8400")
+
+        a = np.tile(xp.arange(5), (5, 1))
+        b = ndimage.rotate(ndimage.rotate(a, 180), -180)
+        xp_assert_equal(a, b)
diff --git a/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8175ba309dd223a6d0fd46df017ea1fbc797a4e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py
@@ -0,0 +1,1609 @@
+import os
+import os.path
+
+import numpy as np
+from numpy.testing import suppress_warnings
+
+from scipy._lib._array_api import (
+    is_jax,
+    is_torch,
+    array_namespace,
+    xp_assert_equal,
+    xp_assert_close,
+    assert_array_almost_equal,
+    assert_almost_equal,
+)
+
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.ndimage as ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2'
+
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+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 = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            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 = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            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 = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            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 = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            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 = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            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]))
+
+
+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'
+
+
+def test_label01(xp):
+    data = xp.ones([])
+    out, n = ndimage.label(data)
+    assert out == 1
+    assert n == 1
+
+
+def test_label02(xp):
+    data = xp.zeros([])
+    out, n = ndimage.label(data)
+    assert out == 0
+    assert n == 0
+
+
+@pytest.mark.thread_unsafe  # due to Cython fused types, see cython#6506
+def test_label03(xp):
+    data = xp.ones([1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1]))
+    assert n == 1
+
+
+def test_label04(xp):
+    data = xp.zeros([1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([0]))
+    assert n == 0
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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')
+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
+
+
+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
+
+
+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, reason='output=dtype is numpy-specific')
+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, reason='output=dtype is numpy-specific')
+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
+
+
+def test_label_output_wrong_size(xp):
+    if is_jax(xp):
+        pytest.xfail("JAX does not raise")
+
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output = xp.zeros([10], dtype=dtype)
+        # TypeError is from non-numpy arrays as output
+        assert_raises((ValueError, TypeError),
+                      ndimage.label, data, output=output)
+
+
+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
+
+@skip_xp_backends("cupy",
+                  reason="`cupyx.scipy.ndimage` does not have `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)
+
+
+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
+
+
+@skip_xp_backends("cupy", reason="cupyx.scipy.ndimage does not have find_object")
+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))]
+
+
+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
+
+    nnz_kwd = {'as_tuple': True} if is_torch(xp) else {}
+
+    truevi = {}
+    for k in true_keys:
+        truevi[k] = xp.nonzero(data == k, **nnz_kwd)
+
+    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)
+
+
+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)
+
+
+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 = xp.asarray((12*[1]+12*[2]+12*[3]), dtype=xp.int32)
+        a = xp.reshape(a, shape)
+
+        nnz_kwd = {'as_tuple': True} if is_torch(xp) else {}
+
+        unique_values = array_namespace(a).unique_values
+        trueKeys = unique_values(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, **nnz_kwd)
+            assert len(vi[k]) == len(trueNdx)
+            for vik, true_vik in zip(vi[k], trueNdx):
+                xp_assert_equal(vik, true_vik)
+
+
+def test_sum01(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([], dtype=dtype)
+        output = ndimage.sum(input)
+        assert output == 0
+
+
+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
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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
+
+
+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
+
+
+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
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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]))
+
+
+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]))
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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])
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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]))
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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]))
+
+
+def test_maximum05(xp):
+    # Regression test for ticket #501 (Trac)
+    x = xp.asarray([-3, -2, -1])
+    assert ndimage.maximum(x) == -1
+
+
+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]))
+
+
+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)
+
+
+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)
+
+
+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]))
+
+
+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]))
+
+
+def test_variance01(xp):
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([], dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                output = ndimage.variance(input)
+            assert xp.isnan(output)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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]))
+
+
+def test_standard_deviation01(xp):
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([], dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                output = ndimage.standard_deviation(input)
+            assert xp.isnan(output)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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]))
+
+
+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]))
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+def test_maximum_position07(xp):
+    # Test float labels
+    if is_torch(xp):
+        pytest.xfail("output[1] is wrong on pytorch")
+
+    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)
+
+
+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)
+
+
+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)
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+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))
+
+
+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)
+
+
+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')
+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)
+
+
+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")
+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])
+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.10/site-packages/scipy/ndimage/tests/test_morphology.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eff9a2c0f4a05295b7565761292b4ecaac007ac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py
@@ -0,0 +1,2938 @@
+import numpy as np
+from scipy._lib._array_api import (
+    is_cupy, is_numpy, is_torch, array_namespace,
+    xp_assert_close, xp_assert_equal, assert_array_almost_equal
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              pytest.mark.usefixtures("xfail_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+class TestNdimageMorphology:
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have 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)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have 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(expected, ft)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have 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'
+    )
+    @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.')
+    @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)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have 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)
+
+    def test_distance_transform_bf07(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf.")
+
+        # 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
+            )
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+
+        # 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)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+
+        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'
+    )
+    @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'
+    )
+    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
+            )
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+        elif is_torch(xp):
+            pytest.xfail("int overflow")
+
+        # 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
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        # 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'
+    )
+    @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)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        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(ref, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt4(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        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(ref, out)
+
+    def test_distance_transform_edt5(self, xp):
+        # Ticket #954 regression test
+        out = ndimage.distance_transform_edt(False)
+        assert_array_almost_equal(out, [0.])
+
+    @skip_xp_backends(
+        np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+    )
+    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
+            )
+
+    def test_generate_structure01(self, xp):
+        struct = ndimage.generate_binary_structure(0, 1)
+        assert struct == 1
+
+    def test_generate_structure02(self, xp):
+        struct = ndimage.generate_binary_structure(1, 1)
+        assert_array_almost_equal(struct, [1, 1, 1])
+
+    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]])
+
+    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]])
+
+    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)
+
+    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)
+
+    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]
+
+    @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)
+
+    @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)
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]))
+
+    @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]]))
+
+    @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]]))
+
+    @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]]))
+
+    @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]]))
+
+    @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]]))
+
+    @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]]))
+
+    @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)
+
+    @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)
+
+    @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)
+
+    @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)
+
+    @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)
+
+    def test_binary_erosion27(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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, reason='inplace out= arguments are numpy-specific'
+    )
+    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)
+
+    def test_binary_erosion29(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion30(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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, reason='inplace out= arguments are numpy-specific'
+    )
+    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)
+
+    def test_binary_erosion32(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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)
+
+    def test_binary_erosion33(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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)
+
+    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, reason='inplace out= arguments are numpy-specific'
+    )
+    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)
+
+    def test_binary_erosion36(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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, reason='inplace out= arguments are numpy-specific'
+    )
+    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)
+
+    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, reason='inplace out= arguments are numpy-specific'
+    )
+    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, reason='inplace out= arguments are numpy-specific'
+    )
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+    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)
+
+    def test_binary_dilation29(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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, reason='output= arrays are numpy-specific')
+    def test_binary_dilation30(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+        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)
+
+    def test_binary_dilation31(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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, reason='output= arrays are numpy-specific')
+    def test_binary_dilation32(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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)
+
+    def test_binary_dilation33(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+        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, reason='inplace output= arrays are numpy-specific',
+    )
+    def test_binary_dilation34(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        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)
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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
+
+    @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)
+
+    @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)
+    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)
+    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)
+
+    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)
+
+    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)
+
+    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_name', ["binary_erosion",
+                                           "binary_dilation",
+                                           "binary_opening",
+                                           "binary_closing",
+                                           "binary_hit_or_miss",
+                                           "binary_propagation",
+                                           "binary_fill_holes"])
+    def test_binary_axes(self, xp, func_name, expand_axis, origin, border_value):
+        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')
+        func = getattr(ndimage, func_name)
+        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)
+
+    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 is read-only.")
+    @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398")
+    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]])
+        )
+
+    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]])
+        )
+
+    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]])
+        )
+
+    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]]),
+        )
+
+    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]]),
+        )
+
+    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]]),
+        )
+
+    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)
+
+    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)
+
+    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(expected, output)
+
+    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(expected, output)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    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(expected, output)
+
+    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(expected, output)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    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(expected, output)
+
+    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(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    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(expected, output)
+
+    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(expected, output)
+
+    @xfail_xp_backends('cupy', reason="cupy#8399")
+    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(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    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 is read-only.")
+    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(expected, output)
+
+    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(expected, output)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8399")
+    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(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    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_name', ["grey_erosion",
+                                           "grey_dilation",
+                                           "grey_opening",
+                                           "grey_closing",
+                                           "morphological_laplace",
+                                           "morphological_gradient",
+                                           "white_tophat",
+                                           "black_tophat"])
+    def test_grey_axes(self, xp, func_name, 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'])
+        func = getattr(ndimage, func_name)
+        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)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss01(self, dtype, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("inplace output= is numpy-specific")
+
+        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(expected, out)
+
+    @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(expected, out)
+
+    @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(expected, out)
+
+
+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:
+            astype = array_namespace(dilated3x3).astype
+            self.dilated3x3 = astype(dilated3x3, xp.uint8)
+
+
+    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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+def test_binary_closing_noninteger_brute_force_passes_when_true(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    if is_cupy(xp):
+        pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+    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))
+    )
+
+
+@pytest.mark.parametrize(
+    'function',
+    ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing'],
+)
+@pytest.mark.parametrize('iterations', [1, 5])
+@pytest.mark.parametrize('brute_force', [False, True])
+def test_binary_input_as_output(function, iterations, brute_force, xp):
+    rstate = np.random.RandomState(123)
+    data = rstate.randint(low=0, high=2, size=100).astype(bool)
+    ndi_func = getattr(ndimage, function)
+
+    # input data is not modified
+    data_orig = data.copy()
+    expected = ndi_func(data, brute_force=brute_force, iterations=iterations)
+    xp_assert_equal(data, data_orig)
+
+    # data should now contain the expected result
+    ndi_func(data, brute_force=brute_force, iterations=iterations, output=data)
+    xp_assert_equal(expected, data)
+
+
+def test_binary_hit_or_miss_input_as_output(xp):
+    if not (is_numpy(xp) or is_cupy(xp)):
+        pytest.xfail("inplace output= is numpy-specific")
+
+    rstate = np.random.RandomState(123)
+    data = rstate.randint(low=0, high=2, size=100).astype(bool)
+
+    # 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(expected, data)
+
+
+def test_distance_transform_cdt_invalid_metric(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not have distance_transform_cdt")
+
+    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.10/site-packages/scipy/ndimage/tests/test_ni_support.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..426d1cf0eccd1ac0f10a90412f008f4b3463c333
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py
@@ -0,0 +1,78 @@
+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
+
+
+@pytest.mark.thread_unsafe
+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.10/site-packages/scipy/ndimage/tests/test_splines.py b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..2561ba5acef20ac340e06164bae96f187486c06a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py
@@ -0,0 +1,72 @@
+"""Tests for spline filtering."""
+import pytest
+
+import numpy as np
+from scipy._lib._array_api import assert_almost_equal
+
+from scipy import ndimage
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+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)
+
+
+@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)
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__init__.py b/venv/lib/python3.10/site-packages/scipy/odr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a44a8c133b674aea416efeb4da469241b50a547f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/__init__.py
@@ -0,0 +1,131 @@
+"""
+=================================================
+Orthogonal distance regression (:mod:`scipy.odr`)
+=================================================
+
+.. currentmodule:: scipy.odr
+
+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'))]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f158672df9e0cb1cfa5b690b9a530a3db29a46dd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..202f253e3d050714369e62be70d3e165f86c0746
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_models.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_models.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f167591762b1026809de5a2fda988946c77d61f0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_models.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_odrpack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_odrpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0691d381e2f95542ac36e26b1612a45dd19d799
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/_odrpack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/models.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/models.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36b8116bcd5f6c4f6f6b544c539058e9408d74f5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/models.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/odrpack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/odrpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41bb7e4ebdda7dbfc1769005a93ce19702dc9f79
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/__pycache__/odrpack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/_add_newdocs.py b/venv/lib/python3.10/site-packages/scipy/odr/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..e09fb6cc8c5f1523dfbeaef466a5b76bd22c01bb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/_add_newdocs.py
@@ -0,0 +1,34 @@
+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.
+
+    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.10/site-packages/scipy/odr/_models.py b/venv/lib/python3.10/site-packages/scipy/odr/_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0a8d2275dcc4698a9ea61be5871d62069be2599
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/_models.py
@@ -0,0 +1,315 @@
+""" 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.shape = (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()))
+    res.shape = (B.shape[-1], x.shape[-1])
+    return res
+
+
+def _lin_fjd(B, x):
+    b = B[1:]
+    b = np.repeat(b, (x.shape[-1],)*b.shape[-1], axis=0)
+    b.shape = x.shape
+    return b
+
+
+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.shape = (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))
+    res.shape = (B.shape[-1], x.shape[-1])
+    return res
+
+
+def _poly_fjacd(B, x, powers):
+    b = B[1:]
+    b.shape = (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)))
+    res.shape = (2, x.shape[-1])
+    return res
+
+
+def _exp_est(data):
+    # Eh.
+    return np.array([1., 1.])
+
+
+class _MultilinearModel(Model):
+    r"""
+    Arbitrary-dimensional linear model
+
+    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.
+
+    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.shape = (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
+
+    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)))
+    _ret.shape = (2,) + x.shape
+
+    return _ret
+
+
+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)))
+    _ret.shape = (3,) + x.shape
+
+    return _ret
+
+
+def _quad_est(data):
+    return (1.,1.,1.)
+
+
+class _UnilinearModel(Model):
+    r"""
+    Univariate linear model
+
+    This model is defined by :math:`y = \beta_0 x + \beta_1`
+
+    Examples
+    --------
+    We can calculate orthogonal distance regression with an 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
+
+    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.10/site-packages/scipy/odr/_odrpack.py b/venv/lib/python3.10/site-packages/scipy/odr/_odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..30d46aa3f4465f31b32e5f13f0b01b940981d489
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/_odrpack.py
@@ -0,0 +1,1154 @@
+"""
+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.
+    """
+    pass
+
+
+class OdrError(Exception):
+    """
+    Exception indicating an error in fitting.
+
+    This is raised by `~scipy.odr.odr` if an error occurs during fitting.
+    """
+    pass
+
+
+class OdrStop(Exception):
+    """
+    Exception stopping fitting.
+
+    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.
+
+    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.
+
+    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.
+
+    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 : boolean
+          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(x,beta)[l,k,i] =
+        d f_l(X,B)/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(x,beta)[l,j,i] = d f_l(X,B)/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.
+
+    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.
+
+    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")
+        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.10/site-packages/scipy/odr/models.py b/venv/lib/python3.10/site-packages/scipy/odr/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..0289b59747bb68a4954e58732ac69d7df144f5f6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/models.py
@@ -0,0 +1,20 @@
+# 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.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'Model', 'exponential', 'multilinear', 'unilinear',
+    'quadratic', 'polynomial'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="odr", module="models",
+                                   private_modules=["_models"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/odrpack.py b/venv/lib/python3.10/site-packages/scipy/odr/odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..192fb3342b7957703996957c882d44656706e41b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/odrpack.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.odr` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'odr', 'OdrWarning', 'OdrError', 'OdrStop',
+    'Data', 'RealData', 'Model', 'Output', 'ODR',
+    'odr_error', 'odr_stop'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="odr", module="odrpack",
+                                   private_modules=["_odrpack"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/odr/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9c9414c20939c5d844f717311f1c06f7c1ea48b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79715a39efdcaf517042bdafc78897df72cb3111
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/odr/tests/test_odr.py b/venv/lib/python3.10/site-packages/scipy/odr/tests/test_odr.py
new file mode 100644
index 0000000000000000000000000000000000000000..971cce6c55a84e08a182e3b25bf9a7e362937e01
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/odr/tests/test_odr.py
@@ -0,0 +1,607 @@
+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_warns,
+                           assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning,
+                       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]
+
+    @pytest.mark.thread_unsafe
+    def test_empty_data(self):
+        beta0 = [0.02, 0.0]
+        linear = Model(self.empty_data_func)
+
+        empty_dat = Data([], [])
+        assert_warns(OdrWarning, ODR,
+                     empty_dat, linear, beta0=beta0)
+
+        empty_dat = RealData([], [])
+        assert_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)
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__init__.pxd b/venv/lib/python3.10/site-packages/scipy/optimize/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..2402eeb020d34ad8b82e287e32545423911ff66c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/__init__.pxd
@@ -0,0 +1 @@
+from .optimize cimport cython_optimize
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fce4cecd22b165f9975160fe7c1ed718ed358853
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e453b94f5d42df50faf74feea1e495a38528dc9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a16f3bf9cec471b85855202a2d17a681afb1534
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_bracket.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_bracket.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b71ea55b2f83a9002b0661811284596f5f2fb5c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_bracket.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36b1be989704623ca434282afcc0b875b448ee7d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f9d3539c2bb345ab5c50c42459ef5ac74726705
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..157940a8a41f37e5c06ea9a25d8d862b6573d86c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_constraints.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_constraints.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b3c1247f558acac4ef796831fad2ff6333c5c1a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_constraints.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..95b184751b5cd0505dce117fab56d608298d51d4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..303c55c48de7d05562e16e9a42e913e7eefe0b25
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0657768b3a7410620530834ba2fca2a39a94904a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a05ed3f3406043ba869cd90f4c56dd8ac8fff23e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b897fa80a581e277656e1dbfc475ce0066565fd4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f881b25c83eea33996ee65b01680bd1dfeef102
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ebf8016dde43484aeeb663a35450887330e105d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c7e098cc99b8c0bca9b0afe33aedbf488c3d46e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ea1a46d7642e971cceaaf97b61a6e195d56de80
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ac19cb522b99a91b8712b0412afec1b31fe72ba
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d40ecf174194455e8e3c57a86319a9e075a45425
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe7bd4a3b9b4913a47c60f76f3e15a56c8d28dc5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7445b73e1c6af9e734952d12a2ab127fa898f33
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16f6156e2d18e5fa977b5b014e4c8d95826b2d74
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_rs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_rs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bcc4d64be1c12130f88c78f3e829656b232dc2f4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_rs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_simplex.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_simplex.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..976d3021e6238557ad65e6383398c3aa78564f5b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_simplex.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb67eba12239298c0e3cf16e8df4eb75c78e3286
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_util.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_milp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_milp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36c595e69b72475718fa230fb6b06917780e66e1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_milp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minimize.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minimize.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7428a144060f9a78a83bcd28ab59b24eaa84128c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minimize.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6d828002c26bfac9c193c81f0b34adc3b0555d1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nnls.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nnls.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f77d8bb19cb5b1d1c200be2340cdbf6659efeeb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nnls.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f09030fcbc453664bd9f6bfd71763f5b40fbbfb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_numdiff.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_numdiff.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7118ce44140dd052881926eb003e7708771583fd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_numdiff.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_qap.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_qap.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecfb10d937527f3a0e13a3af48e7a8db360a79f0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_qap.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc7fd09fc3be8a5cdbf5a965fc3a60b2f2cc7a2b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15b7f213a70b6f1d3e995e0801c4c5e09d1963c1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b86cfa9f0467b76f3ec928f284f4e4f9be106f50
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_shgo.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_shgo.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d4e9d03098b102d2d38aad6824ddccfcf744a3e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_shgo.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_slsqp_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_slsqp_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d50796d16c6613f98d87767df7baf768c80bb5b9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_slsqp_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_spectral.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_spectral.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d64067194da448ac71948caeaae31bae805959e3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_spectral.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_tnc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_tnc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f433595526bf3abe2b6c3de256235de1b7364a7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_tnc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04f260f8c7fe855f2c17c28b83e233ba74599845
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_dogleg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_dogleg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..906f314b12232e6506dc08dff72d37b29f6272af
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_dogleg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_exact.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_exact.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6ecc7a1124c664d639b42edccf87a91e856ebec
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_exact.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3b70fa8a06d751da01d888155149435600c7366
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c739d354ad7d00c3e4b639a65cc5bd965da5315e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_tstutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_tstutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42d7ea1b52a92d26afad6eea1a9956958e6f3756
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_tstutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_zeros_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_zeros_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dbe7289dcb7973709865cc2c5b1bf20cacdd02e7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_zeros_py.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/cobyla.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/cobyla.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd6a8066d6d618eba046b18c65bf8a2b81711803
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/cobyla.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/elementwise.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/elementwise.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7dd4fa7595e9ca4fd0271cd5dcf2f09ef6ff171
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/elementwise.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/lbfgsb.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/lbfgsb.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d5390c7bd7b1712f0443ce7c194184269931bd3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/lbfgsb.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/linesearch.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/linesearch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3416c0e993c39d14a2191f0405681636ef1d6b4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/linesearch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79b735ca7698fd105963939d5b07e35a5ef2e532
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack2.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack2.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..878f980597df8873eba39d942855fedd9e0be1f0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack2.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/moduleTNC.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/moduleTNC.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6639a35ca914d48b5d83da125207b89905ebc97
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/moduleTNC.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/nonlin.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/nonlin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2988588dc432d47874f6b4ff73f11c28b176db6f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/nonlin.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/optimize.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/optimize.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0eb56510b46c51c46310acb88f92f14d7425aa13
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/optimize.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/slsqp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/slsqp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a604aa720d784f56554d5d6d165ddcd51d4eeb9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/slsqp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/tnc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/tnc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b320f8c6509288b9a45229169cafecbc798aa8a0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/tnc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/zeros.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/zeros.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..424e86453a3c262be5f7b48854ff4dec83263a10
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/zeros.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_bracket.py b/venv/lib/python3.10/site-packages/scipy/optimize/_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..263243c612d08ebdc9939cc892771b49ac766d0c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_bracket.py
@@ -0,0 +1,713 @@
+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_default_dtype
+
+_ELIMITS = -1  # used in _bracket_root
+_ESTOPONESIDE = 2  # used in _bracket_root
+
+def _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, maxiter):
+
+    if not callable(func):
+        raise ValueError('`func` must be callable.')
+
+    if not np.iterable(args):
+        args = (args,)
+
+    xp = array_namespace(xl0)
+    xl0 = xp.asarray(xl0)[()]
+    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(xl0.dtype, "real floating"):
+        xl0 = xp.asarray(xl0, dtype=xp_default_dtype(xp))
+
+    # 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.broadcast_arrays(
+        xl0, xp.asarray(xr0), xp.asarray(xmin), xp.asarray(xmax), xp.asarray(factor))
+
+    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.asarray(1.0))
+        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, maxiter, xp
+
+
+def _bracket_root(func, xl0, xr0=None, *, xmin=None, xmax=None, factor=None,
+                  args=(), 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.
+    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, maxiter)
+    func, xl0, xr0, xmin, xmax, factor, args, maxiter, xp = temp
+
+    xs = (xl0, xr0)
+    temp = eim._initialize(func, xs, args)
+    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, maxiter):
+
+    if not callable(func):
+        raise ValueError('`func` must be callable.')
+
+    if not np.iterable(args):
+        args = (args,)
+
+    xp = array_namespace(xm0)
+    xm0 = xp.asarray(xm0)[()]
+    if (not xp.isdtype(xm0.dtype, "numeric")
+        or xp.isdtype(xm0.dtype, "complex floating")):
+        raise ValueError('`xm0` must be numeric and real.')
+    if not xp.isdtype(xm0.dtype, "real floating"):
+        xm0 = xp.asarray(xm0, dtype=xp_default_dtype(xp))
+
+    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
+    xl0, xm0, xr0, xmin, xmax, factor = xp.broadcast_arrays(
+        xp.asarray(xl0), xm0, xp.asarray(xr0), xp.asarray(xmin),
+        xp.asarray(xmax), xp.asarray(factor)
+    )
+
+    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, xp.asarray(0.5))
+        xl0 = xp.astype(xl0, xm0.dtype, copy=False)
+    if xr0_not_supplied:
+        xr0 = xm0 + xp.minimum((xmax - xm0)/16, xp.asarray(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, maxiter, xp
+
+
+def _bracket_minimum(func, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None,
+                     factor=None, args=(), 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.
+    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, maxiter)
+    func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter, xp = temp
+
+    xs = (xl0, xm0, xr0)
+    temp = eim._initialize(func, xs, args)
+    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.10/site-packages/scipy/optimize/_chandrupatla.py b/venv/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a4b70098919b9fba626bfecd5c1bcc559ab7702
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py
@@ -0,0 +1,552 @@
+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_sign, xp_copy, xp_take_along_axis
+
+# TODO:
+# - (maybe?) don't use fancy indexing assignment
+# - figure out how to replace the new `try`/`except`s
+
+
+def _chandrupatla(func, a, b, *, args=(), 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`.
+    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.
+        https://doi.org/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, xatol, xrtol,
+                           fatol, frtol, maxiter, callback)
+    func, args, xatol, xrtol, fatol, frtol, maxiter, callback = res
+
+    # Initialization
+    temp = eim._initialize(func, (a, b), args)
+    func, xs, fs, args, shape, dtype, xp = temp
+    x1, x2 = xs
+    f1, f2 = fs
+    status = xp.full_like(x1, xp.asarray(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, xp.asarray(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, 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, xatol, xrtol, fatol, frtol, maxiter, callback
+
+
+def _chandrupatla_minimize(func, x1, x2, x3, *, args=(), 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.
+    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. https://doi.org/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, xatol, xrtol,
+                           fatol, frtol, maxiter, callback)
+    func, args, xatol, xrtol, fatol, frtol, maxiter, callback = res
+
+    # Initialization
+    xs = (x1, x2, x3)
+    temp = eim._initialize(func, xs, args)
+    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, xp.asarray(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.10/site-packages/scipy/optimize/_cobyla_py.py b/venv/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e99acf373df59524f66e19f625f50b8d5d3cc76
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py
@@ -0,0 +1,316 @@
+"""
+Interface to Constrained Optimization By Linear Approximation
+
+Functions
+---------
+.. autosummary::
+   :toctree: generated/
+
+    fmin_cobyla
+
+"""
+
+import functools
+from threading import RLock
+
+import numpy as np
+from scipy.optimize import _cobyla as cobyla
+from ._optimize import (OptimizeResult, _check_unknown_options,
+    _prepare_scalar_function)
+try:
+    from itertools import izip
+except ImportError:
+    izip = zip
+
+__all__ = ['fmin_cobyla']
+
+# Workaround as _cobyla.minimize is not threadsafe
+# due to an unknown f2py bug and can segfault,
+# see gh-9658.
+_module_lock = RLock()
+def synchronized(func):
+    @functools.wraps(func)
+    def wrapper(*args, **kwargs):
+        with _module_lock:
+            return func(*args, **kwargs)
+    return wrapper
+
+@synchronized
+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 wraps a FORTRAN
+    implementation of the algorithm.
+
+    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.
+
+
+    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
+
+
+    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
+    con = tuple({'type': 'ineq', 'fun': c, 'args': consargs} for c in cons)
+
+    # options
+    opts = {'rhobeg': rhobeg,
+            'tol': rhoend,
+            'disp': disp,
+            'maxiter': maxfun,
+            'catol': catol,
+            'callback': callback}
+
+    sol = _minimize_cobyla(func, x0, args, constraints=con,
+                           **opts)
+    if disp and not sol['success']:
+        print(f"COBYLA failed to find a solution: {sol.message}")
+    return sol['x']
+
+
+@synchronized
+def _minimize_cobyla(fun, x0, args=(), constraints=(),
+                     rhobeg=1.0, tol=1e-4, maxiter=1000,
+                     disp=False, catol=2e-4, callback=None, bounds=None,
+                     **unknown_options):
+    """
+    Minimize a scalar function of one or more variables using the
+    Constrained Optimization BY Linear Approximation (COBYLA) algorithm.
+
+    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 : bool
+        Set to True to print convergence messages. If False,
+        `verbosity` is ignored as set to 0.
+    maxiter : int
+        Maximum number of function evaluations.
+    catol : float
+        Tolerance (absolute) for constraint violations
+
+    """
+    _check_unknown_options(unknown_options)
+    maxfun = maxiter
+    rhoend = tol
+    iprint = int(bool(disp))
+
+    # check constraints
+    if isinstance(constraints, dict):
+        constraints = (constraints, )
+
+    if bounds:
+        i_lb = np.isfinite(bounds.lb)
+        if np.any(i_lb):
+            def lb_constraint(x, *args, **kwargs):
+                return x[i_lb] - bounds.lb[i_lb]
+
+            constraints.append({'type': 'ineq', 'fun': lb_constraint})
+
+        i_ub = np.isfinite(bounds.ub)
+        if np.any(i_ub):
+            def ub_constraint(x):
+                return bounds.ub[i_ub] - x[i_ub]
+
+            constraints.append({'type': 'ineq', 'fun': ub_constraint})
+
+    for ic, con in enumerate(constraints):
+        # check type
+        try:
+            ctype = con['type'].lower()
+        except KeyError as e:
+            raise KeyError('Constraint %d has no type defined.' % ic) 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 != 'ineq':
+                raise ValueError(f"Constraints of type '{con['type']}' not handled by "
+                                 "COBYLA.")
+
+        # check function
+        if 'fun' not in con:
+            raise KeyError('Constraint %d has no function defined.' % ic)
+
+        # check extra arguments
+        if 'args' not in con:
+            con['args'] = ()
+
+    # m is the total number of constraint values
+    # it takes into account that some constraints may be vector-valued
+    cons_lengths = []
+    for c in constraints:
+        f = c['fun'](x0, *c['args'])
+        try:
+            cons_length = len(f)
+        except TypeError:
+            cons_length = 1
+        cons_lengths.append(cons_length)
+    m = sum(cons_lengths)
+
+    # 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)
+
+    def calcfc(x, con):
+        f = sf.fun(x)
+        i = 0
+        for size, c in izip(cons_lengths, constraints):
+            con[i: i + size] = c['fun'](x, *c['args'])
+            i += size
+        return f
+
+    def wrapped_callback(x):
+        if callback is not None:
+            callback(np.copy(x))
+
+    info = np.zeros(4, np.float64)
+    xopt, info = cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg,
+                                  rhoend=rhoend, iprint=iprint, maxfun=maxfun,
+                                  dinfo=info, callback=wrapped_callback)
+
+    if info[3] > catol:
+        # Check constraint violation
+        info[0] = 4
+
+    return OptimizeResult(x=xopt,
+                          status=int(info[0]),
+                          success=info[0] == 1,
+                          message={1: 'Optimization terminated successfully.',
+                                   2: 'Maximum number of function evaluations '
+                                      'has been exceeded.',
+                                   3: 'Rounding errors are becoming damaging '
+                                      'in COBYLA subroutine.',
+                                   4: 'Did not converge to a solution '
+                                      'satisfying the constraints. See '
+                                      '`maxcv` for magnitude of violation.',
+                                   5: 'NaN result encountered.'
+                                   }.get(info[0], 'Unknown exit status.'),
+                          nfev=int(info[1]),
+                          fun=info[2],
+                          maxcv=info[3])
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py b/venv/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..38ae0477ca38e28dda80e0bf2dd1f0905eacff6e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py
@@ -0,0 +1,72 @@
+import numpy as np
+from threading import Lock
+
+from ._optimize import _check_unknown_options
+
+
+COBYQA_LOCK = Lock()
+
+
+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/
+    """
+    from .._lib.cobyqa import minimize  # import here to avoid circular imports
+
+    _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),
+    }
+    with COBYQA_LOCK:
+        return minimize(fun, x0, args, bounds, constraints, callback, options)
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_constraints.py b/venv/lib/python3.10/site-packages/scipy/optimize/_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bae893e231eb9bd89308e441b8abf841f4605bb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_constraints.py
@@ -0,0 +1,594 @@
+"""Constraints definition for minimize."""
+import numpy as np
+from ._hessian_update_strategy import BFGS
+from ._differentiable_functions import (
+    VectorFunction, LinearVectorFunction, IdentityVectorFunction)
+from ._optimize import OptimizeWarning
+from warnings import warn, catch_warnings, simplefilter, filterwarnings
+from scipy.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 matrix}, 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 matrix, 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 set this property for all components.
+        Default is False. Has no effect for equality constraints.
+    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 matrix}, 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.
+
+    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 matrix}, 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 set this property for all components.
+        Default is False. Has no effect for equality constraints.
+    """
+    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.
+    """
+    def _input_validation(self):
+        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.
+    """
+    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 bound on a 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 bound on a 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('Constraint %d has no type defined.' % ic) 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('Constraint %d has no function defined.' % ic)
+
+    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.10/site-packages/scipy/optimize/_dcsrch.py b/venv/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8b4df4763ba4f699869431a0b6528383c2f0328
--- /dev/null
+++ b/venv/lib/python3.10/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 an 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.10/site-packages/scipy/optimize/_differentiable_functions.py b/venv/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..afbb2152c21a7837e77a6a77b3d8f1f6b0114270
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py
@@ -0,0 +1,694 @@
+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
+from scipy._lib import array_api_extra as xpx
+
+
+FD_METHODS = ('2-point', '3-point', 'cs')
+
+
+def _wrapper_fun(fun, args=()):
+    ncalls = [0]
+
+    def wrapped(x):
+        ncalls[0] += 1
+        # Send a copy because the user may overwrite it.
+        # Overwriting results in undefined behaviour because
+        # fun(self.x) will change self.x, with the two no longer linked.
+        fx = fun(np.copy(x), *args)
+        # Make sure the function returns a true scalar
+        if not np.isscalar(fx):
+            try:
+                fx = 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 wrapped, ncalls
+
+
+def _wrapper_grad(grad, fun=None, args=(), finite_diff_options=None):
+    ncalls = [0]
+
+    if callable(grad):
+        def wrapped(x, **kwds):
+            # kwds present to give function same signature as numdiff variant
+            ncalls[0] += 1
+            return np.atleast_1d(grad(np.copy(x), *args))
+        return wrapped, ncalls
+
+    elif grad in FD_METHODS:
+        def wrapped1(x, f0=None):
+            ncalls[0] += 1
+            return approx_derivative(
+                fun, x, f0=f0, **finite_diff_options
+            )
+
+        return wrapped1, ncalls
+
+
+def _wrapper_hess(hess, grad=None, x0=None, args=(), finite_diff_options=None):
+    if callable(hess):
+        H = hess(np.copy(x0), *args)
+        ncalls = [1]
+
+        if sps.issparse(H):
+            def wrapped(x, **kwds):
+                ncalls[0] += 1
+                return sps.csr_matrix(hess(np.copy(x), *args))
+
+            H = sps.csr_matrix(H)
+
+        elif isinstance(H, LinearOperator):
+            def wrapped(x, **kwds):
+                ncalls[0] += 1
+                return hess(np.copy(x), *args)
+
+        else:  # dense
+            def wrapped(x, **kwds):
+                ncalls[0] += 1
+                return np.atleast_2d(np.asarray(hess(np.copy(x), *args)))
+
+            H = np.atleast_2d(np.asarray(H))
+
+        return wrapped, ncalls, H
+    elif hess in FD_METHODS:
+        ncalls = [0]
+
+        def wrapped1(x, f0=None):
+            return approx_derivative(
+                grad, x, f0=f0, **finite_diff_options
+            )
+
+        return wrapped1, ncalls, None
+
+
+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.
+
+    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,
+                 finite_diff_bounds, epsilon=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, self._nfev = _wrapper_fun(fun, args=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
+
+        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
+        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
+
+        # Initial function evaluation
+        self._update_fun()
+
+        # Initial gradient evaluation
+        self._wrapped_grad, self._ngev = _wrapper_grad(
+            grad,
+            fun=self._wrapped_fun,
+            args=args,
+            finite_diff_options=finite_diff_options
+        )
+        self._update_grad()
+
+        # Hessian evaluation
+        if callable(hess):
+            self._wrapped_hess, self._nhev, self.H = _wrapper_hess(
+                hess, x0=x0, args=args
+            )
+            self.H_updated = True
+        elif hess in FD_METHODS:
+            self._wrapped_hess, self._nhev, self.H = _wrapper_hess(
+                hess,
+                grad=self._wrapped_grad,
+                x0=x0,
+                finite_diff_options=finite_diff_options
+            )
+            self._update_grad()
+            self.H = self._wrapped_hess(self.x, f0=self.g)
+            self.H_updated = True
+        elif isinstance(hess, HessianUpdateStrategy):
+            self.H = hess
+            self.H.initialize(self.n, 'hess')
+            self.H_updated = True
+            self.x_prev = None
+            self.g_prev = None
+            self._nhev = [0]
+
+    @property
+    def nfev(self):
+        return self._nfev[0]
+
+    @property
+    def ngev(self):
+        return self._ngev[0]
+
+    @property
+    def nhev(self):
+        return self._nhev[0]
+
+    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)
+            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 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, finite_diff_jac_sparsity,
+                 finite_diff_bounds, sparse_jacobian):
+        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
+
+        # promotes to floating
+        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
+
+        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
+            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
+            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.")
+
+        # Function evaluation
+        def fun_wrapped(x):
+            self.nfev += 1
+            return np.atleast_1d(fun(x))
+
+        def update_fun():
+            self.f = fun_wrapped(self.x)
+
+        self._update_fun_impl = update_fun
+        update_fun()
+
+        self.v = np.zeros_like(self.f)
+        self.m = self.v.size
+
+        # Jacobian Evaluation
+        if callable(jac):
+            self.J = jac(self.x)
+            self.J_updated = True
+            self.njev += 1
+
+            if (sparse_jacobian or
+                    sparse_jacobian is None and sps.issparse(self.J)):
+                def jac_wrapped(x):
+                    self.njev += 1
+                    return sps.csr_matrix(jac(x))
+                self.J = sps.csr_matrix(self.J)
+                self.sparse_jacobian = True
+
+            elif sps.issparse(self.J):
+                def jac_wrapped(x):
+                    self.njev += 1
+                    return jac(x).toarray()
+                self.J = self.J.toarray()
+                self.sparse_jacobian = False
+
+            else:
+                def jac_wrapped(x):
+                    self.njev += 1
+                    return np.atleast_2d(jac(x))
+                self.J = np.atleast_2d(self.J)
+                self.sparse_jacobian = False
+
+            def update_jac():
+                self.J = jac_wrapped(self.x)
+
+        elif jac in FD_METHODS:
+            self.J = approx_derivative(fun_wrapped, self.x, f0=self.f,
+                                       **finite_diff_options)
+            self.J_updated = True
+
+            if (sparse_jacobian or
+                    sparse_jacobian is None and sps.issparse(self.J)):
+                def update_jac():
+                    self._update_fun()
+                    self.J = sps.csr_matrix(
+                        approx_derivative(fun_wrapped, self.x, f0=self.f,
+                                          **finite_diff_options))
+                self.J = sps.csr_matrix(self.J)
+                self.sparse_jacobian = True
+
+            elif sps.issparse(self.J):
+                def update_jac():
+                    self._update_fun()
+                    self.J = approx_derivative(fun_wrapped, self.x, f0=self.f,
+                                               **finite_diff_options).toarray()
+                self.J = self.J.toarray()
+                self.sparse_jacobian = False
+
+            else:
+                def update_jac():
+                    self._update_fun()
+                    self.J = np.atleast_2d(
+                        approx_derivative(fun_wrapped, self.x, f0=self.f,
+                                          **finite_diff_options))
+                self.J = np.atleast_2d(self.J)
+                self.sparse_jacobian = False
+
+        self._update_jac_impl = update_jac
+
+        # Define Hessian
+        if callable(hess):
+            self.H = hess(self.x, self.v)
+            self.H_updated = True
+            self.nhev += 1
+
+            if sps.issparse(self.H):
+                def hess_wrapped(x, v):
+                    self.nhev += 1
+                    return sps.csr_matrix(hess(x, v))
+                self.H = sps.csr_matrix(self.H)
+
+            elif isinstance(self.H, LinearOperator):
+                def hess_wrapped(x, v):
+                    self.nhev += 1
+                    return hess(x, v)
+
+            else:
+                def hess_wrapped(x, v):
+                    self.nhev += 1
+                    return np.atleast_2d(np.asarray(hess(x, v)))
+                self.H = np.atleast_2d(np.asarray(self.H))
+
+            def update_hess():
+                self.H = hess_wrapped(self.x, self.v)
+        elif hess in FD_METHODS:
+            def jac_dot_v(x, v):
+                return jac_wrapped(x).T.dot(v)
+
+            def update_hess():
+                self._update_jac()
+                self.H = approx_derivative(jac_dot_v, self.x,
+                                           f0=self.J.T.dot(self.v),
+                                           args=(self.v,),
+                                           **finite_diff_options)
+            update_hess()
+            self.H_updated = True
+        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
+
+            def update_hess():
+                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._update_hess_impl = update_hess
+
+        if isinstance(hess, HessianUpdateStrategy):
+            def update_x(x):
+                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:
+            def update_x(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
+                self.J_updated = False
+                self.H_updated = False
+
+        self._update_x_impl = update_x
+
+    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):
+            self._update_x_impl(x)
+
+    def _update_fun(self):
+        if not self.f_updated:
+            self._update_fun_impl()
+            self.f_updated = True
+
+    def _update_jac(self):
+        if not self.J_updated:
+            self._update_jac_impl()
+            self.J_updated = True
+
+    def _update_hess(self):
+        if not self.H_updated:
+            self._update_hess_impl()
+            self.H_updated = True
+
+    def fun(self, x):
+        self._update_x(x)
+        self._update_fun()
+        return self.f
+
+    def jac(self, x):
+        self._update_x(x)
+        self._update_jac()
+        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()
+        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_matrix(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_matrix((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(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.10/site-packages/scipy/optimize/_direct_py.py b/venv/lib/python3.10/site-packages/scipy/optimize/_direct_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c01c38747dbef4b9c71e9b593316f466f484bca
--- /dev/null
+++ b/venv/lib/python3.10/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 an 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.10/site-packages/scipy/optimize/_dual_annealing.py b/venv/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb480a902c593ffee1d242d79018c9175bcc6d3a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py
@@ -0,0 +1,732 @@
+# 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.
+
+    .. versionadded:: 1.2.0
+
+    References
+    ----------
+    .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs
+        statistics. Journal of Statistical Physics, 52, 479-487 (1998).
+    .. [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.10/site-packages/scipy/optimize/_elementwise.py b/venv/lib/python3.10/site-packages/scipy/optimize/_elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..883c644dbcbbb954ea3e3c184bd610b28f05cca8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_elementwise.py
@@ -0,0 +1,801 @@
+from scipy.optimize._bracket import _bracket_root, _bracket_minimum
+from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize
+from scipy._lib._util import _RichResult
+
+
+def find_root(f, init, /, *, args=(), 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``.
+    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.
+        https://doi.org/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, **tolerances,
+                        maxiter=maxiter, callback=_callback)
+    return reformat_result(res)
+
+
+def find_minimum(f, init, /, *, args=(), tolerances=None, maxiter=100, callback=None):
+    """Find the minimum of an 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``.
+    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:
+
+    - ``xr - xl <= abs(xm)*xrtol + xatol`` or
+    - ``(fl - 2*fm + fr)/2 <= abs(fm)*frtol + fatol``.
+
+    Note that first of these differs from the termination conditions described
+    in [1]_.
+
+    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. https://doi.org/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, **tolerances,
+                                 maxiter=maxiter, callback=_callback)
+    return reformat_result(res)
+
+
+def bracket_root(f, xl0, xr0=None, *, xmin=None, xmax=None, factor=None, args=(),
+                 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``.
+    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, 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
+
+
+def bracket_minimum(f, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None,
+                     factor=None, args=(), 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``.
+    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, 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.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..426fa2565038a67cd669485576802658a2f48d8f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6917e4fa3595a6c7722b64be6578348843df6477
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b4d8d6a7abf5168b36726fbc2bcb287234e2b63
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/_highs_wrapper.py b/venv/lib/python3.10/site-packages/scipy/optimize/_highspy/_highs_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88f0fb14c627b10584995fbde17f3a0e445b0cf
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_isotonic.py b/venv/lib/python3.10/site-packages/scipy/optimize/_isotonic.py
new file mode 100644
index 0000000000000000000000000000000000000000..825576535402a9acf8bbff009a5f76282cb4f500
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_linesearch.py b/venv/lib/python3.10/site-packages/scipy/optimize/_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..31442e02d323e0f6d163505bf77dd30855ce1218
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_linesearch.py
@@ -0,0 +1,896 @@
+"""
+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`
+
+    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``.
+
+    """
+    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] Nocedal, J., & Wright, S. J. (2006). Numerical optimization.
+       In Springer Series in Operations Research and Financial Engineering.
+       (Springer Series in Operations Research and Financial Engineering).
+       Springer Nature.
+
+    """
+    _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 Wright and Nocedal, 'Numerical Optimization',
+    1999, pp. 59-61.
+
+    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.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.optimize import line_search
+
+    A 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.10/site-packages/scipy/optimize/_linprog_highs.py b/venv/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9455cf460f96b7768c28acfbba76ad9ad08eed3f
--- /dev/null
+++ b/venv/lib/python3.10/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_matrix, 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_matrix(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.10/site-packages/scipy/optimize/_linprog_ip.py b/venv/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e6bf717b4d7becd46d0046cedf5f807004898e4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py
@@ -0,0 +1,1126 @@
+"""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
+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:
+                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.
+        sparse, lstsq, sym_pos, cholesky = False, 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(Dinv, 0, 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_matrix(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.10/site-packages/scipy/optimize/_linprog_rs.py b/venv/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py
new file mode 100644
index 0000000000000000000000000000000000000000..43fed5805c4e40f0c38de91f053e3926cf1478e4
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_linprog_simplex.py b/venv/lib/python3.10/site-packages/scipy/optimize/_linprog_simplex.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47806c9a595f756b9f86d268c5c146ea86c77c6
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_lsq/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f60adcc891304e34ac9d85d108b6a232b4bf0c93
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_lsq/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..934c6de4524f57fb3271e131b9b079dac6671509
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..192c9fd055ec945fbcb1fee4cd95c5635a959a43
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/common.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbf3689aa4d6058a8ca031f819fe71d2655451b5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/common.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/dogbox.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/dogbox.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bf2fe9ae15ea904f670ce8a6a13b9868eeffcdb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/dogbox.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/least_squares.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/least_squares.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3cc6f8fe85523b2a40f09de0b93f5bf2e04ada6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/least_squares.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94783150c208019aeddffce0cb38e70713d441bb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c098d4e932e099da99d2dcffe7554b68757a3400
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1821c90149b465742521209bd6e3854c0f05b6aa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f34ead4a1fc4edbb3c2ab50a204aa9a3cc21cff
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_lsq/common.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f8117f23ec1111d5205537c59931b165e2bfdaf
--- /dev/null
+++ b/venv/lib/python3.10/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 import issparse
+from scipy.sparse.linalg import LinearOperator, aslinearoperator
+
+
+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 matrix 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 matrix 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 - a 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.10/site-packages/scipy/optimize/_lsq/dogbox.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bb5abbe79028afed7b110603a0d5dfd6affae7f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py
@@ -0,0 +1,331 @@
+"""
+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 .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):
+    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, f)
+            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
+
+    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.10/site-packages/scipy/optimize/_lsq/least_squares.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..1595e40d16a01b8355510c4721ca0fb6b5b23b4a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py
@@ -0,0 +1,972 @@
+"""Generic interface for least-squares minimization."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.sparse import issparse
+from scipy.sparse.linalg import LinearOperator
+from scipy.optimize import _minpack, OptimizeResult
+from scipy.optimize._numdiff import approx_derivative, group_columns
+from scipy.optimize._minimize import Bounds
+
+from .trf import trf
+from .dogbox import dogbox
+from .common import EPS, in_bounds, make_strictly_feasible
+
+
+TERMINATION_MESSAGES = {
+    -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, diff_step):
+    n = x0.size
+
+    if diff_step is None:
+        epsfcn = EPS
+    else:
+        epsfcn = diff_step**2
+
+    # Compute MINPACK's `diag`, which is inverse of our `x_scale` and
+    # ``x_scale='jac'`` corresponds to ``diag=None``.
+    if isinstance(x_scale, str) and x_scale == 'jac':
+        diag = None
+    else:
+        diag = 1 / x_scale
+
+    full_output = True
+    col_deriv = False
+    factor = 100.0
+
+    if jac is None:
+        if max_nfev is None:
+            # n squared to account for Jacobian evaluations.
+            max_nfev = 100 * n * (n + 1)
+        x, info, status = _minpack._lmdif(
+            fun, x0, (), full_output, ftol, xtol, gtol,
+            max_nfev, epsfcn, factor, diag)
+    else:
+        if max_nfev is None:
+            max_nfev = 100 * n
+        x, info, status = _minpack._lmder(
+            fun, jac, x0, (), full_output, col_deriv,
+            ftol, xtol, gtol, max_nfev, factor, diag)
+
+    f = info['fvec']
+
+    if callable(jac):
+        J = jac(x)
+    else:
+        J = np.atleast_2d(approx_derivative(fun, x))
+
+    cost = 0.5 * np.dot(f, f)
+    g = J.T.dot(f)
+    g_norm = norm(g, ord=np.inf)
+
+    nfev = info['nfev']
+    njev = info.get('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):
+    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
+
+
+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=1.0, 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):
+    """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. Method 'lm'
+        always uses the '2-point' scheme. 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 matrix (csr_matrix preferred for performance) or
+        a `scipy.sparse.linalg.LinearOperator`.
+    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 : array_like or '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]_).
+    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.
+    max_nfev : None or int, optional
+        Maximum number of function evaluations before the termination.
+        If None (default), the value is chosen automatically:
+
+        * For 'trf' and 'dogbox' : 100 * n.
+        * For 'lm' :  100 * n if `jac` is callable and 100 * n * (n + 1)
+          otherwise (because 'lm' counts function calls in Jacobian
+          estimation).
+
+    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 matrix}, 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.
+    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`.
+
+    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 matrix 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. Methods 'trf' and 'dogbox' do
+            not count function calls for numerical Jacobian approximation, as
+            opposed to 'lm' method.
+        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:
+
+            * -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 least-squares
+    algorithms implemented in MINPACK (lmder, lmdif). 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_matrix
+    >>> def sparsity_broyden(n):
+    ...     sparsity = lil_matrix((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)
+
+    ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method)
+
+    if method == 'trf':
+        x0 = make_strictly_feasible(x0, lb, ub)
+
+    if kwargs is None:
+        kwargs = {}
+    if tr_options is None:
+        tr_options = {}
+
+    def fun_wrapped(x):
+        return np.atleast_1d(fun(x, *args, **kwargs))
+
+    f0 = fun_wrapped(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 callable(jac):
+        J0 = jac(x0, *args, **kwargs)
+
+        if issparse(J0):
+            J0 = J0.tocsr()
+
+            def jac_wrapped(x, _=None):
+                return jac(x, *args, **kwargs).tocsr()
+
+        elif isinstance(J0, LinearOperator):
+            def jac_wrapped(x, _=None):
+                return jac(x, *args, **kwargs)
+
+        else:
+            J0 = np.atleast_2d(J0)
+
+            def jac_wrapped(x, _=None):
+                return np.atleast_2d(jac(x, *args, **kwargs))
+
+    else:  # Estimate Jacobian by finite differences.
+        if method == 'lm':
+            if jac_sparsity is not None:
+                raise ValueError("method='lm' does not support "
+                                 "`jac_sparsity`.")
+
+            if jac != '2-point':
+                warn(f"jac='{jac}' works equivalently to '2-point' for method='lm'.",
+                     stacklevel=2)
+
+            J0 = jac_wrapped = None
+        else:
+            if jac_sparsity is not None and tr_solver == 'exact':
+                raise ValueError("tr_solver='exact' is incompatible "
+                                 "with `jac_sparsity`.")
+
+            jac_sparsity = check_jac_sparsity(jac_sparsity, m, n)
+
+            def jac_wrapped(x, f):
+                J = approx_derivative(fun, x, rel_step=diff_step, method=jac,
+                                      f0=f, bounds=bounds, args=args,
+                                      kwargs=kwargs, sparsity=jac_sparsity)
+                if J.ndim != 2:  # J is guaranteed not sparse.
+                    J = np.atleast_2d(J)
+
+                return J
+
+            J0 = jac_wrapped(x0, f0)
+
+    if J0 is not None:
+        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'
+
+    if method == 'lm':
+        result = call_minpack(fun_wrapped, x0, jac_wrapped, ftol, xtol, gtol,
+                              max_nfev, x_scale, diff_step)
+
+    elif method == 'trf':
+        result = trf(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol, xtol,
+                     gtol, max_nfev, x_scale, loss_function, tr_solver,
+                     tr_options.copy(), verbose)
+
+    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(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol,
+                        xtol, gtol, max_nfev, x_scale, loss_function,
+                        tr_solver, tr_options, verbose)
+
+    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.10/site-packages/scipy/optimize/_lsq/lsq_linear.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..b077c45e40874fc63490748f75f8463bc2adb08d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py
@@ -0,0 +1,361 @@
+"""Linear least squares with bound constraints on independent variables."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.sparse import issparse, csr_matrix
+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 a 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 matrix of 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
+    -------
+    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.
+    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 matrix and bounds on the
+    variables is solved.
+
+    >>> import numpy as np
+    >>> from scipy.sparse import rand
+    >>> from scipy.optimize import lsq_linear
+    >>> rng = np.random.default_rng()
+    ...
+    >>> m = 2000
+    >>> n = 1000
+    ...
+    >>> A = rand(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_matrix(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.10/site-packages/scipy/optimize/_lsq/trf.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py
new file mode 100644
index 0000000000000000000000000000000000000000..9154bdba5b2cc41883811ba1820dfc251e515d6c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py
@@ -0,0 +1,560 @@
+"""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)
+
+
+def trf(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+        loss_function, tr_solver, tr_options, verbose):
+    # 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)
+    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)
+
+
+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):
+    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, f)
+            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
+
+    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):
+    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, f)
+            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
+
+    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.10/site-packages/scipy/optimize/_lsq/trf_linear.py b/venv/lib/python3.10/site-packages/scipy/optimize/_lsq/trf_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd752763179bcf97945c7f34ce6a9e49e85c819e
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..710d8c41decf596e7481bfb8d88d30f008d6f967
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_nnls.py b/venv/lib/python3.10/site-packages/scipy/optimize/_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..be904c90d715583faaf7751ce62b9c992e07e208
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_nnls.py
@@ -0,0 +1,97 @@
+import numpy as np
+from ._cython_nnls import _nnls
+
+
+__all__ = ['nnls']
+
+
+def nnls(A, b, maxiter=None, *, atol=None):
+    """
+    Solve ``argmin_x || Ax - b ||_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``.
+    atol: float
+        Tolerance value used in the algorithm to assess closeness to zero in
+        the projected residual ``(A.T @ (A x - b)`` entries. Increasing this
+        value relaxes the solution constraints. A typical relaxation value can
+        be selected as ``max(m, n) * np.linalg.norm(a, 1) * np.spacing(1.)``.
+        This value is not set as default since the norm operation becomes
+        expensive for large problems hence can be used only when necessary.
+
+    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 [2]_ which is an improved version of 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`
+    .. [2] : Bro, Rasmus and de Jong, Sijmen, "A Fast Non-Negativity-
+       Constrained Least Squares Algorithm", Journal Of Chemometrics, 1997,
+       :doi:`10.1002/(SICI)1099-128X(199709/10)11:5<393::AID-CEM483>3.0.CO;2-L`
+
+     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("Expected a two-dimensional array (matrix)" +
+                         f", but the shape of A is {A.shape}")
+    if len(b.shape) != 1:
+        raise ValueError("Expected a one-dimensional array (vector)" +
+                         f", but the shape of b is {b.shape}")
+
+    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 not maxiter:
+        maxiter = 3*n
+    x, rnorm, info = _nnls(A, b, maxiter)
+    if info == -1:
+        raise RuntimeError("Maximum number of iterations reached.")
+
+    return x, rnorm
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_optimize.py b/venv/lib/python3.10/site-packages/scipy/optimize/_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c0214daad371c51c5b860e4773e2bb01faf123d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_optimize.py
@@ -0,0 +1,4131 @@
+#__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
+import inspect
+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)
+from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS
+from scipy._lib._array_api import array_namespace
+from scipy._lib 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', 'slsqp', 'cobyla', 'cobyqa'}:
+        return callback  # don't wrap
+
+    sig = 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):
+    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):
+    """
+    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 an 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.
+
+    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)
+
+    # 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)
+
+    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
+
+
+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.asarray(x)
+    if xp.isdtype(x.dtype, 'integral'):
+        x = xp.astype(x, xp.asarray(1.).dtype)
+    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
+
+
+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.asarray(x)
+    if xp.isdtype(x.dtype, 'integral'):
+        x = xp.astype(x, xp.asarray(1.).dtype)
+    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
+
+
+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 = xpx.atleast_nd(x, ndim=1, xp=xp)
+    if xp.isdtype(x.dtype, 'integral'):
+        x = xp.astype(x, xp.asarray(1.).dtype)
+    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[0] = 1200 * x[0]**2 - 400 * x[1] + 2
+    diagonal[-1] = 200
+    diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
+    return H + xpx.create_diagonal(diagonal, xp=xp)
+
+
+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 = xpx.atleast_nd(x, ndim=1, xp=xp)
+    if xp.isdtype(x.dtype, 'integral'):
+        x = xp.astype(x, xp.asarray(1.).dtype)
+    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):
+            try:
+                fx = 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):
+            try:
+                fx = 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.
+
+    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
+
+    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.
+
+    """
+    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
+        finally:
+            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("         Iterations: %d" % iterations)
+            print("         Function evaluations: %d" % fcalls[0])
+
+    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 : \\*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 : integer
+        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.
+
+    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``.
+
+    See Also
+    --------
+    minimize: Interface to minimization algorithms for multivariate
+        functions. See ``method='BFGS'`` in particular.
+
+    References
+    ----------
+    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, **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.
+
+    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.shape = (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)
+
+    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("         Iterations: %d" % k)
+        print("         Function evaluations: %d" % sf.nfev)
+        print("         Gradient evaluations: %d" % sf.ngev)
+
+    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, **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.
+
+    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)
+
+    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("         Iterations: %d" % k)
+        print("         Function evaluations: %d" % sf.nfev)
+        print("         Gradient evaluations: %d" % sf.ngev)
+
+    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,
+                       **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.
+
+    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
+    )
+    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("         Iterations: %d" % k)
+            print("         Function evaluations: %d" % sf.nfev)
+            print("         Gradient evaluations: %d" % sf.ngev)
+            print("         Hessian evaluations: %d" % hcalls)
+        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 matrix
+                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("         Iterations: %d" % iter)
+        print("         Function evaluations: %d" % fcalls[0])
+    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.10/site-packages/scipy/optimize/_qap.py b/venv/lib/python3.10/site-packages/scipy/optimize/_qap.py
new file mode 100644
index 0000000000000000000000000000000000000000..03fe3b128c066adb21406021ec2e34effbf65703
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_qap.py
@@ -0,0 +1,760 @@
+import numpy as np
+import operator
+import warnings
+import numbers
+from . import (linear_sum_assignment, OptimizeResult)
+from ._optimize import _check_unknown_options
+
+from scipy._lib._util import check_random_state
+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``.
+
+            .. versionchanged:: 1.15.0
+                As part of the `SPEC-007 `_
+                transition from use of `numpy.random.RandomState` to
+                `numpy.random.Generator` is occurring. Supplying
+                `np.random.RandomState` to this function will now emit a
+                `DeprecationWarning`. In SciPy 1.17 its use will raise an exception.
+                In addition relying on global state using `np.random.seed`
+                will emit a `FutureWarning`. In SciPy 1.17 the global random number
+                generator will no longer be used.
+                Use of an int-like seed will raise a `FutureWarning`, in SciPy 1.17 it
+                will be normalized via `np.random.default_rng` rather than
+                `np.random.RandomState`.
+
+        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}.")
+
+    _spec007_transition(options.get("rng", None))
+    res = methods[method](A, B, **options)
+    return res
+
+
+def _spec007_transition(rng):
+    if isinstance(rng, np.random.RandomState):
+        warnings.warn(
+            "Use of `RandomState` with `quadratic_assignment` is deprecated"
+            " and will result in an exception in SciPy 1.17",
+            DeprecationWarning,
+            stacklevel=2
+        )
+    if ((rng is None or rng is np.random) and
+            np.random.mtrand._rand._bit_generator._seed_seq is None):
+        warnings.warn(
+            "The NumPy global RNG was seeded by calling `np.random.seed`."
+            " From SciPy 1.17, this function will no longer use the global RNG.",
+            FutureWarning,
+            stacklevel=2
+        )
+    if isinstance(rng, numbers.Integral | np.integer):
+        warnings.warn(
+            "The behavior when the rng option is an integer is changing: the value"
+            " will be normalized using np.random.default_rng beginning in SciPy 1.17,"
+            " and the resulting Generator will be used to generate random numbers.",
+            FutureWarning,
+            stacklevel=2
+        )
+
+
+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 = check_random_state(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, https://doi.org/10.1016/j.patcog.2018.09.014
+
+    """
+    _check_unknown_options(unknown_options)
+    rng = check_random_state(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.10/site-packages/scipy/optimize/_remove_redundancy.py b/venv/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb81ad1696b768d2304b2fc42a80cc9678cbde00
--- /dev/null
+++ b/venv/lib/python3.10/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 sparse matrix
+        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 matrix
+        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 matrix
+        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 matrix
+        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(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.10/site-packages/scipy/optimize/_shgo.py b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e9f37ce003ba42df054e25f03fbcdfe1478a423
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo.py
@@ -0,0 +1,1600 @@
+"""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 True 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)))
+
+        # 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
+
+        # 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
+        if self.n_sampled == 0:
+            self.C = self.sampling_function(n, dim)
+        else:
+            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.10/site-packages/scipy/optimize/_shgo_lib/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6fd1a37cf3ad81fed4e8f17fbaab82c3f5af79b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3f07f9458c81f68aed34e172a8014988de95aca
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62a33cac4d5b2e73769ac8b0098d05e158146dd5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py
new file mode 100644
index 0000000000000000000000000000000000000000..178e9daea2d03e335a6901483f574d7453fb9340
--- /dev/null
+++ b/venv/lib/python3.10/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
+
+    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
+
+    @cache
+    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 : boolean
+            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.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py b/venv/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py
new file mode 100644
index 0000000000000000000000000000000000000000..e47558ee7b9a181638841c34bb63603b5d37e221
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_slsqp_py.py b/venv/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ab66837497a6626d042d56530ead46ea134ad9c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py
@@ -0,0 +1,511 @@
+"""
+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 scipy.optimize._slsqp import slsqp
+from numpy import (zeros, array, linalg, append, concatenate, finfo,
+                   sqrt, vstack, isfinite, atleast_1d)
+from ._optimize import (OptimizeResult, _check_unknown_options,
+                        _prepare_scalar_function, _clip_x_for_func,
+                        _check_clip_x)
+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._lib import array_api_extra as xpx
+
+
+__docformat__ = "restructuredtext en"
+
+_epsilon = sqrt(finfo(float).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 : string, 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
+
+    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,
+                    **unknown_options):
+    """
+    Minimize a scalar function of one or more variables using Sequential
+    Least Squares Programming (SLSQP).
+
+    Options
+    -------
+    ftol : float
+        Precision goal for the value of f in the stopping criterion.
+    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
+        Maximum number of 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 `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.
+    """
+    _check_unknown_options(unknown_options)
+    iter = maxiter - 1
+    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('Constraint %d has no type defined.' % ic) 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('Constraint %d has no function defined.' % ic)
+
+        # 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, [atleast_1d(c['fun'](x, *c['args']))
+              for c in cons['eq']]))
+    mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args']))
+               for c in cons['ineq']]))
+    # m = The total number of constraints
+    m = meq + mieq
+    # la = The number of constraints, or 1 if there are no constraints
+    la = array([1, m]).max()
+    # n = The number of independent variables
+    n = len(x)
+
+    # Define the workspaces for SLSQP
+    n1 = n + 1
+    mineq = m - meq + n1 + n1
+    len_w = (3*n1+m)*(n1+1)+(n1-meq+1)*(mineq+2) + 2*mineq+(n1+mineq)*(n1-meq) \
+            + 2*meq + n1 + ((n+1)*n)//2 + 2*m + 3*n + 3*n1 + 1
+    len_jw = mineq
+    w = zeros(len_w)
+    jw = zeros(len_jw)
+
+    # 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 = array([(_arr_to_scalar(l), _arr_to_scalar(u))
+                      for (l, u) 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], bnds[:, 1]
+
+        # Mark infinite bounds with nans; the Fortran code understands this
+        infbnd = ~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)
+    # 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 the iteration counter and the mode value
+    mode = array(0, int)
+    acc = array(acc, float)
+    majiter = array(iter, int)
+    majiter_prev = 0
+
+    # Initialize internal SLSQP state variables
+    alpha = array(0, float)
+    f0 = array(0, float)
+    gs = array(0, float)
+    h1 = array(0, float)
+    h2 = array(0, float)
+    h3 = array(0, float)
+    h4 = array(0, float)
+    t = array(0, float)
+    t0 = array(0, float)
+    tol = array(0, float)
+    iexact = array(0, int)
+    incons = array(0, int)
+    ireset = array(0, int)
+    itermx = array(0, int)
+    line = array(0, int)
+    n1 = array(0, int)
+    n2 = array(0, int)
+    n3 = array(0, int)
+
+    # Print the header if iprint >= 2
+    if iprint >= 2:
+        print("%5s %5s %16s %16s" % ("NIT", "FC", "OBJFUN", "GNORM"))
+
+    # 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 = append(wrapped_grad(x), 0.0)
+    c = _eval_constraint(x, cons)
+    a = _eval_con_normals(x, cons, la, n, m, meq, mieq)
+
+    while 1:
+        # Call SLSQP
+        slsqp(m, meq, x, xl, xu, fx, c, g, a, acc, majiter, mode, w, jw,
+              alpha, f0, gs, h1, h2, h3, h4, t, t0, tol,
+              iexact, incons, ireset, itermx, line,
+              n1, n2, n3)
+
+        if mode == 1:  # objective and constraint evaluation required
+            fx = wrapped_fun(x)
+            c = _eval_constraint(x, cons)
+
+        if mode == -1:  # gradient evaluation required
+            g = append(wrapped_grad(x), 0.0)
+            a = _eval_con_normals(x, cons, la, n, m, meq, mieq)
+
+        if majiter > majiter_prev:
+            # call callback if major iteration has incremented
+            if callback is not None:
+                callback(np.copy(x))
+
+            # Print the status of the current iterate if iprint > 2
+            if iprint >= 2:
+                print("%5i %5i % 16.6E % 16.6E" % (majiter, sf.nfev,
+                                                   fx, linalg.norm(g)))
+
+        # If exit mode is not -1 or 1, slsqp has completed
+        if abs(mode) != 1:
+            break
+
+        majiter_prev = int(majiter)
+
+    # Optimization loop complete. Print status if requested
+    if iprint >= 1:
+        print(exit_modes[int(mode)] + "    (Exit mode " + str(mode) + ')')
+        print("            Current function value:", fx)
+        print("            Iterations:", majiter)
+        print("            Function evaluations:", sf.nfev)
+        print("            Gradient evaluations:", sf.ngev)
+
+    return OptimizeResult(x=x, fun=fx, jac=g[:-1], nit=int(majiter),
+                          nfev=sf.nfev, njev=sf.ngev, status=int(mode),
+                          message=exit_modes[int(mode)], success=(mode == 0))
+
+
+def _eval_constraint(x, cons):
+    # Compute constraints
+    if cons['eq']:
+        c_eq = concatenate([atleast_1d(con['fun'](x, *con['args']))
+                            for con in cons['eq']])
+    else:
+        c_eq = zeros(0)
+
+    if cons['ineq']:
+        c_ieq = concatenate([atleast_1d(con['fun'](x, *con['args']))
+                             for con in cons['ineq']])
+    else:
+        c_ieq = zeros(0)
+
+    # Now combine c_eq and c_ieq into a single matrix
+    c = concatenate((c_eq, c_ieq))
+    return c
+
+
+def _eval_con_normals(x, cons, la, n, m, meq, mieq):
+    # Compute the normals of the constraints
+    if cons['eq']:
+        a_eq = vstack([con['jac'](x, *con['args'])
+                       for con in cons['eq']])
+    else:  # no equality constraint
+        a_eq = zeros((meq, n))
+
+    if cons['ineq']:
+        a_ieq = vstack([con['jac'](x, *con['args'])
+                        for con in cons['ineq']])
+    else:  # no inequality constraint
+        a_ieq = zeros((mieq, n))
+
+    # Now combine a_eq and a_ieq into a single a matrix
+    if m == 0:  # no constraints
+        a = zeros((la, n))
+    else:
+        a = vstack((a_eq, a_ieq))
+    a = concatenate((a, zeros([la, 1])), 1)
+
+    return a
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_tnc.py b/venv/lib/python3.10/site-packages/scipy/optimize/_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..327fe4262e25f2f7e2c95d7e5261b6f188e72881
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_tnc.py
@@ -0,0 +1,431 @@
+# 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._lib 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,
+                  **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.
+    """
+    _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)
+    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.10/site-packages/scipy/optimize/_trlib/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trlib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..537b73b3aeb36df09863a0cd24957e5612deb030
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_trlib/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trlib/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce6c90cc855bc8f7ddcf069fc15618170113c77b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trlib/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dadc727e74e40b5200810191b21cdeda941c5f6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion.py
@@ -0,0 +1,304 @@
+"""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, **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.
+
+    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.
+    sf = _prepare_scalar_function(fun, x0, jac=jac, hess=hess, args=args)
+    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]
+    m = subproblem(x, fun, jac, hess, hessp)
+    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)
+
+        # 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("         Iterations: %d" % k)
+        print("         Function evaluations: %d" % sf.nfev)
+        print("         Gradient evaluations: %d" % sf.ngev)
+        print("         Hessian evaluations: %d" % (sf.nhev + nhessp[0]))
+
+    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.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..549cfb9760dda474cb858b7b36d236af48111067
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8da7fd8f85c49f482b0a133f2290fec167e50ae5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4178d386eaaadb95dfdb948dc17b68882513d460
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42eac68d9878b347b58d1b917564c8b22e8658ce
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30f001b01027240975942b37272a01b0bc015c65
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cb21a23ae81dfcfe192cd34af5831cf229e39cd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d2fca373e0b1f58d48b532e3ba65bf623b87b30
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/report.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/report.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c55bfcc9a253850480a72c961fdfa49e9947844
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/report.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88ca569038b01fca19e8517d0c2fbd556b0d53ce
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e9e75f04c032e5be077f9b7db210b96072092c9
--- /dev/null
+++ b/venv/lib/python3.10/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_matrix 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_matrix((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_matrix((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_matrix((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_matrix((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_matrix((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_matrix((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.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..88a9f8deb1abfaa82533eeb6308bbfbd5516ed4d
--- /dev/null
+++ b/venv/lib/python3.10/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 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.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
new file mode 100644
index 0000000000000000000000000000000000000000..580f9ccf8eab9f22d73ae41f130b2e5e541a71da
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
@@ -0,0 +1,576 @@
+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` function requested termination.",
+    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):
+    """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 : string 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.
+
+    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 : integer
+        Number of the objective function evaluations.
+    njev : integer
+        Number of the objective function gradient evaluations.
+    nhev : integer
+        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 matrix}
+        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` function requested termination.
+        * 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)
+        modified_ub = np.nextafter(bounds.ub, np.inf, where=bounds.ub < np.inf)
+        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)
+
+    # 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.10/site-packages/scipy/optimize/_trustregion_constr/projections.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..a07b836bdbad688a265ae34ce91a361fd5050eb1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py
@@ -0,0 +1,407 @@
+"""Basic linear factorizations needed by the solver."""
+
+from scipy.sparse import (bmat, csc_matrix, eye, issparse)
+from scipy.sparse.linalg import LinearOperator
+import scipy.linalg
+import scipy.sparse.linalg
+try:
+    from sksparse.cholmod import cholesky_AAt
+    sksparse_available = True
+except ImportError:
+    import warnings
+    sksparse_available = False
+import numpy as np
+from warnings import warn
+
+__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
+    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 = csc_matrix(bmat([[eye(n), A.T], [A, None]]))
+    # 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 matrix (or ndarray), shape (m, n)
+        Matrix ``A`` used in the projection.
+    method : string, 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_matrix(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 matrix.")
+        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.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..a039a7738c283f90f30fd7c4583bf9e1a8f559d5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py
@@ -0,0 +1,637 @@
+"""Equality-constrained quadratic programming solvers."""
+
+from scipy.sparse import (linalg, bmat, csc_matrix)
+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 matrix, shape (n, n)
+        Hessian matrix of the EQP problem.
+    c : array_like, shape (n,)
+        Gradient of the quadratic objective function.
+    A : sparse matrix
+        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 = csc_matrix(bmat([[H, A.T], [A, None]]))
+    # 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 a 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 a 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 a 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 matrix 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 matrix 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 matrix 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 matrix or ndarray), shape (n, n)
+        Operator for projecting ``x`` into the null space of A.
+    Y : LinearOperator,  sparse matrix, 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
+    a 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.10/site-packages/scipy/optimize/_trustregion_constr/report.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/report.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f997d663cd5ce6265e77f940622b6105362bf7
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82d04f6383a0af99bacdf2e9ae715f6b82eb30cf
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8e07f3fdede6058092bce50b83f9dd8f7474069
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9aa3931382fa5000bd0d08d3294fcd397c72228c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1eaa3841471a6f052ae775118369a1cc3a18786
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d67c75c6052efe59ba457eba437a65d9e31196e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52e866061d4a9f942dfc4ab96e1e889fe24e9be9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..452b327d02da3b3bd3fab9592bdef4d56d6aff57
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9aa57058c6523d4106b26840ef447431d615cd6
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ff3c39d649d0ac663d9b71bb906f1daac021118
--- /dev/null
+++ b/venv/lib/python3.10/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_matrix
+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_matrix(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_matrix(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_matrix(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_matrix(A)
+        np.random.seed(0)
+
+        Z, LS, Y = projections(A)
+        Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
+        for k in range(20):
+            z = np.random.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 = np.random.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_matrix(A)
+        np.random.seed(0)
+
+        Z, LS, Y = projections(A)
+        Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
+        for k in range(1):
+            z = np.random.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 = np.random.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_matrix(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.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..70e65e53b9d2389541c0aab45b94b1d30dcdd146
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
@@ -0,0 +1,645 @@
+import numpy as np
+from scipy.sparse import csc_matrix
+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_matrix([[6, 2, 1],
+                        [2, 5, 2],
+                        [1, 2, 4]])
+        A = csc_matrix([[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_matrix([[6, 2, 1],
+                        [2, 5, 2],
+                        [1, 2, 4]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[1, 2, 1, 3],
+                        [2, 0, 2, 4],
+                        [1, 2, 0, 2],
+                        [3, 4, 2, 0]])
+        A = csc_matrix([[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_matrix([[1, 2, 1, 3],
+                        [2, 0, 2, 4],
+                        [1, 2, 0, 2],
+                        [3, 4, 2, 0]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[6, 2, 1, 3],
+                        [2, 5, 2, 4],
+                        [1, 2, 4, 5],
+                        [3, 4, 5, 7]])
+        A = csc_matrix([[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_matrix([[1, 2, 1, 3],
+                        [2, 0, 2, 4],
+                        [1, 2, 0, 2],
+                        [3, 4, 2, 0]])
+        A = csc_matrix([[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.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..66fa5bd17f80a907db425c927c08e5dc0797028e
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py
new file mode 100644
index 0000000000000000000000000000000000000000..e14b3f366fba818d9174af97fa91e065bf26e826
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py
@@ -0,0 +1,361 @@
+"""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:
+            f = self.fun(x)
+            c_eq, c_ineq = self.constr(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_matrix` because of
+                # the way ``BoxConstraint``, ``NonlinearConstraint``
+                # and ``LinearConstraint`` are defined.
+                J_eq = sps.csr_matrix(J_eq)
+                J_ineq = sps.csr_matrix(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_matrix((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.10/site-packages/scipy/optimize/_trustregion_dogleg.py b/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a54abd60c703408d6c87cb5020d6781fdf0213c7
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/_tstutils.py b/venv/lib/python3.10/site-packages/scipy/optimize/_tstutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f56e835e345d66023efae81114a45ed29269f18d
--- /dev/null
+++ b/venv/lib/python3.10/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)
+#       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.10/site-packages/scipy/optimize/_zeros_py.py b/venv/lib/python3.10/site-packages/scipy/optimize/_zeros_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b96902ccbd58ed8fb6de3bbafe551f53fb8bf86
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/_zeros_py.py
@@ -0,0 +1,1395 @@
+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.
+
+    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 += (
+                        " Failed to converge after %d iterations, value is %s."
+                        % (itr + 1, 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 += (
+                            " Failed to converge after %d iterations, value is %s."
+                            % (itr + 1, 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 = ("Failed to converge after %d iterations, value is %s."
+               % (itr + 1, 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].
+    xtol : number, optional
+        The computed root ``x0`` will satisfy ``np.allclose(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.allclose(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.
+    args : tuple, optional
+        Containing extra arguments for the function `f`.
+        `f` is called by ``apply(f, (x)+args)``.
+    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.
+
+    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
+
+    See Also
+    --------
+    brentq, brenth, bisect, newton
+    fixed_point : scalar fixed-point finder
+    fsolve : n-dimensional root-finding
+
+    """
+    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].
+    xtol : number, optional
+        The computed root ``x0`` will satisfy ``np.allclose(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.allclose(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.
+    args : tuple, optional
+        Containing extra arguments for the function `f`.
+        `f` is called by ``apply(f, (x)+args)``.
+    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
+
+    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.
+
+    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]`.
+    xtol : number, optional
+        The computed root ``x0`` will satisfy ``np.allclose(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.allclose(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.
+    args : tuple, optional
+        Containing extra arguments for the function `f`.
+        `f` is called by ``apply(f, (x)+args)``.
+    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
+
+    Notes
+    -----
+    `f` must be continuous.  f(a) and f(b) must have opposite signs.
+
+    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].
+    xtol : number, optional
+        The computed root ``x0`` will satisfy ``np.allclose(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.allclose(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.
+    args : tuple, optional
+        Containing extra arguments for the function `f`.
+        `f` is called by ``apply(f, (x)+args)``.
+    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
+
+    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 = "toms748: Overriding k: ->%d" % 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.allclose(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.allclose(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.
+
+    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.
+
+    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)
+       doi = {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.10/site-packages/scipy/optimize/cobyla.py b/venv/lib/python3.10/site-packages/scipy/optimize/cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..87d111d8fc1634e54d3766a3f1c58abd37ac58cb
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/cython_optimize.pxd b/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d35f8da68b34d3a587f3a99326770d8550a2135c
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/cython_optimize/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a07250bbeb06542721480c42005307992558fced
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/cython_optimize/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..634a1406704e2787ea51869b635e663f5db3d497
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize/_zeros.pxd b/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize/_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d3c9e98f0a24d80d15d1f7052f690d608f66dd80
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd b/venv/lib/python3.10/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..0d83c80eb886846ddbbd6927e37e05812911f856
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/lbfgsb.py b/venv/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py
new file mode 100644
index 0000000000000000000000000000000000000000..866407cabb3decf0ff72239e6fd372f69f7550c0
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/minpack.py b/venv/lib/python3.10/site-packages/scipy/optimize/minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..29fddef537361d8508e6343d23b2c3c7d6d12ec6
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/minpack2.py b/venv/lib/python3.10/site-packages/scipy/optimize/minpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdb3503e0e1e4c886c89bfb62e6a2efc3ba54549
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/moduleTNC.py b/venv/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fc5884ed5c39437b7681395419d641443a1fdb8
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/nonlin.py b/venv/lib/python3.10/site-packages/scipy/optimize/nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b490b40ef790a2943d539790b45fc378df2c76
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/slsqp.py b/venv/lib/python3.10/site-packages/scipy/optimize/slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2b77d2eb447527cd91e92907e06ad53dd1ad3d8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/slsqp.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
+    'OptimizeResult',
+    'fmin_slsqp',
+    'slsqp',
+    'zeros',
+]
+
+
+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.10/site-packages/scipy/optimize/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d698878201e1f290c522d1517c946c4bf27280f0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__basinhopping.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__basinhopping.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..687bce4ed3f5a293f0f383d5b5f843bd811722e2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__basinhopping.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__differential_evolution.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__differential_evolution.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42d67183c281ee9e8c70eb603071fb4cebac124a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__differential_evolution.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f77a5ed66064b7e972526f544193a0a9e79ab730
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fcffd4d960eff68eeecb546abb352c7a2809baeb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5137f0f85752bb21d08da87da24a7374e688ffe
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..227eb7818a9cbe9363ac58fad3ef46410cfd96a5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__root.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__root.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f48db164c34d1e2c6088e3b516a234a5e683ec00
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__root.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__shgo.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__shgo.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c0c7c79680d490bc5a8228afe12f8bc40c5d3fb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__shgo.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__spectral.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__spectral.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..283eac2b050b2ec17275124db0cde6ff61d4cd35
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__spectral.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_bracket.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_bracket.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a63ea0faf493496af0ae47e54d7e2fbf242fd156
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_bracket.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..539e2828336a164514765165050d87cf1405d3c4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cobyla.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cobyla.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bad0c618fe995ac5db9c1555f750666344bfd4af
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cobyla.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cobyqa.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cobyqa.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58e62d143ac416ed74566a325afc3ec133bcd3ce
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cobyqa.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6e598d060876a106dc31575578a0146a10e720e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_constraints.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_constraints.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e2777122cdb30f94e3c1308504f39fdf4042557
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_constraints.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d6ba0668a6ecf31d6939620f51312fb6f31316e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cae85989f064e06cb3f8981efb681db754108010
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_direct.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_direct.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aeb8e9ee10f5813a7f087bb6a60f997e6913c5de
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_direct.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_extending.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_extending.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3dc9c4123abf8a8074ce464d65e8ec873a608004
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_extending.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf73050eb05e9dd6a195a849f4bd38f44d36c8ef
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d95ea45f1ffa07f0e3f640d61a5b4fd75286867
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8cb6914fee7e54b5948efacfcdf2dbbd1be5bb9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50abb7d0a49e225cb7b244e56cc9a26496ef5ce5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_least_squares.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_least_squares.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7da130959152b04d7738f20ba0f596373cf9e3cd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_least_squares.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1dbc76f8438d5a800d73cfab0d769643ade6d11f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linesearch.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linesearch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..263436133b4f0cc455d3b532d4dc96f094e1d9cb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linesearch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bdce633f9f282f1f458e86b462cca61742611e5a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ed1e4871430698ef8b808fb0fef99ffe5a2c47f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..208cdd98f1c96f8d5ddbfb6d321dc3a3b84585a6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_milp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_milp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fcc02602cf39dad35fee7d7ed8e2935829cc706
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_milp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41040976419b629fd6cb1b138af088496245a35b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minpack.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..babce913c5be9732df2945c7c984599b54e4ea63
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minpack.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_nnls.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_nnls.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6caeb660f192b3000c1a413ac718f59dfe91f9e4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_nnls.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_nonlin.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_nonlin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51fb43abf1b3700506a69f7d3c643c7f406bf406
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_nonlin.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ea0af16b2b960669a0b29db90896cb5a46af707
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb8bd13855f54affe01f119c22231b326f1c924a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_regression.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_regression.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba5030d96d6edac34d3c421cfe41e5497ac3539f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_regression.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_slsqp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_slsqp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..034a8d74b86647aa0358d0ab6fd776a5f0b1039e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_slsqp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_tnc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_tnc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c9e9e9f6ef4e8715e5b759f8a1942fa57e2034e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_tnc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5793400f2e937ab91b4f3045a8c5b1089ba85406
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0e564cb9265adde39a3da9b017e1c0ad3dfff87
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63d90a6ae981fccf7148c1b4faa95ce08b112886
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_zeros.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_zeros.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11fe95e8e316ed09c531df0ed1e55c9ddd09162b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_zeros.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx b/venv/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..d831b3c7f5dcaee71371027c7ee95aa9ee51d157
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/_cython_examples/meson.build b/venv/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..1fb210fbecb84a21518ad8828a789376410f02aa
--- /dev/null
+++ b/venv/lib/python3.10/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.0.8')
+  error('tests requires Cython >= 3.0.8')
+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.10/site-packages/scipy/optimize/tests/test__basinhopping.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..80729460ee6aa596d7dc2c398ce43ff4aacc7bff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__basinhopping.py
@@ -0,0 +1,535 @@
+"""
+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(20)
+    def test_all_nograd_minimizers(self):
+        # Test 2-D minimizations without gradient. Newton-CG requires jac=True,
+        # so not included here.
+        i = 1
+        methods = ['CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP',
+                   'Nelder-Mead', 'Powell', 'COBYLA', 'COBYQA']
+        minimizer_kwargs = copy.copy(self.kwargs_nograd)
+        for method in methods:
+            # COBYQA takes extensive amount of time on this problem
+            niter = 10 if method == 'COBYQA' else self.niter
+            minimizer_kwargs["method"] = method
+            res = basinhopping(func2d_nograd, self.x0[i],
+                               minimizer_kwargs=minimizer_kwargs,
+                               niter=niter, disp=self.disp, seed=1234)
+            tol = self.tol
+            if method == 'COBYLA':
+                tol = 2
+            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)
+        self.niter = 10
+        res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+                           niter=self.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)
+
+
+@pytest.mark.thread_unsafe
+class Test_Storage:
+    def setup_method(self):
+        self.x0 = np.array(1)
+        self.f0 = 0
+
+        minres = OptimizeResult(success=True)
+        minres.x = self.x0
+        minres.fun = self.f0
+
+        self.storage = Storage(minres)
+
+    def test_higher_f_rejected(self):
+        new_minres = OptimizeResult(success=True)
+        new_minres.x = self.x0 + 1
+        new_minres.fun = self.f0 + 1
+
+        ret = self.storage.update(new_minres)
+        minres = self.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):
+        new_minres = OptimizeResult(success=success)
+        new_minres.x = self.x0 + 1
+        new_minres.fun = self.f0 - 1
+
+        ret = self.storage.update(new_minres)
+        minres = self.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
+
+
+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.10/site-packages/scipy/optimize/tests/test__differential_evolution.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__differential_evolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f81877f08abe436211210d5bd15d876c9a7177c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__differential_evolution.py
@@ -0,0 +1,1703 @@
+"""
+Unit tests for the differential global minimization algorithm.
+"""
+import multiprocessing
+from multiprocessing.dummy import Pool as ThreadPool
+import platform
+
+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
+from scipy.sparse import csr_matrix
+from scipy import stats
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_allclose, assert_almost_equal,
+                           assert_string_equal, assert_, suppress_warnings)
+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_equal(result.x, solver.x)
+
+    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)
+        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]))
+        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
+        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)
+        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')
+        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,
+                               seed=1)
+
+    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,)
+        solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3,
+                                             maxfun=12)
+        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)
+        _, 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):
+        solver = DifferentialEvolutionSolver(rosen, self.bounds, tol=0.2,
+                                             polish=False)
+        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.
+        res = differential_evolution(rosen, self.bounds, x0=[0.2, 0.8])
+        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
+        bounds = [(0., 2.), (0., 2.)]
+        solver = DifferentialEvolutionSolver(rosen, bounds, updating='deferred')
+        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'
+        )
+        assert res.success
+
+    @pytest.mark.thread_unsafe
+    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')
+
+        # Safely forking from a multithreaded process is
+        # problematic, and deprecated in Python 3.12, so
+        # we use a slower but portable alternative
+        # see gh-19848
+        ctx = multiprocessing.get_context("spawn")
+        with ctx.Pool(2) as p:
+            # should raise a UserWarning because the updating='immediate'
+            # is being overridden by the workers keyword
+            with warns(UserWarning):
+                with DifferentialEvolutionSolver(rosen, bounds, workers=p.map) as s:
+                    solver.solve()
+            assert s._updating == 'deferred'
+
+    @pytest.mark.fail_slow(10)
+    def test_parallel(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()
+
+        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):
+        solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)])
+        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)
+
+    @pytest.mark.thread_unsafe
+    def test_constraint_solve(self):
+        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,))
+
+        # 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)
+    @pytest.mark.thread_unsafe
+    def test_impossible_constraint(self):
+        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=1, 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_matrix(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 suppress_warnings() as sup:
+            sup.filter(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
+        res = differential_evolution(
+            f, bounds, strategy='best1bin', rng=12345, 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 matrix for the LinearConstraint instead of an
+        # array
+
+        L = LinearConstraint(csr_matrix(A), -np.inf, b)
+
+        # using a lower popsize to speed the test up
+        res = differential_evolution(
+            f, bounds, strategy='best1bin', rng=1211134, constraints=(L,),
+            popsize=2, tol=0.05
+        )
+
+        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 suppress_warnings() as sup:
+            sup.filter(UserWarning)
+            res = differential_evolution(
+                f, bounds, strategy='best1bin', rng=1211134,
+                constraints=constraints, popsize=2, 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
+
+        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 suppress_warnings() as sup:
+            sup.filter(UserWarning)
+            res = differential_evolution(f, bounds, strategy='best1bin',
+                                         rng=1234, 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
+
+        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 suppress_warnings() as sup:
+            sup.filter(UserWarning)
+            res = differential_evolution(f, bounds, rng=1234,
+                                         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]))
+
+    @pytest.mark.fail_slow(10)
+    def test_L4(self):
+        # Lampinen ([5]) test problem 4
+        def f(x):
+            return np.sum(x[:3])
+
+        A = np.zeros((4, 9))
+        A[1, [4, 6]] = 0.0025, 0.0025
+        A[2, [5, 7, 4]] = 0.0025, 0.0025, -0.0025
+        A[3, [8, 5]] = 0.01, -0.01
+        A = A[1:, 1:]
+        b = np.array([1, 1, 1])
+
+        def c1(x):
+            x = np.hstack(([0], x))  # 1-indexed to match reference
+            return [x[1]*x[6] - 833.33252*x[4] - 100*x[1] + 83333.333,
+                    x[2]*x[7] - 1250*x[5] - x[2]*x[4] + 1250*x[4],
+                    x[3]*x[8] - 1250000 - x[3]*x[5] + 2500*x[5]]
+
+        L = LinearConstraint(A, -np.inf, 1)
+        N = NonlinearConstraint(c1, 0, np.inf)
+
+        bounds = [(100, 10000)] + [(1000, 10000)]*2 + [(10, 1000)]*5
+        constraints = (L, N)
+
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning)
+            res = differential_evolution(
+                f, bounds, strategy='best1bin', rng=1234,
+                constraints=constraints, popsize=3, tol=0.05
+            )
+
+        f_opt = 7049.248
+
+        x_opt = [579.306692, 1359.97063, 5109.9707, 182.0177, 295.601172,
+                217.9823, 286.416528, 395.601172]
+
+        assert_allclose(f(x_opt), f_opt, atol=0.001)
+        assert_allclose(res.fun, f_opt, atol=0.001)
+
+        # use higher tol here for 32-bit Windows, see gh-11693
+        if (platform.system() == 'Windows' and np.dtype(np.intp).itemsize < 8):
+            assert_allclose(res.x, x_opt, rtol=2.4e-6, atol=0.0035)
+        else:
+            # tolerance determined from macOS + MKL failure, see gh-12701
+            assert_allclose(res.x, x_opt, rtol=5e-6, atol=0.0024)
+
+        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]))
+
+    @pytest.mark.fail_slow(10)
+    def test_L5(self):
+        # Lampinen ([5]) test problem 5
+
+        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=1234,
+                                     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
+        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=1234,
+                                     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
+        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=1234,
+                                     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):
+        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 suppress_warnings() as sup:
+            sup.filter(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=1234, 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
+
+        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=1234,
+                                     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.thread_unsafe
+    @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)]
+        res1 = differential_evolution(rosen, bounds, updating='deferred',
+                                      rng=1)
+        res2 = differential_evolution(rosen_vec, bounds, vectorized=True,
+                                      updating='deferred', rng=1)
+
+        # 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)]
+
+        res1 = differential_evolution(rosen, bounds, updating='deferred',
+                                      rng=1, constraints=[nlc1, nlc2],
+                                      polish=False)
+        res2 = differential_evolution(rosen_vec, bounds, vectorized=True,
+                                      updating='deferred', rng=1,
+                                      constraints=[nlc1, nlc2],
+                                      polish=False)
+        # the two minimisation runs should be functionally equivalent
+        assert_allclose(res1.x, res2.x)
+
+    def test_constraint_violation_error_message(self):
+
+        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=864197532)
+        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):
+        # 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=10,
+            polish=False
+        )
+        assert solver.strategy is custom_strategy_fn
+        solver.solve()
+        assert calls[0] > 0
+
+        # check custom strategy works with updating='deferred'
+        res = differential_evolution(
+            rosen, bounds, strategy=custom_strategy_fn, updating='deferred'
+        )
+        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
+            )
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..3465be508491aae411e113167b8fdd84f6d2d70b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py
@@ -0,0 +1,416 @@
+# 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.rng = check_random_state(self.seed)
+        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):
+        lu = list(zip(*self.ld_bounds))
+        lower = np.array(lu[0])
+        upper = np.array(lu[1])
+        dim = lower.size
+        vd = VisitingDistribution(lower, upper, qv, self.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):
+        lu = list(zip(*self.ld_bounds))
+        lower = np.array(lu[0])
+        upper = np.array(lu[1])
+        vd = VisitingDistribution(lower, upper, qv, self.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)
+
+    @pytest.mark.thread_unsafe
+    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})
+
+    @pytest.mark.thread_unsafe
+    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.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b0e4097bc9aadbfd3335aa3a86d063216f2c69a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
@@ -0,0 +1,310 @@
+"""
+Unit test for Linear Programming via Simplex Algorithm.
+"""
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+from pytest import raises as assert_raises
+from scipy.optimize._linprog_util import _clean_inputs, _LPProblem
+from scipy._lib._util import VisibleDeprecationWarning
+from copy import deepcopy
+from datetime import date
+
+
+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]
+    A = np.random.rand(4, 4)
+    bad2D = [[1, 2], [3, 4]]
+    bad3D = np.random.rand(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():
+    bad = np.random.rand(4, 4).ravel()
+    cb = np.random.rand(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]
+
+    Agood = np.random.rand(m, n)
+    Abad = np.random.rand(m, n + 1)
+    bgood = np.random.rand(m)
+    bbad = np.random.rand(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 np.testing.suppress_warnings() as sup:
+        sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged")
+        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():
+    lp = _LPProblem(
+        c=[[1, 2]],
+        A_ub=np.random.rand(2, 2),
+        b_ub=[[1], [2]],
+        A_eq=np.random.rand(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 np.testing.suppress_warnings() as sup:
+        sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged")
+        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.10/site-packages/scipy/optimize/tests/test__numdiff.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..21fcf36b01f480ea23e15b67e4bebb1270d63c3b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py
@@ -0,0 +1,841 @@
+import math
+from itertools import product
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_
+from pytest import raises as assert_raises
+
+from scipy.sparse import csr_matrix, csc_matrix, lil_matrix
+
+from scipy.optimize._numdiff import (
+    _adjust_scheme_to_bounds, approx_derivative, check_derivative,
+    group_columns, _eps_for_method, _compute_absolute_step)
+
+
+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_matrix, csc_matrix, lil_matrix]:
+        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
+        jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
+                                       method='2-point')
+        jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0)
+        jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
+                                       method='cs')
+        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)
+
+    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)
+        jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
+                                       method='cs')
+        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.
+        np.random.seed(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 = np.random.random(100).astype(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)
+
+        # 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
+
+    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):
+        np.random.seed(0)
+        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
+
+    def test_all(self):
+        A = self.structure(self.n)
+        order = np.arange(self.n)
+        groups_1 = group_columns(A, order)
+        np.random.shuffle(order)
+        groups_2 = group_columns(A, order)
+
+        for method, groups, l, u in product(
+                ['2-point', '3-point', 'cs'], [groups_1, groups_2],
+                [-np.inf, self.lb], [np.inf, self.ub]):
+            J = approx_derivative(self.fun, self.x0, method=method,
+                                  bounds=(l, u), sparsity=(A, groups))
+            assert_(isinstance(J, csr_matrix))
+            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))
+            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_matrix(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)
+        np.random.seed(1)
+        for i in range(10):
+            p = np.random.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))
+        np.random.seed(1)
+        for i in range(10):
+            p = np.random.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)
+        np.random.seed(1)
+        for i in range(10):
+            p = np.random.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)
+        np.random.seed(1)
+        for i in range(10):
+            p = np.random.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)
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__remove_redundancy.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..817282011699dea333042a4173f65c999a2925fc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__remove_redundancy.py
@@ -0,0 +1,228 @@
+"""
+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_matrix
+
+
+def setup_module():
+    np.random.seed(2017)
+
+
+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 test_no_redundancy(self):
+        m, n = 10, 10
+        A0 = np.random.rand(m, n)
+        b0 = np.random.rand(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 = np.random.rand(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 = np.random.rand(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 = np.random.rand(m, n)
+        b0 = np.random.rand(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 = np.random.rand(m, n)
+        b0 = np.random.rand(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 = np.random.rand(m, n)
+        b0 = np.random.rand(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):
+        np.random.seed(2032)
+        m, n = 20, 10
+        A0 = np.random.rand(m, n)
+        b0 = np.random.rand(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 = np.random.rand(m, n)
+        b0 = np.random.rand(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 = np.random.rand(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):
+        np.random.seed(2013)
+        m, n = 20, 5
+        p = 0.1
+        A = np.random.rand(m, n)
+        A[np.random.rand(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):
+        np.random.seed(2017)
+        m, n = 20, 50
+        p = 0.05
+        A = np.random.rand(m, n)
+        A[np.random.rand(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):
+        np.random.seed(2017)
+        m, n = 100, 100
+        p = 0.01
+        A = np.random.rand(m, n)
+        A[np.random.rand(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_matrix(A), b)
+        A1, b1, status, message = rr_res
+        return A1.toarray(), b1, status, message
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__root.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__root.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e2f45a10d3d976d02be18084d241adea8612b05
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__root.py
@@ -0,0 +1,124 @@
+"""
+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')
+
+    @pytest.mark.thread_unsafe
+    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.10/site-packages/scipy/optimize/tests/test__shgo.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..82efb74beee92eacc75f64c6c705374fa5ada322
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__shgo.py
@@ -0,0 +1,1156 @@
+import logging
+import sys
+
+import numpy as np
+import time
+from multiprocessing import Pool
+from numpy.testing import assert_allclose, IS_PYPY
+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)
+from scipy.optimize._constraints import new_constraint_to_old
+from scipy.optimize._shgo import SHGO
+
+
+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)
+
+    @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])
+
+    @pytest.mark.xfail(IS_PYPY and sys.platform == 'win32',
+            reason="Failing and fix in PyPy not planned (see gh-18632)")
+    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
+
+        shgo(
+            func,
+            bounds=[[-1, 1], [1, 2]],
+            n=100, iters=5,
+            sampling_method="sobol",
+            minimizer_kwargs={'method': 'SLSQP', 'jac': True}
+        )
+
+        # 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)
+
+    @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)
+
+    @pytest.mark.thread_unsafe
+    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.10/site-packages/scipy/optimize/tests/test__spectral.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b4dc52cc20caf0206fe53933d4dfc6d0fbb2c34
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test__spectral.py
@@ -0,0 +1,226 @@
+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
+    np.random.seed(1234)
+    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.10/site-packages/scipy/optimize/tests/test_bracket.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3a47fc005a2af6bbd02465634fdb72fa131f8f8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_bracket.py
@@ -0,0 +1,906 @@
+import pytest
+
+import numpy as np
+
+from scipy.optimize._bracket import _ELIMITS
+from scipy.optimize.elementwise import bracket_root, bracket_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, array_namespace)
+from scipy._lib._array_api import xp_ravel
+from scipy.conftest import array_api_compatible
+
+
+# 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
+
+
+array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+jax_skip_reason = 'JAX arrays do not support item assignment.'
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy', reason=jax_skip_reason)
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+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))
+            xp_assert_equal(res_attr.shape, shape)
+
+        xp_test = array_namespace(xp.asarray(1.))
+        assert res.success.dtype == xp_test.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)
+        xp_test = array_namespace(xp.asarray(1.))
+
+        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_test.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, 'hello')
+        with pytest.raises(ValueError, match=message):
+            _bracket_root(lambda x: x, -4, 4, xmin=np)
+        with pytest.raises(ValueError, match=message):
+            _bracket_root(lambda x: x, -4, 4, xmax=object())
+        with pytest.raises(ValueError, match=message):
+            _bracket_root(lambda x: x, -4, 4, factor=sum)
+
+        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
+        xp_test = array_namespace(xp.asarray(1.))
+
+        # Test that integers are not passed to `f`
+        # (otherwise this would overflow)
+        def f(x):
+            assert xp_test.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.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy', reason=jax_skip_reason)
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+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.nan,
+                     lambda x: x**2]
+
+            return [funcs[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)
+        xp_test = array_namespace(xp.asarray(1.))
+        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_test.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='hello')
+        with pytest.raises(ValueError, match=message):
+            _bracket_minimum(lambda x: x**2, xp.asarray(-4),
+                             xr0='farcical aquatic ceremony')
+        with pytest.raises(ValueError, match=message):
+            _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmin=np)
+        with pytest.raises(ValueError, match=message):
+            _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmax=object())
+        with pytest.raises(ValueError, match=message):
+            _bracket_minimum(lambda x: x**2, xp.asarray(-4), factor=sum)
+
+        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 = "shape mismatch: objects cannot be broadcast"
+        # raised by `xp.broadcast, but the traceback is readable IMO
+        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=xl0, xr0=xr0, xmin=xmin,
+                               xmax=xmax, factor=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))
+            xp_assert_equal(res_attr.shape, shape)
+
+        xp_test = array_namespace(xp.asarray(1.))
+        assert res.success.dtype == xp_test.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.
+        xp_test = array_namespace(xp.asarray(1.))
+
+        # Test that integers are not passed to `f`
+        # (otherwise this would overflow)
+        def f(x):
+            assert xp_test.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)
+        assert xmin == result.xl
+
+    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)
+        assert xmax == result.xr
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_chandrupatla.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcc2ae1a70be2883a3d2346a1cb8d95d8ac027fa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_chandrupatla.py
@@ -0,0 +1,984 @@
+import math
+import pytest
+import numpy as np
+
+from scipy import stats, special
+import scipy._lib._elementwise_iterative_method as eim
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import array_namespace, is_cupy, is_numpy, xp_ravel, xp_size
+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
+from .test_zeros import TestScalarRootFinders
+
+
+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_root = _wrap_chandrupatla(find_root)
+_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)
+]
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('jax.numpy',
+                              reason='JAX arrays do not support item assignment.')
+@pytest.mark.skip_xp_backends('array_api_strict',
+                              reason='Currently uses fancy indexing assignment.')
+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.)
+        xp_test = array_namespace(loc)  # need xp.stack
+
+        @_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_test.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_test.isdtype(res.success.dtype, 'bool')
+        assert xp_test.isdtype(res.status.dtype, 'integral')
+        assert xp_test.isdtype(res.nfev.dtype, 'integral')
+        assert xp_test.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), 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))
+
+        xp_test = array_namespace(loc)  # need astype
+        def f(x, loc):
+            assert x.dtype == dtype
+            return xp_test.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
+        xp_test = array_namespace(xp.asarray(1.))  # need `xp.newaxis`
+        loc = xp.linspace(-1, 1, 6)[:, xp_test.newaxis]
+        brackets = xp.asarray(list(permutations([-5, 0, 5]))).T
+        res = _chandrupatla_minimize(self.f, *brackets, args=(loc,))
+        assert xp.all(xp.isclose(res.x, loc) | (res.fun == self.f(loc, loc)))
+        ref = res.x[:, 0]  # all columns should be the same
+        xp_test = array_namespace(loc)  # need `xp.broadcast_arrays
+        xp_assert_close(*xp_test.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`
+        xp_test = array_namespace(xp.asarray(1.))  # need `xp.isdtype`
+        def f(x):
+            assert xp_test.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)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('array_api_strict',
+                              reason='Currently uses fancy indexing assignment.')
+@pytest.mark.skip_xp_backends('jax.numpy',
+                              reason='JAX arrays do not support item assignment.')
+@pytest.mark.skip_xp_backends('cupy',
+                              reason='cupy/cupy#8391')
+class TestChandrupatla(TestScalarRootFinders):
+
+    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 = _chandrupatla_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
+        xp_test = array_namespace(p_xp)  # need xp.bool
+
+        @np.vectorize
+        def chandrupatla_single(p):
+            return _chandrupatla_root(self.f, -5, 5, args=(p,))
+
+        def f(*args, **kwargs):
+            f.f_evals += 1
+            return self.f(*args, **kwargs)
+        f.f_evals = 0
+
+        res = _chandrupatla_root(f, xp.asarray(-5.), xp.asarray(5.), args=args_xp)
+        refs = chandrupatla_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_fun = [ref.fun for ref in refs]
+        ref_fun = xp.reshape(xp.asarray(ref_fun, dtype=dtype), shape)
+        xp_assert_close(res.fun, ref_fun, atol=1e-15)
+        xp_assert_equal(res.fun, 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_test.bool), shape)
+        xp_assert_equal(res.success, ref_success)
+
+        ref_flag = [ref.status for ref in refs]
+        ref_flag = xp.reshape(xp.asarray(ref_flag, dtype=xp.int32), shape)
+        xp_assert_equal(res.status, ref_flag)
+
+        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.xl for ref in refs]
+        ref_xl = xp.reshape(xp.asarray(ref_xl, dtype=dtype), shape)
+        xp_assert_close(res.xl, ref_xl)
+
+        ref_xr = [ref.xr for ref in refs]
+        ref_xr = xp.reshape(xp.asarray(ref_xr, dtype=dtype), shape)
+        xp_assert_close(res.xr, ref_xr)
+
+        xp_assert_less(res.xl, res.xr)
+        finite = xp.isfinite(res.x)
+        assert xp.all((res.x[finite] == res.xl[finite])
+                      | (res.x[finite] == res.xr[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.fl for ref in refs]
+        ref_fl = xp.reshape(xp.asarray(ref_fl, dtype=dtype), shape)
+        xp_assert_close(res.fl, ref_fl, atol=atol)
+        xp_assert_equal(res.fl, self.f(res.xl, *args_xp))
+
+        ref_fr = [ref.fr for ref in refs]
+        ref_fr = xp.reshape(xp.asarray(ref_fr, dtype=dtype), shape)
+        xp_assert_close(res.fr, ref_fr, atol=atol)
+        xp_assert_equal(res.fr, self.f(res.xr, *args_xp))
+
+        assert xp.all(xp.abs(res.fun[finite]) ==
+                      xp.minimum(xp.abs(res.fl[finite]),
+                                 xp.abs(res.fr[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 = _chandrupatla_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, xatol=0, xrtol=0, fatol=0, frtol=0)
+
+        kwargs = kwargs0.copy()
+        kwargs['xatol'] = 1e-3
+        res1 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(res1.xr - res1.xl, xp.full_like(p, xp.asarray(1e-3)))
+        kwargs['xatol'] = 1e-6
+        res2 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(res2.xr - res2.xl, xp.full_like(p, xp.asarray(1e-6)))
+        xp_assert_less(res2.xr - res2.xl, res1.xr - res1.xl)
+
+        kwargs = kwargs0.copy()
+        kwargs['xrtol'] = 1e-3
+        res1 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(res1.xr - res1.xl, 1e-3 * xp.abs(res1.x))
+        kwargs['xrtol'] = 1e-6
+        res2 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(res2.xr - res2.xl, 1e-6 * xp.abs(res2.x))
+        xp_assert_less(res2.xr - res2.xl, res1.xr - res1.xl)
+
+        kwargs = kwargs0.copy()
+        kwargs['fatol'] = 1e-3
+        res1 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(xp.abs(res1.fun), xp.full_like(p, xp.asarray(1e-3)))
+        kwargs['fatol'] = 1e-6
+        res2 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(xp.abs(res2.fun), xp.full_like(p, xp.asarray(1e-6)))
+        xp_assert_less(xp.abs(res2.fun), xp.abs(res1.fun))
+
+        kwargs = kwargs0.copy()
+        kwargs['frtol'] = 1e-3
+        x1, x2 = bracket
+        f0 = xp.minimum(xp.abs(self.f(x1, *args)), xp.abs(self.f(x2, *args)))
+        res1 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(xp.abs(res1.fun), 1e-3*f0)
+        kwargs['frtol'] = 1e-6
+        res2 = _chandrupatla_root(self.f, *bracket, **kwargs)
+        xp_assert_less(xp.abs(res2.fun), 1e-6*f0)
+        xp_assert_less(xp.abs(res2.fun), xp.abs(res1.fun))
+
+    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.fun = res
+            return res
+        f.x = None
+        f.fun = None
+
+        res = _chandrupatla_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.xl, res.xr) == bracket
+            else:
+                changed = (((res.xl == callback.xl) & (res.xr != callback.xr))
+                           | ((res.xl != callback.xl) & (res.xr == callback.xr)))
+                assert xp.all(changed)
+
+            callback.xl = res.xl
+            callback.xr = res.xr
+            assert res.status == eim._EINPROGRESS
+            xp_assert_equal(self.f(res.xl, p), res.fl)
+            xp_assert_equal(self.f(res.xr, p), res.fr)
+            xp_assert_equal(self.f(res.x, p), res.fun)
+            if callback.iter == maxiter:
+                raise StopIteration
+        callback.iter = -1  # callback called once before first iteration
+        callback.res = None
+        callback.xl = None
+        callback.xr = None
+
+        res2 = _chandrupatla_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.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 = _chandrupatla_root(f, *bracket, xrtol=4e-10, xatol=1e-5)
+        xp_assert_close(res.fun, 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 = _chandrupatla_root(f, a, b, args=(root,), xatol=1e-3)
+        try:
+            xp_assert_close(res.x, root, atol=1e-3)
+        except AssertionError:
+            assert res.x.dtype == dtype
+            xp.all(res.fun == 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)
+            _chandrupatla_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)
+            _chandrupatla_root(func, *bracket)
+
+        # raised by `np.broadcast, but the traceback is readable IMO
+        message = "...not be broadcast..."  # all messages include this part
+        with pytest.raises((ValueError, RuntimeError), match=message):
+            bracket = xp.asarray([-2, -3]), xp.asarray([3, 4, 5])
+            _chandrupatla_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])
+            _chandrupatla_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):
+            _chandrupatla_root(func, *bracket, xatol=-1)
+        with pytest.raises(ValueError, match=message):
+            _chandrupatla_root(func, *bracket, xrtol=xp.nan)
+        with pytest.raises(ValueError, match=message):
+            _chandrupatla_root(func, *bracket, fatol='ekki')
+        with pytest.raises(ValueError, match=message):
+            _chandrupatla_root(func, *bracket, frtol=xp.nan)
+
+        message = '`maxiter` must be a non-negative integer.'
+        with pytest.raises(ValueError, match=message):
+            _chandrupatla_root(func, *bracket, maxiter=1.5)
+        with pytest.raises(ValueError, match=message):
+            _chandrupatla_root(func, *bracket, maxiter=-1)
+
+        message = '`callback` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            _chandrupatla_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 = _chandrupatla_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)
+        xp_test = array_namespace(a)  # need isdtype
+        def f(x):
+            assert xp_test.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 = _chandrupatla_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 = _chandrupatla_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 = _chandrupatla_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 = _chandrupatla_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.xl, a)
+        xp_assert_equal(res.xr, 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 = _chandrupatla_root(f, -b, -a, maxiter=0)
+        xp_assert_equal(res.x, -a)
+
+        # Test maxiter = 1
+        res = _chandrupatla_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 = _chandrupatla_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.10/site-packages/scipy/optimize/tests/test_cobyla.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd27eb9baa27433d1f801e8582dd2e8d29db3da2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyla.py
@@ -0,0 +1,166 @@
+import math
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_, assert_array_equal
+import pytest
+
+from scipy.optimize import fmin_cobyla, minimize, Bounds
+
+
+class TestCobyla:
+    def setup_method(self):
+        self.x0 = [4.95, 0.66]
+        self.solution = [math.sqrt(25 - (2.0/3)**2), 2.0/3]
+        self.opts = {'disp': False, 'rhobeg': 1, 'tol': 1e-5,
+                     '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)
+
+    @pytest.mark.xslow(True, reason='not slow, but noisy so only run rarely')
+    def test_simple(self, capfd):
+        # 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=True)
+        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
+
+        callback = Callback()
+
+        # Minimize with method='COBYLA'
+        cons = ({'type': 'ineq', 'fun': self.con1},
+                {'type': 'ineq', 'fun': self.con2})
+        sol = minimize(self.fun, self.x0, method='cobyla', constraints=cons,
+                       callback=callback, 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_(sol.nfev == callback.n_calls,
+                "Callback is not called exactly once for every function eval.")
+        assert_array_equal(
+            sol.x,
+            callback.last_x,
+            "Last design vector sent to the callback is not equal to returned value.",
+        )
+
+    def test_minimize_constraint_violation(self):
+        rng = np.random.RandomState(1234)
+        pb = rng.rand(10, 10)
+        spread = rng.rand(10)
+
+        def p(w):
+            return pb.dot(w)
+
+        def f(w):
+            return -(w * spread).sum()
+
+        def c1(w):
+            return 500 - abs(p(w)).sum()
+
+        def c2(w):
+            return 5 - abs(p(w).sum())
+
+        def c3(w):
+            return 5 - abs(p(w)).max()
+
+        cons = ({'type': 'ineq', 'fun': c1},
+                {'type': 'ineq', 'fun': c2},
+                {'type': 'ineq', 'fun': c3})
+        w0 = np.zeros((10,))
+        sol = minimize(f, w0, method='cobyla', constraints=cons,
+                       options={'catol': 1e-6})
+        assert_(sol.maxcv > 1e-6)
+        assert_(not sol.success)
+
+
+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.10/site-packages/scipy/optimize/tests/test_cobyqa.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf16af71625c4d476353407f9708c981915b098a
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_constraint_conversion.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_constraint_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..c33183d5cb4e7ccaf4d755cbd2d8b28afaf46395
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_constraint_conversion.py
@@ -0,0 +1,286 @@
+"""
+Unit test for constraint conversion
+"""
+
+import numpy as np
+from numpy.testing import (assert_array_almost_equal,
+                           assert_allclose, assert_warns, suppress_warnings)
+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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.0")
+            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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.0")
+            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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.0")
+            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, num_parallel_threads):
+        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 suppress_warnings() as sup:
+                    sup.filter(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)
+            if num_parallel_threads == 1:
+                assert_allclose(funs['cobyqa'], funs['trust-constr'],
+                                rtol=1e-4)
+
+    @pytest.mark.fail_slow(20)
+    def test_individual_constraint_objects(self, num_parallel_threads):
+        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 suppress_warnings() as sup:
+                    sup.filter(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)
+            if num_parallel_threads == 1:
+                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 suppress_warnings() as sup:
+                    sup.filter(UserWarning)
+                    result = minimize(fun, x0, method=method, constraints=con)
+                    funs[method] = result.fun
+            assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3)
+            if num_parallel_threads == 1:
+                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 suppress_warnings() as sup:
+                sup.filter(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)
+
+    @pytest.mark.thread_unsafe
+    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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.0")
+            assert_warns(OptimizeWarning, minimize, fun, (2, 0, 1),
+                         method=self.method, bounds=bnds, constraints=cons)
+
+    @pytest.mark.thread_unsafe
+    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:
+            assert_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 suppress_warnings() as sup:
+                sup.filter(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.10/site-packages/scipy/optimize/tests/test_constraints.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c4186ba7b6dd6f56b89e2f39add9eb16e6beccb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_constraints.py
@@ -0,0 +1,255 @@
+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_matrix((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])
+
+    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.10/site-packages/scipy/optimize/tests/test_cython_optimize.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_cython_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f859c1143eb6b63c439fe278bfdd4fdaa15410f
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_differentiable_functions.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..cac12af0033c09c3fbf73c52a9c2cb52b84d8239
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_differentiable_functions.py
@@ -0,0 +1,805 @@
+import pytest
+import platform
+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.sparse import csr_matrix
+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)
+
+    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)
+
+    @pytest.mark.thread_unsafe
+    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
+
+
+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)
+        approx = VectorFunction(ex.fun, x0, '2-point', ex.hess, None, None,
+                                (-np.inf, np.inf), None)
+        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_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)
+
+    @pytest.mark.thread_unsafe
+    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_LinearVectorFunction():
+    A_dense = np.array([
+        [-1, 2, 0],
+        [0, 4, 2]
+    ])
+    x0 = np.zeros(3)
+    A_sparse = csr_matrix(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)))
+
+
+@pytest.mark.skipif(
+    platform.python_implementation() == "PyPy",
+    reason="assert_deallocate not available on PyPy"
+)
+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
+
+
+@pytest.mark.skipif(
+    platform.python_implementation() == "PyPy",
+    reason="assert_deallocate not available on PyPy"
+)
+@pytest.mark.xfail(reason="TODO remove reference cycle from VectorFunction")
+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
+
+
+@pytest.mark.skipif(
+    platform.python_implementation() == "PyPy",
+    reason="assert_deallocate not available on PyPy"
+)
+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_matrix(A_dense)
+    with assert_deallocated(lambda: LinearVectorFunction(A_sparse, x0, None)):
+        pass
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_direct.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_direct.py
new file mode 100644
index 0000000000000000000000000000000000000000..835d3164c8d547599a507550dcc7629e7d327394
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_direct.py
@@ -0,0 +1,321 @@
+"""
+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)
+
+    @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.10/site-packages/scipy/optimize/tests/test_extending.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..279cac794e5f453fee52f19026f96eb530259485
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2434e92434ff2ecc74ce2e8b8119632207fd0853
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_isotonic_regression.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_isotonic_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49c56db5b4470c1e4e0f787df52c80eb055c120
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e4452cd61c5400c13f4f239055352bae754ad7e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py
@@ -0,0 +1,43 @@
+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)
+
+
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee47f45509c86968b9b551eb8740ad301fd37958
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py
@@ -0,0 +1,122 @@
+import numpy as np
+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
+    nbd = np.full(shape=(n,), fill_value=2, dtype=np.int32)
+    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=np.int32)
+    task = np.zeros(2, dtype=np.int32)
+    ln_task = np.zeros(2, dtype=np.int32)
+    lsave = np.zeros(4, dtype=np.int32)
+    isave = np.zeros(44, dtype=np.int32)
+    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.10/site-packages/scipy/optimize/tests/test_least_squares.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..d27d670a1aac01f7129d483e0a048a38dce35404
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_least_squares.py
@@ -0,0 +1,874 @@
+from itertools import product
+
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import (assert_, assert_allclose,
+                           assert_equal, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+from scipy.sparse import issparse, lil_matrix
+from scipy.sparse.linalg import aslinearoperator
+
+from scipy.optimize import least_squares, Bounds
+from scipy.optimize._lsq.least_squares import IMPLEMENTED_LOSSES
+from scipy.optimize._lsq.common import EPS, make_strictly_feasible, CL_scaling_vector
+
+
+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])])
+
+
+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.RandomState(0)
+
+        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.randn(n)
+        self.ub += 0.1 * rng.randn(n)
+
+        self.x0 += 0.1 * rng.randn(n)
+        self.x0 = make_strictly_feasible(self.x0, self.lb, self.ub)
+
+        if mode == 'sparse':
+            self.sparsity = lil_matrix((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_matrix((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, random_seed=None):
+        rng = np.random.RandomState(random_seed)
+        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.randn(self.m)
+
+        outliers = rng.randint(0, self.m, n_outliers)
+        self.y[outliers] += 50 * noise * rng.rand(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:
+    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 suppress_warnings() as sup:
+                sup.filter(
+                    UserWarning,
+                    "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'"
+                )
+                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 suppress_warnings() as sup:
+                sup.filter(
+                    UserWarning,
+                    "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'"
+                )
+                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=None, 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 and res2 should be equivalent.
+        # res2 and res3 should be different.
+        res1 = least_squares(fun_trivial, 2.0, diff_step=1e-1,
+                             method=self.method)
+        res2 = 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(res2.x, 0, atol=1e-4)
+        assert_allclose(res3.x, 0, atol=1e-4)
+        assert_equal(res1.x, res2.x)
+        assert_equal(res1.nfev, res2.nfev)
+
+    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.nfev < 30)
+            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_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 suppress_warnings() as sup:
+                sup.filter(
+                    UserWarning,
+                    "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'"
+                )
+                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)
+
+
+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, random_seed=0)
+
+            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_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_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.RandomState(1)
+
+    x = np.linspace(0, 1, 100).astype("float32")
+    y = rng.random(100).astype("float32")
+
+    def func(p, x):
+        return p[0] + p[1] * x
+
+    def err(p, x, y):
+        return func(p, x) - y
+
+    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
+    assert_allclose(res.x, np.array([0.4082241, 0.15530563]), atol=5e-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.10/site-packages/scipy/optimize/tests/test_linear_assignment.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_linear_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..d59792da9eef38e313eaa0bca70f873627f8d3cf
--- /dev/null
+++ b/venv/lib/python3.10/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
+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.
+    np.random.seed(1234)
+    for _ in range(100):
+        lsa_raises = False
+        mwfbm_raises = False
+        sparse = random(100, 100, density=0.06,
+                        data_rvs=lambda size: np.random.randint(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.10/site-packages/scipy/optimize/tests/test_linesearch.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..6eee0743d97665185c35cf144d66e00542925480
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_linesearch.py
@@ -0,0 +1,328 @@
+"""
+Tests for line search routines
+"""
+from numpy.testing import (assert_equal, assert_array_almost_equal,
+                           assert_array_almost_equal_nulp, assert_warns,
+                           suppress_warnings)
+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)))
+
+        np.random.seed(1234)
+        self.A = np.random.randn(self.N, self.N)
+
+    def scalar_iter(self):
+        for name, phi, derphi in self.scalar_funcs:
+            for old_phi0 in np.random.randn(3):
+                yield name, phi, derphi, old_phi0
+
+    def line_iter(self):
+        rng = np.random.RandomState(1234)
+        for name, f, fprime in self.line_funcs:
+            k = 0
+            while k < 9:
+                x = rng.randn(self.N)
+                p = rng.randn(self.N)
+                if np.dot(p, fprime(x)) >= 0:
+                    # always pick a descent direction
+                    continue
+                k += 1
+                old_fv = float(rng.randn())
+                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 suppress_warnings() as sup:
+                sup.filter(LineSearchWarning,
+                           "The line search algorithm could not find a solution")
+                sup.filter(LineSearchWarning,
+                           "The line search algorithm did not converge")
+                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...
+
+    @pytest.mark.thread_unsafe
+    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)
+
+        s, _, _, _, _, _ = assert_warns(LineSearchWarning,
+                                        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
+        assert_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.10/site-packages/scipy/optimize/tests/test_linprog.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d18e68e394c31e3bc19f49e80c8e9adbc055193
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_linprog.py
@@ -0,0 +1,2577 @@
+"""
+Unit test for Linear Programming
+"""
+import sys
+import platform
+
+import numpy as np
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+                           assert_array_less, assert_warns, suppress_warnings)
+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
+from scipy._lib._util import VisibleDeprecationWarning
+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):
+    """
+    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.RandomState(0)
+    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.rand(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.RandomState(0)
+    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.RandomState(seed)
+    m_eq, m_ub, n = 10, 20, 50
+    c = rng.rand(n)-0.5
+    A_ub = rng.rand(m_ub, n)-0.5
+    b_ub = rng.rand(m_ub)-0.5
+    A_eq = rng.rand(m_eq, n)-0.5
+    b_eq = rng.rand(m_eq)-0.5
+    lb = -rng.rand(n)
+    ub = rng.rand(n)
+    lb[lb < -rng.rand()] = -np.inf
+    ub[ub > rng.rand()] = 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.RandomState(seed)
+    phi = rng.normal(0, 1, size=(m, d))  # random feature mapping
+    w_true = rng.randn(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_matrix((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'])
+
+
+@pytest.mark.thread_unsafe
+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])
+
+
+@pytest.mark.thread_unsafe
+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=-64.049494229)
+
+    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])
+
+    @pytest.mark.thread_unsafe
+    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
+
+        assert_warns(OptimizeWarning, f,
+                     c, A_ub=A_ub, b_ub=b_ub, options=o)
+
+    @pytest.mark.thread_unsafe
+    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 np.testing.assert_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 np.testing.suppress_warnings() as sup:
+            sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged")
+            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.RandomState(0)
+        m = 100
+        n = 150
+        A_eq = scipy.sparse.rand(m, n, 0.5)
+        x_valid = rng.randn(n)
+        c = rng.randn(n)
+        ub = x_valid + rng.rand(n)
+        lb = x_valid - rng.rand(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]
+        np.random.seed(0)
+        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)
+
+    @pytest.mark.thread_unsafe
+    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.RandomState(0)
+        c = rng.rand(n)
+        c[1] = 1
+        A_eq = rng.rand(m, n)
+        A_eq[:, 1] = 0
+        b_eq = rng.rand(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.7087836730413404)
+
+    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.RandomState(0)
+        m, n = 2, 4
+        c = rng.rand(n)
+        c[1] = -1
+        A_eq = rng.rand(m, n)
+        A_eq[:, 1] = 0
+        b_eq = rng.rand(m)
+
+        A_ub = rng.rand(m, n)
+        A_ub[:, 1] = 0
+        b_ub = rng.rand(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.RandomState(1234)
+        c = rng.rand(n)
+        A_eq = rng.rand(m, n)
+        A_eq[0, :] = 0
+        b_eq = rng.rand(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.RandomState(1234)
+        c = rng.rand(n)
+        A_ub = rng.rand(m, n)
+        A_ub[0, :] = 0
+        b_ub = -rng.rand(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.RandomState(0)
+        c = rng.rand(n)
+        A_eq = rng.rand(m, n)
+        b_eq = rng.rand(m)
+        A_eq[-1, :] = 2 * A_eq[-2, :]
+        b_eq[-1] *= -1
+        with suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "Solving system with option 'sym_pos'")
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(LinAlgWarning)
+            res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+                          method=self.method, options=self.options)
+        _assert_success(res, desired_fun=-64.049494229)
+
+    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 suppress_warnings() as sup:
+            sup.filter(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 suppress_warnings() as sup:
+            # this is an UmfpackWarning but I had trouble importing it
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...")
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            sup.filter(OptimizeWarning, "Solving system with option...")
+            sup.filter(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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning,
+                       "Solving system with option 'sym_pos'")
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(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 suppress_warnings() as sup:
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(OptimizeWarning,
+                       "Solving system with option 'cholesky'")
+            sup.filter(OptimizeWarning, "Solving system with option 'sym_pos'")
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(LinAlgWarning)
+            res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+                          method=self.method, options=self.options)
+
+        desired_fun = 1.730550597
+        _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 suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(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 suppress_warnings() as sup:
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            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 suppress_warnings() as sup:
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(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 suppress_warnings() as sup:
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(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 suppress_warnings() as sup:
+            sup.filter(RuntimeWarning)
+            sup.filter(OptimizeWarning, "Solving system with option...")
+            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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "Solving system with option...")
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...")
+            sup.filter(RuntimeWarning, "divide by zero encountered...")
+            sup.filter(RuntimeWarning, "overflow encountered...")
+            sup.filter(RuntimeWarning, "invalid value encountered...")
+            sup.filter(LinAlgWarning, "Ill-conditioned matrix...")
+            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.thread_unsafe
+    @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)
+        assert_warns(OptimizeWarning, f, options=options)
+
+    def test_crossover(self):
+        A_eq, b_eq, c, _, _ = magic_square(4)
+        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.")
+
+    @pytest.mark.thread_unsafe
+    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.")
+
+    @pytest.mark.thread_unsafe
+    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.")
+
+    @pytest.mark.thread_unsafe
+    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 suppress_warnings() as sup:
+            if has_umfpack:
+                sup.filter(UmfpackWarning)
+            sup.filter(MatrixRankWarning, "Matrix is exactly singular")
+            sup.filter(OptimizeWarning, "Solving system with option...")
+
+            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_success(res, desired_fun=1.730550597)
+
+    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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            sup.filter(OptimizeWarning, "Invalid permc_spec option")
+            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)
+                _assert_success(res, desired_fun=1.730550597)
+
+
+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=-64.049494229)
+
+    def test_alternate_initial_point(self):
+        # use "improved" initial point
+        A, b, c = lpgen_2d(20, 20)
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...")
+            sup.filter(OptimizeWarning, "Solving system with option...")
+            sup.filter(LinAlgWarning, "Ill-conditioned matrix...")
+            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=-64.049494229)
+
+    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 suppress_warnings() as sup:
+            sup.filter(RuntimeWarning)
+            sup.filter(OptimizeWarning, "Solving system with option...")
+            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):
+        A, b, c, _, _ = magic_square(3)
+        p = np.random.rand(*c.shape)
+        with suppress_warnings() as sup:
+            sup.filter(OptimizeWarning, "A_eq does not appear...")
+            sup.filter(RuntimeWarning, "invalid value encountered")
+            sup.filter(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=1.730550597)
+        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.10/site-packages/scipy/optimize/tests/test_lsq_common.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..650deedce88b6babd8a3f2b62a5839f1a6cb966c
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_lsq_linear.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..23032e99764ed2e90d7192c078e5cb4518e328fd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_linear.py
@@ -0,0 +1,287 @@
+import pytest
+
+import numpy as np
+from numpy.linalg import lstsq
+from numpy.testing import assert_allclose, assert_equal, assert_
+
+from scipy.sparse import rand, coo_matrix
+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.RandomState(0)
+
+    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 np.testing.suppress_warnings() as sup:
+            sup.filter(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):
+        np.random.seed(0)
+        n, m = np.sort(np.random.randint(2, 1000, size=2))
+        m *= 2   # make m >> n
+        A = 1.0 * np.random.randint(-99, 99, size=[m, n])
+        b = 1.0 * np.random.randint(-99, 99, size=[m])
+        bounds = 1.0 * np.sort(np.random.randint(-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 = np.random.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_matrix(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 = rand(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 = rand(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_matrix((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, match=""):
+            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.10/site-packages/scipy/optimize/tests/test_milp.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..165417fa1c0a9799056fd67a7218499c611a673e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_milp.py
@@ -0,0 +1,459 @@
+"""
+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:"
+
+@pytest.mark.thread_unsafe
+# 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.x, r2.x)
+
+    # 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)
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_minimize_constrained.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_minimize_constrained.py
new file mode 100644
index 0000000000000000000000000000000000000000..cda21fd1dc2b24b128e47405e01353fdae41a75c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_minimize_constrained.py
@@ -0,0 +1,845 @@
+import numpy as np
+import pytest
+from scipy.linalg import block_diag
+from scipy.sparse import csc_matrix
+from numpy.testing import (assert_array_almost_equal,
+                           assert_array_less, assert_,
+                           suppress_warnings)
+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_matrix(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.thread_unsafe
+    @pytest.mark.parametrize('prob', list_of_problems)
+    @pytest.mark.parametrize('grad', ('prob.grad', '3-point', False))
+    @pytest.mark.parametrize('hess', ("prob.hess", '3-point', SR1(),
+                                      BFGS(exception_strategy='damp_update'),
+                                      BFGS(exception_strategy='skip_update')))
+    def test_list_of_problems(self, prob, grad, hess):
+        grad = prob.grad if grad == "prob.grad" else grad
+        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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.0")
+            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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.0")
+            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 np.testing.suppress_warnings() as sup:
+        sup.filter(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_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 np.testing.suppress_warnings() as sup:
+        sup.filter(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 suppress_warnings() as sup:
+        sup.filter(UserWarning, "delta_grad == 0.0")
+        sup.filter(UserWarning, "Singular Jacobian matrix.")
+        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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "Initial guess is not within "
+                                    "the specified bounds")
+            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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "Initial guess is not within "
+                                    "the specified bounds")
+            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 suppress_warnings() as sup:
+            sup.filter(UserWarning, "Initial guess is not within "
+                                    "the specified bounds")
+            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.10/site-packages/scipy/optimize/tests/test_minpack.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef107c5692c2d30a06b6943542696b95bc21e818
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_minpack.py
@@ -0,0 +1,1194 @@
+"""
+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,
+                           assert_warns, suppress_warnings)
+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
+        np.random.seed(0)
+        self.y_meas = y_true + 0.01*np.random.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), 'solution not found (ier=%d)' % 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), 'solution not found (ier=%d)' % 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), 'solution not found (ier=%d)' % 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), 'solution not found (ier=%d)' % 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 suppress_warnings() as sup:
+            sup.filter(OptimizeWarning,
+                       "Covariance of the parameters could not be estimated")
+            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)
+
+    @pytest.mark.thread_unsafe
+    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])
+        assert_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
+
+        np.random.seed(0)
+        xdata = np.linspace(0, 4, 50)
+        y = func(xdata, 2.5, 1.3)
+        ydata = y + 0.2 * np.random.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.RandomState(0)
+        xdata = np.arange(1, 4)
+        y = func(xdata, 2.5, 1.0)
+        ydata = y + 0.2 * rng.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.2e-7, atol=1e-14)
+                assert_allclose(pcov1, pcov2, rtol=1.2e-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)
+        target = 4.7 * xdata ** 2 + 3.5 * xdata + np.random.rand(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.10/site-packages/scipy/optimize/tests/test_nnls.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..67443dd6147bd7ee8898bac2a1a7993f6e56e799
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_nnls.py
@@ -0,0 +1,429 @@
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+from scipy.optimize import nnls
+
+
+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_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, atol=500*np.linalg.norm(a, 1)*np.spacing(1.))
+        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, atol=500*np.linalg.norm(a, 1)*np.spacing(1.))
+        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, atol=1e-7)
+
+        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
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_nonlin.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5eb094c15902eca6e089ba3bbf6dfd8eb06970e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_nonlin.py
@@ -0,0 +1,536 @@
+""" 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 .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)
+
+
+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):
+        np.random.seed(123)
+
+        A = np.random.randn(N, N)
+        if complex:
+            A = A + 1j*np.random.randn(N, N)
+        b = np.random.randn(N)
+        if complex:
+            b = b + 1j*np.random.randn(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.RandomState(123)
+
+        N = 7
+
+        def rand(*a):
+            q = rng.rand(*a)
+            if complex:
+                q = q + 1j*rng.rand(*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.rand(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)
+
+    @pytest.mark.thread_unsafe
+    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.10/site-packages/scipy/optimize/tests/test_optimize.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..913ef51f049386a06c61164a3fc07c15111ed212
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_optimize.py
@@ -0,0 +1,3257 @@
+"""
+Unit tests for optimization routines from optimize.py
+
+Authors:
+   Ed Schofield, Nov 2005
+   Andrew Straw, April 2008
+
+"""
+import itertools
+import platform
+import threading
+import numpy as np
+from numpy.testing import (assert_allclose, assert_equal,
+                           assert_almost_equal,
+                           assert_no_warnings, assert_warns,
+                           assert_array_less, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+
+import scipy
+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
+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.conftest import array_api_compatible
+from scipy._lib._array_api_no_0d import xp_assert_equal, array_namespace
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+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)
+
+
+@pytest.mark.thread_unsafe
+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 assert_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 assert_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)
+
+
+@pytest.mark.thread_unsafe
+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 assert_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
+        epsilon = np.sqrt(np.spacing(1.)) * np.random.rand(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 = {'disp': False, '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 = {'disp': False, '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={'disp': False, '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)
+            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.thread_unsafe
+    @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])
+        xinit = np.random.randn(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',
+                                        'cobyla', 'cobyqa', 'slsqp',
+                                        'trust-constr', 'dogleg', 'trust-ncg',
+                                        'trust-exact', 'trust-krylov'])
+    def test_nan_values(self, method, num_parallel_threads):
+        if num_parallel_threads > 1 and method == 'cobyqa':
+            pytest.skip('COBYQA does not support concurrent execution')
+
+        # Check nan values result to failed exit status
+        rng = np.random.RandomState(1234)
+
+        count = [0]
+
+        def func(x):
+            return np.nan
+
+        def func2(x):
+            count[0] += 1
+            if count[0] > 2:
+                return np.nan
+            else:
+                return rng.rand()
+
+        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'), suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.*")
+            sup.filter(RuntimeWarning, ".*does not use Hessian.*")
+            sup.filter(RuntimeWarning, ".*does not use gradient.*")
+
+            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'), suppress_warnings() as sup:
+            # for trust-constr
+            sup.filter(UserWarning, "delta_grad == 0.*")
+            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
+        else:
+            ref = optimize.minimize(**kwargs, options={'maxiter': maxiter})
+            assert res.nit == ref.nit == maxiter
+        assert res.fun == ref.fun
+        assert_equal(res.x, ref.x)
+        assert res.status == (3 if method in [
+            'trust-constr',
+            'cobyqa',
+        ] else 99)
+
+    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.thread_unsafe
+    @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
+        np.random.seed(1234)
+
+        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'), suppress_warnings() as sup:
+            sup.filter(UserWarning, "delta_grad == 0.*")
+            sup.filter(RuntimeWarning, ".*does not use Hessian.*")
+            sup.filter(RuntimeWarning, ".*does not use gradient.*")
+
+            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.thread_unsafe
+    @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)
+
+
+@array_api_compatible
+class TestRosen:
+    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.))
+
+    @skip_xp_backends('jax.numpy',
+                      reasons=["JAX arrays do not support item assignment"])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    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))
+
+    @skip_xp_backends('jax.numpy',
+                      reasons=["JAX arrays do not support item assignment"])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_hess_prod(self, xp):
+        one = xp.asarray(1.)
+        xp_test = array_namespace(one)
+        # 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_test.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 suppress_warnings() as sup:
+                sup.filter(RuntimeWarning,
+                           ("Method .+ does not use (gradient|Hessian.*)"
+                            " information"))
+                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])
+
+    @pytest.mark.thread_unsafe
+    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.thread_unsafe
+@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():
+
+    rng = np.random.RandomState(0)
+    x0 = rng.rand(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 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)
+
+    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')
+    # 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=1.5e-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
+    )
+
+
+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)
+
+
+@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 matrix. Check that results are the same whether `hess`
+    # returns a dense or sparse matrix 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
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_quadratic_assignment.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_quadratic_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f7f26158d8e7ddb33012db4dfc4030661aa75bb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_quadratic_assignment.py
@@ -0,0 +1,455 @@
+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_, assert_warns
+
+
+################
+# 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
+
+
+@pytest.mark.filterwarnings("ignore:The NumPy global RNG was seeded by calling")
+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)
+
+    @pytest.mark.thread_unsafe
+    def test_unknown_options(self):
+        A, B, opt_perm = chr12c()
+
+        def f():
+            quadratic_assignment(A, B, method=self.method,
+                                 options={"ekki-ekki": True})
+        assert_warns(OptimizeWarning, f)
+
+    @pytest.mark.thread_unsafe
+    def test_deprecation_future_warnings(self):
+        # May be removed after SPEC-7 transition is complete in SciPy 1.17
+        A = np.arange(16).reshape((4, 4))
+        B = np.arange(16).reshape((4, 4))
+
+        with pytest.warns(DeprecationWarning, match="Use of `RandomState`*"):
+            rng = np.random.RandomState(0)
+            quadratic_assignment(A, B, method=self.method,
+                                 options={"rng": rng, "maximize": False})
+
+        with pytest.warns(FutureWarning, match="The NumPy global RNG was seeded*"):
+            np.random.seed(0)
+            quadratic_assignment(A, B, method=self.method,
+                                 options={"maximize": False})
+
+        with pytest.warns(FutureWarning, match="The behavior when the rng option*"):
+            quadratic_assignment(A, B, method=self.method,
+                                 options={"rng": 0, "maximize": False})
+
+
+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))}
+            )
+
+
+@pytest.mark.filterwarnings("ignore:The NumPy global RNG was seeded by calling")
+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.10/site-packages/scipy/optimize/tests/test_regression.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..44916ba96293db19756b8222422e76945aa48ebb
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_slsqp.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..45216aa296b56a6a71b89c994e8fc360b826ba00
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_slsqp.py
@@ -0,0 +1,613 @@
+"""
+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
+
+
+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):
+        self.been_called = True
+        self.ncalls += 1
+
+
+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'], res['message'])
+        assert_(callback.been_called)
+        assert_equal(callback.ncalls, res['nit'])
+
+    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):
+        np.random.seed(10)
+        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
+
+    @pytest.mark.thread_unsafe
+    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.
+        np.random.seed(1)
+        bounds = Bounds(np.array([0.1]), np.array([1.0]))
+        n_inputs = len(bounds.lb)
+        x0 = np.array(bounds.lb + (bounds.ub - bounds.lb) *
+                      np.random.random(n_inputs))
+
+        def f(x):
+            assert (x >= bounds.lb).all()
+            return np.linalg.norm(x)
+
+        with pytest.warns(RuntimeWarning, match='x were outside bounds'):
+            res = minimize(f, x0, method='SLSQP', bounds=bounds)
+            assert res.success
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_tnc.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cde9837bfd08e62916660a9750d833629b6b547
--- /dev/null
+++ b/venv/lib/python3.10/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.10/site-packages/scipy/optimize/tests/test_trustregion.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..0439f8125c565d70cbed8c6c41f762fdae06d4ce
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion.py
@@ -0,0 +1,110 @@
+"""
+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)
+
+    @pytest.mark.thread_unsafe
+    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.10/site-packages/scipy/optimize/tests/test_trustregion_exact.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..020b6d883a5fa59006c142df4fcb8c3e115c46bf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_exact.py
@@ -0,0 +1,351 @@
+"""
+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_array_equal,
+                           assert_equal, assert_array_almost_equal)
+
+
+def random_entry(n, min_eig, max_eig, case):
+
+    # Generate random matrix
+    rand = np.random.uniform(-1, 1, (n, n))
+
+    # QR decomposition
+    Q, _, _ = qr(rand, pivoting='True')
+
+    # Generate random eigenvalues
+    eigvalues = np.random.uniform(min_eig, max_eig, 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] = np.random.uniform(-1, 1, n-1)
+        g = np.dot(Q, g)
+    elif case == 'jac_equal_zero':
+        g = np.zeros(n)
+    else:
+        g = np.random.uniform(-1, 1, 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_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.fail_slow(10)
+    def test_for_random_entries(self):
+        # Seed
+        np.random.seed(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)
+
+                # 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)
+
diff --git a/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_krylov.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee288c1b1348d280141bb62c09aba8fa67027142
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_krylov.py
@@ -0,0 +1,170 @@
+"""
+Unit tests for Krylov space trust-region subproblem solver.
+
+"""
+import pytest
+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)
+
+    @pytest.mark.thread_unsafe
+    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.10/site-packages/scipy/optimize/tests/test_zeros.py b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..99fedb181424a3669719f9d4703b739bb53fa8c4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/optimize/tests/test_zeros.py
@@ -0,0 +1,965 @@
+import pytest
+
+from functools import lru_cache
+
+from numpy.testing import (assert_warns, assert_,
+                           assert_allclose,
+                           assert_equal,
+                           assert_array_equal,
+                           suppress_warnings)
+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):
+        known_fail = {'fun7.4'} if method == zeros.ridder else {}
+        self.run_collection('chandrupatla', method, method.__name__,
+                            known_fail=known_fail)
+
+    @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)
+
+
+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))
+
+    @pytest.mark.thread_unsafe
+    def test_array_newton_zero_der_failures(self):
+        # test derivative zero warning
+        assert_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 = 'Failed to converge after %d iterations, value is .*' % (iters)
+                with pytest.raises(RuntimeError, match=msg):
+                    x, r = zeros.newton(f1, x0, maxiter=iters, disp=True, **kwargs)
+
+    @pytest.mark.thread_unsafe
+    def test_deriv_zero_warning(self):
+        def func(x):
+            return x ** 2 - 2.0
+        def dfunc(x):
+            return 2 * x
+        assert_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_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)
+
+
+@pytest.mark.thread_unsafe
+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 suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "RMS of")
+        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 suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "Tolerance of")
+        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 suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "Tolerance of")
+        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)
+
+
+@pytest.mark.thread_unsafe
+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
+
+
+@pytest.mark.thread_unsafe
+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
+
+    assert_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
+
+
+@pytest.mark.thread_unsafe
+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)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/__init__.py b/venv/lib/python3.10/site-packages/scipy/sparse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..18fe7e011db102f57a8263d1db343818715aeeee
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/__init__.py
@@ -0,0 +1,331 @@
+"""
+===================================
+Sparse arrays (:mod:`scipy.sparse`)
+===================================
+
+.. currentmodule:: scipy.sparse
+
+.. toctree::
+   :hidden:
+
+   sparse.csgraph
+   sparse.linalg
+   sparse.migration_to_sparray
+
+SciPy 2-D sparse array package for numeric data.
+
+.. note::
+
+   This package is switching to an array interface, compatible with
+   NumPy arrays, from the older matrix interface.  We recommend that
+   you use the array objects (`bsr_array`, `coo_array`, etc.) for
+   all new work.
+
+   When using the array interface, please note that:
+
+   - ``x * y`` no longer performs matrix multiplication, but
+     element-wise multiplication (just like with NumPy arrays).  To
+     make code work with both arrays and matrices, use ``x @ y`` for
+     matrix multiplication.
+   - Operations such as ``sum``, that used to produce dense matrices, now
+     produce arrays, whose multiplication behavior differs similarly.
+   - Sparse arrays use array style *slicing* operations, returning scalars,
+     1D, or 2D sparse arrays. If you need 2D results, use an appropriate index.
+     E.g. ``A[:, i, None]`` or ``A[:, [i]]``.
+
+   The construction utilities (`eye`, `kron`, `random`, `diags`, etc.)
+   have appropriate replacements (see :ref:`sparse-construction-functions`).
+
+   For more information see
+   :ref:`Migration from spmatrix to sparray `.
+
+
+Submodules
+==========
+
+.. autosummary::
+
+   csgraph - Compressed sparse graph routines
+   linalg - Sparse linear algebra routines
+
+
+Sparse array classes
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   bsr_array - Block Sparse Row array
+   coo_array - A sparse array in COOrdinate format
+   csc_array - Compressed Sparse Column array
+   csr_array - Compressed Sparse Row array
+   dia_array - Sparse array with DIAgonal storage
+   dok_array - Dictionary Of Keys based sparse array
+   lil_array - Row-based list of lists sparse array
+   sparray - Sparse array base class
+
+.. _sparse-construction-functions:
+
+Building sparse arrays
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   diags_array - Return a sparse array from diagonals
+   eye_array - Sparse MxN array whose k-th diagonal is all ones
+   random_array - Random values in a given shape array
+   block_array - Build a sparse array from sub-blocks
+
+.. _combining-arrays:
+
+Combining arrays
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   kron - Kronecker product of two sparse arrays
+   kronsum - Kronecker sum of sparse arrays
+   block_diag - Build a block diagonal sparse array
+   tril - Lower triangular portion of a sparse array
+   triu - Upper triangular portion of a sparse array
+   hstack - Stack sparse arrays horizontally (column wise)
+   vstack - Stack sparse arrays vertically (row wise)
+
+Sparse tools
+------------
+
+.. autosummary::
+   :toctree: generated/
+
+   save_npz - Save a sparse array to a file using ``.npz`` format.
+   load_npz - Load a sparse array from a file using ``.npz`` format.
+   find - Return the indices and values of the nonzero elements
+   get_index_dtype - determine a good dtype for index arrays.
+   safely_cast_index_arrays - cast index array dtype or raise if shape too big
+
+Identifying sparse arrays
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   issparse - Check if the argument is a sparse object (array or matrix).
+
+
+Sparse matrix classes
+=====================
+
+.. autosummary::
+   :toctree: generated/
+
+   bsr_matrix - Block Sparse Row matrix
+   coo_matrix - A sparse matrix in COOrdinate format
+   csc_matrix - Compressed Sparse Column matrix
+   csr_matrix - Compressed Sparse Row matrix
+   dia_matrix - Sparse matrix with DIAgonal storage
+   dok_matrix - Dictionary Of Keys based sparse matrix
+   lil_matrix - Row-based list of lists sparse matrix
+   spmatrix - Sparse matrix base class
+
+Building sparse matrices
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   eye - Sparse MxN matrix whose k-th diagonal is all ones
+   identity - Identity matrix in sparse matrix format
+   diags - Return a sparse matrix from diagonals
+   spdiags - Return a sparse matrix from diagonals
+   bmat - Build a sparse matrix from sparse sub-blocks
+   random - Random values in a given shape matrix
+   rand - Random values in a given shape matrix (old interface)
+
+**Combining matrices use the same functions as for** :ref:`combining-arrays`.
+
+Identifying sparse matrices
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   issparse
+   isspmatrix
+   isspmatrix_csc
+   isspmatrix_csr
+   isspmatrix_bsr
+   isspmatrix_lil
+   isspmatrix_dok
+   isspmatrix_coo
+   isspmatrix_dia
+
+
+Warnings
+========
+
+.. autosummary::
+   :toctree: generated/
+
+   SparseEfficiencyWarning
+   SparseWarning
+
+
+Usage information
+=================
+
+There are seven available sparse array types:
+
+    1. csc_array: Compressed Sparse Column format
+    2. csr_array: Compressed Sparse Row format
+    3. bsr_array: Block Sparse Row format
+    4. lil_array: List of Lists format
+    5. dok_array: Dictionary of Keys format
+    6. coo_array: COOrdinate format (aka IJV, triplet format)
+    7. dia_array: DIAgonal format
+
+To construct an array efficiently, use any of `coo_array`,
+`dok_array` or `lil_array`. `dok_array` and `lil_array`
+support basic slicing and fancy indexing with a similar syntax
+to NumPy arrays. The COO format does not support indexing (yet)
+but can also be used to efficiently construct arrays using coord
+and value info.
+
+Despite their similarity to NumPy arrays, it is **strongly discouraged**
+to use NumPy functions directly on these arrays because NumPy typically
+treats them as generic Python objects rather than arrays, leading to
+unexpected (and incorrect) results. If you do want to apply a NumPy
+function to these arrays, first check if SciPy has its own implementation
+for the given sparse array class, or **convert the sparse array to
+a NumPy array** (e.g., using the `toarray` method of the class)
+before applying the method.
+
+All conversions among the CSR, CSC, and COO formats are efficient,
+linear-time operations.
+
+To perform manipulations such as multiplication or inversion, first
+convert the array to either CSC or CSR format. The `lil_array`
+format is row-based, so conversion to CSR is efficient, whereas
+conversion to CSC is less so.
+
+Matrix vector product
+---------------------
+
+To do a vector product between a 2D sparse array and a vector use
+the matmul operator (i.e., ``@``) which performs a dot product (like the
+``dot`` method):
+
+>>> import numpy as np
+>>> from scipy.sparse import csr_array
+>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+>>> v = np.array([1, 0, -1])
+>>> A @ v
+array([ 1, -3, -1], dtype=int64)
+
+The CSR format is especially suitable for fast matrix vector products.
+
+Example 1
+---------
+
+Construct a 1000x1000 `lil_array` and add some values to it:
+
+>>> from scipy.sparse import lil_array
+>>> from scipy.sparse.linalg import spsolve
+>>> from numpy.linalg import solve, norm
+>>> from numpy.random import rand
+
+>>> A = lil_array((1000, 1000))
+>>> A[0, :100] = rand(100)
+>>> A.setdiag(rand(1000))
+
+Now convert it to CSR format and solve A x = b for x:
+
+>>> A = A.tocsr()
+>>> b = rand(1000)
+>>> x = spsolve(A, b)
+
+Convert it to a dense array and solve, and check that the result
+is the same:
+
+>>> x_ = solve(A.toarray(), b)
+
+Now we can compute norm of the error with:
+
+>>> err = norm(x-x_)
+>>> err < 1e-10
+True
+
+It should be small :)
+
+
+Example 2
+---------
+
+Construct an array in COO format:
+
+>>> from scipy import sparse
+>>> from numpy import array
+>>> I = array([0,3,1,0])
+>>> J = array([0,3,1,2])
+>>> V = array([4,5,7,9])
+>>> A = sparse.coo_array((V,(I,J)),shape=(4,4))
+
+Notice that the indices do not need to be sorted.
+
+Duplicate (i,j) entries are summed when converting to CSR or CSC.
+
+>>> I = array([0,0,1,3,1,0,0])
+>>> J = array([0,2,1,3,1,0,0])
+>>> V = array([1,1,1,1,1,1,1])
+>>> B = sparse.coo_array((V,(I,J)),shape=(4,4)).tocsr()
+
+This is useful for constructing finite-element stiffness and mass matrices.
+
+Further details
+---------------
+
+CSR column indices are not necessarily sorted. Likewise for CSC row
+indices. Use the ``.sorted_indices()`` and ``.sort_indices()`` methods when
+sorted indices are required (e.g., when passing data to other libraries).
+
+"""
+
+# Original code by Travis Oliphant.
+# Modified and extended by Ed Schofield, Robert Cimrman,
+# Nathan Bell, and Jake Vanderplas.
+
+import warnings as _warnings
+
+from ._base import *
+from ._csr import *
+from ._csc import *
+from ._lil import *
+from ._dok import *
+from ._coo import *
+from ._dia import *
+from ._bsr import *
+from ._construct import *
+from ._extract import *
+from ._matrix import spmatrix
+from ._matrix_io import *
+from ._sputils import get_index_dtype, safely_cast_index_arrays
+
+# For backward compatibility with v0.19.
+from . import csgraph
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract,
+    lil, sparsetools, sputils
+)
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
+msg = 'the matrix subclass is not the recommended way'
+_warnings.filterwarnings('ignore', message=msg)
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_base.py b/venv/lib/python3.10/site-packages/scipy/sparse/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..926e191013c7cacebab7a8e025a017358ba82f50
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_base.py
@@ -0,0 +1,1448 @@
+"""Base class for sparse matrices"""
+
+import numpy as np
+
+from ._sputils import (asmatrix, check_reshape_kwargs, check_shape,
+                       get_sum_dtype, isdense, isscalarlike,
+                       matrix, validateaxis, getdtype)
+
+from ._matrix import spmatrix
+
+__all__ = ['isspmatrix', 'issparse', 'sparray',
+           'SparseWarning', 'SparseEfficiencyWarning']
+
+
+class SparseWarning(Warning):
+    pass
+
+
+class SparseFormatWarning(SparseWarning):
+    pass
+
+
+class SparseEfficiencyWarning(SparseWarning):
+    pass
+
+
+# The formats that we might potentially understand.
+_formats = {'csc': [0, "Compressed Sparse Column"],
+            'csr': [1, "Compressed Sparse Row"],
+            'dok': [2, "Dictionary Of Keys"],
+            'lil': [3, "List of Lists"],
+            'dod': [4, "Dictionary of Dictionaries"],
+            'sss': [5, "Symmetric Sparse Skyline"],
+            'coo': [6, "COOrdinate"],
+            'lba': [7, "Linpack BAnded"],
+            'egd': [8, "Ellpack-itpack Generalized Diagonal"],
+            'dia': [9, "DIAgonal"],
+            'bsr': [10, "Block Sparse Row"],
+            'msr': [11, "Modified compressed Sparse Row"],
+            'bsc': [12, "Block Sparse Column"],
+            'msc': [13, "Modified compressed Sparse Column"],
+            'ssk': [14, "Symmetric SKyline"],
+            'nsk': [15, "Nonsymmetric SKyline"],
+            'jad': [16, "JAgged Diagonal"],
+            'uss': [17, "Unsymmetric Sparse Skyline"],
+            'vbr': [18, "Variable Block Row"],
+            'und': [19, "Undefined"]
+            }
+
+
+# These univariate ufuncs preserve zeros.
+_ufuncs_with_fixed_point_at_zero = frozenset([
+        np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh,
+        np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad,
+        np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt])
+
+
+MAXPRINT = 50
+
+
+class _spbase:
+    """ This class provides a base class for all sparse arrays.  It
+    cannot be instantiated.  Most of the work is provided by subclasses.
+    """
+
+    __array_priority__ = 10.1
+    _format = 'und'  # undefined
+    _allow_nd = (2,)
+
+    @property
+    def ndim(self) -> int:
+        return len(self._shape)
+
+    @property
+    def _shape_as_2d(self):
+        s = self._shape
+        return (1, s[-1]) if len(s) == 1 else s
+
+    @property
+    def _bsr_container(self):
+        from ._bsr import bsr_array
+        return bsr_array
+
+    @property
+    def _coo_container(self):
+        from ._coo import coo_array
+        return coo_array
+
+    @property
+    def _csc_container(self):
+        from ._csc import csc_array
+        return csc_array
+
+    @property
+    def _csr_container(self):
+        from ._csr import csr_array
+        return csr_array
+
+    @property
+    def _dia_container(self):
+        from ._dia import dia_array
+        return dia_array
+
+    @property
+    def _dok_container(self):
+        from ._dok import dok_array
+        return dok_array
+
+    @property
+    def _lil_container(self):
+        from ._lil import lil_array
+        return lil_array
+
+    def __init__(self, arg1, *, maxprint=None):
+        self._shape = None
+        if self.__class__.__name__ == '_spbase':
+            raise ValueError("This class is not intended"
+                             " to be instantiated directly.")
+        if isinstance(self, sparray) and np.isscalar(arg1):
+            raise ValueError(
+                "scipy sparse array classes do not support instantiation from a scalar"
+            )
+        self.maxprint = MAXPRINT if maxprint is None else maxprint
+
+    @property
+    def shape(self):
+        return self._shape
+
+    def reshape(self, *args, **kwargs):
+        """reshape(self, shape, order='C', copy=False)
+
+        Gives a new shape to a sparse array/matrix without changing its data.
+
+        Parameters
+        ----------
+        shape : length-2 tuple of ints
+            The new shape should be compatible with the original shape.
+        order : {'C', 'F'}, optional
+            Read the elements using this index order. 'C' means to read and
+            write the elements using C-like index order; e.g., read entire first
+            row, then second row, etc. 'F' means to read and write the elements
+            using Fortran-like index order; e.g., read entire first column, then
+            second column, etc.
+        copy : bool, optional
+            Indicates whether or not attributes of self should be copied
+            whenever possible. The degree to which attributes are copied varies
+            depending on the type of sparse array being used.
+
+        Returns
+        -------
+        reshaped : sparse array/matrix
+            A sparse array/matrix with the given `shape`, not necessarily of the same
+            format as the current object.
+
+        See Also
+        --------
+        numpy.reshape : NumPy's implementation of 'reshape' for ndarrays
+        """
+        # If the shape already matches, don't bother doing an actual reshape
+        # Otherwise, the default is to convert to COO and use its reshape
+        # Don't restrict ndim on this first call. That happens in constructor
+        shape = check_shape(args, self.shape, allow_nd=range(1, 65))
+        order, copy = check_reshape_kwargs(kwargs)
+        if shape == self.shape:
+            if copy:
+                return self.copy()
+            else:
+                return self
+
+        return self.tocoo(copy=copy).reshape(shape, order=order, copy=False)
+
+    def resize(self, shape):
+        """Resize the array/matrix in-place to dimensions given by ``shape``
+
+        Any elements that lie within the new shape will remain at the same
+        indices, while non-zero elements lying outside the new shape are
+        removed.
+
+        Parameters
+        ----------
+        shape : (int, int)
+            number of rows and columns in the new array/matrix
+
+        Notes
+        -----
+        The semantics are not identical to `numpy.ndarray.resize` or
+        `numpy.resize`. Here, the same data will be maintained at each index
+        before and after reshape, if that index is within the new bounds. In
+        numpy, resizing maintains contiguity of the array, moving elements
+        around in the logical array but not within a flattened representation.
+
+        We give no guarantees about whether the underlying data attributes
+        (arrays, etc.) will be modified in place or replaced with new objects.
+        """
+        # As an inplace operation, this requires implementation in each format.
+        raise NotImplementedError(
+            f'{type(self).__name__}.resize is not implemented')
+
+    def astype(self, dtype, casting='unsafe', copy=True):
+        """Cast the array/matrix elements to a specified type.
+
+        Parameters
+        ----------
+        dtype : string or numpy dtype
+            Typecode or data-type to which to cast the data.
+        casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+            Controls what kind of data casting may occur.
+            Defaults to 'unsafe' for backwards compatibility.
+            'no' means the data types should not be cast at all.
+            'equiv' means only byte-order changes are allowed.
+            'safe' means only casts which can preserve values are allowed.
+            'same_kind' means only safe casts or casts within a kind,
+            like float64 to float32, are allowed.
+            'unsafe' means any data conversions may be done.
+        copy : bool, optional
+            If `copy` is `False`, the result might share some memory with this
+            array/matrix. If `copy` is `True`, it is guaranteed that the result and
+            this array/matrix do not share any memory.
+        """
+
+        dtype = getdtype(dtype)
+        if self.dtype != dtype:
+            return self.tocsr().astype(
+                dtype, casting=casting, copy=copy).asformat(self.format)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    @classmethod
+    def _ascontainer(cls, X, **kwargs):
+        if issubclass(cls, sparray):
+            return np.asarray(X, **kwargs)
+        else:
+            return asmatrix(X, **kwargs)
+
+    @classmethod
+    def _container(cls, X, **kwargs):
+        if issubclass(cls, sparray):
+            return np.array(X, **kwargs)
+        else:
+            return matrix(X, **kwargs)
+
+    def _asfptype(self):
+        """Upcast array to a floating point format (if necessary)"""
+
+        fp_types = ['f', 'd', 'F', 'D']
+
+        if self.dtype.char in fp_types:
+            return self
+        else:
+            for fp_type in fp_types:
+                if self.dtype <= np.dtype(fp_type):
+                    return self.astype(fp_type)
+
+            raise TypeError(
+                f'cannot upcast [{self.dtype.name}] to a floating point format'
+            )
+
+    def __iter__(self):
+        for r in range(self.shape[0]):
+            yield self[r]
+
+    def _getmaxprint(self):
+        """Maximum number of elements to display when printed."""
+        return self.maxprint
+
+    def count_nonzero(self, axis=None):
+        """Number of non-zero entries, equivalent to
+
+        np.count_nonzero(a.toarray(), axis=axis)
+
+        Unlike the nnz property, which return the number of stored
+        entries (the length of the data attribute), this method counts the
+        actual number of non-zero entries in data.
+
+        Duplicate entries are summed before counting.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Count nonzeros for the whole array, or along a specified axis.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        numpy array
+            A reduced array (no axis `axis`) holding the number of nonzero values
+            for each of the indices of the nonaxis dimensions.
+
+        Notes
+        -----
+        If you want to count nonzero and explicit zero stored values (e.g. nnz)
+        along an axis, two fast idioms are provided by `numpy` functions for the
+        common CSR, CSC, COO formats.
+
+        For the major axis in CSR (rows) and CSC (cols) use `np.diff`:
+
+            >>> import numpy as np
+            >>> import scipy as sp
+            >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
+            >>> major_axis_stored_values = np.diff(A.indptr)  # -> np.array([2, 1])
+
+        For the minor axis in CSR (cols) and CSC (rows) use `numpy.bincount` with
+        minlength ``A.shape[1]`` for CSR and ``A.shape[0]`` for CSC:
+
+            >>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1])
+
+        For COO, use the minor axis approach for either `axis`:
+
+            >>> A = A.tocoo()
+            >>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1])
+            >>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0])
+
+        Examples
+        --------
+
+            >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
+            >>> A.count_nonzero(axis=0)
+            array([2, 1, 0])
+        """
+        clsname = self.__class__.__name__
+        raise NotImplementedError(f"count_nonzero not implemented for {clsname}.")
+
+    def _getnnz(self, axis=None):
+        """Number of stored values, including explicit zeros.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Report stored values for the whole array, or along a specified axis.
+
+        See also
+        --------
+        count_nonzero : Number of non-zero entries
+        """
+        clsname = self.__class__.__name__
+        raise NotImplementedError(f"getnnz not implemented for {clsname}.")
+
+    @property
+    def nnz(self) -> int:
+        """Number of stored values, including explicit zeros.
+
+        See also
+        --------
+        count_nonzero : Number of non-zero entries
+        """
+        return self._getnnz()
+
+    @property
+    def size(self) -> int:
+        """Number of stored values.
+
+        See also
+        --------
+        count_nonzero : Number of non-zero values.
+        """
+        return self._getnnz()
+
+    @property
+    def format(self) -> str:
+        """Format string for matrix."""
+        return self._format
+
+    @property
+    def T(self):
+        """Transpose."""
+        return self.transpose()
+
+    @property
+    def real(self):
+        return self._real()
+
+    @property
+    def imag(self):
+        return self._imag()
+
+    def __repr__(self):
+        _, format_name = _formats[self.format]
+        sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+        return (
+            f"<{format_name} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+            f"\twith {self.nnz} stored elements and shape {self.shape}>"
+        )
+
+    def __str__(self):
+        maxprint = self._getmaxprint()
+
+        A = self.tocoo()
+
+        # helper function, outputs "(i,j)  v"
+        def tostr(coords, data):
+            pairs = zip(zip(*(c.tolist() for c in coords)), data)
+            return '\n'.join(f'  {idx}\t{val}' for idx, val in pairs)
+
+        out = repr(self)
+        if self.nnz == 0:
+            return out
+
+        out += '\n  Coords\tValues\n'
+        if self.nnz > maxprint:
+            half = maxprint // 2
+            out += tostr(tuple(c[:half] for c in A.coords), A.data[:half])
+            out += "\n  :\t:\n"
+            half = maxprint - half
+            out += tostr(tuple(c[-half:] for c in A.coords), A.data[-half:])
+        else:
+            out += tostr(A.coords, A.data)
+
+        return out
+
+    def __bool__(self):  # Simple -- other ideas?
+        if self.shape == (1, 1):
+            return self.nnz != 0
+        else:
+            raise ValueError("The truth value of an array with more than one "
+                             "element is ambiguous. Use a.any() or a.all().")
+    __nonzero__ = __bool__
+
+    # What should len(sparse) return? For consistency with dense matrices,
+    # perhaps it should be the number of rows?  But for some uses the number of
+    # non-zeros is more important.  For now, raise an exception!
+    def __len__(self):
+        raise TypeError("sparse array length is ambiguous; use getnnz()"
+                        " or shape[0]")
+
+    def asformat(self, format, copy=False):
+        """Return this array/matrix in the passed format.
+
+        Parameters
+        ----------
+        format : {str, None}
+            The desired sparse format ("csr", "csc", "lil", "dok", "array", ...)
+            or None for no conversion.
+        copy : bool, optional
+            If True, the result is guaranteed to not share data with self.
+
+        Returns
+        -------
+        A : This array/matrix in the passed format.
+        """
+        if format is None or format == self.format:
+            if copy:
+                return self.copy()
+            else:
+                return self
+        else:
+            try:
+                convert_method = getattr(self, 'to' + format)
+            except AttributeError as e:
+                raise ValueError(f'Format {format} is unknown.') from e
+
+            # Forward the copy kwarg, if it's accepted.
+            try:
+                return convert_method(copy=copy)
+            except TypeError:
+                return convert_method()
+
+    ###################################################################
+    #  NOTE: All arithmetic operations use csr_matrix by default.
+    # Therefore a new sparse array format just needs to define a
+    # .tocsr() method to provide arithmetic support. Any of these
+    # methods can be overridden for efficiency.
+    ####################################################################
+
+    def multiply(self, other):
+        """Point-wise multiplication by another array/matrix."""
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        return self.tocsr().multiply(other)
+
+    def maximum(self, other):
+        """Element-wise maximum between this and another array/matrix."""
+        return self.tocsr().maximum(other)
+
+    def minimum(self, other):
+        """Element-wise minimum between this and another array/matrix."""
+        return self.tocsr().minimum(other)
+
+    def dot(self, other):
+        """Ordinary dot product
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.sparse import csr_array
+        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> v = np.array([1, 0, -1])
+        >>> A.dot(v)
+        array([ 1, -3, -1], dtype=int64)
+
+        """
+        if np.isscalar(other):
+            return self * other
+        else:
+            return self @ other
+
+    def power(self, n, dtype=None):
+        """Element-wise power."""
+        return self.tocsr().power(n, dtype=dtype)
+
+    def _broadcast_to(self, shape, copy=False):
+        if self.shape == shape:
+            return self.copy() if copy else self
+        else:
+            return self.tocsr()._broadcast_to(shape, copy)
+
+    def __eq__(self, other):
+        return self.tocsr().__eq__(other)
+
+    def __ne__(self, other):
+        return self.tocsr().__ne__(other)
+
+    def __lt__(self, other):
+        return self.tocsr().__lt__(other)
+
+    def __gt__(self, other):
+        return self.tocsr().__gt__(other)
+
+    def __le__(self, other):
+        return self.tocsr().__le__(other)
+
+    def __ge__(self, other):
+        return self.tocsr().__ge__(other)
+
+    def __abs__(self):
+        return abs(self.tocsr())
+
+    def __round__(self, ndigits=0):
+        return round(self.tocsr(), ndigits=ndigits)
+
+    def _add_sparse(self, other):
+        return self.tocsr()._add_sparse(other)
+
+    def _add_dense(self, other):
+        return self.tocoo()._add_dense(other)
+
+    def _sub_sparse(self, other):
+        return self.tocsr()._sub_sparse(other)
+
+    def _sub_dense(self, other):
+        return self.todense() - other
+
+    def _rsub_dense(self, other):
+        # note: this can't be replaced by other + (-self) for unsigned types
+        return other - self.todense()
+
+    def __add__(self, other):  # self + other
+        if isscalarlike(other):
+            if other == 0:
+                return self.copy()
+            # Now we would add this scalar to every element.
+            raise NotImplementedError('adding a nonzero scalar to a '
+                                      'sparse array is not supported')
+        elif issparse(other):
+            if other.shape != self.shape:
+                raise ValueError("inconsistent shapes")
+            return self._add_sparse(other)
+        elif isdense(other):
+            other = np.broadcast_to(other, self.shape)
+            return self._add_dense(other)
+        else:
+            return NotImplemented
+
+    def __radd__(self,other):  # other + self
+        return self.__add__(other)
+
+    def __sub__(self, other):  # self - other
+        if isscalarlike(other):
+            if other == 0:
+                return self.copy()
+            raise NotImplementedError('subtracting a nonzero scalar from a '
+                                      'sparse array is not supported')
+        elif issparse(other):
+            if other.shape != self.shape:
+                raise ValueError("inconsistent shapes")
+            return self._sub_sparse(other)
+        elif isdense(other):
+            other = np.broadcast_to(other, self.shape)
+            return self._sub_dense(other)
+        else:
+            return NotImplemented
+
+    def __rsub__(self,other):  # other - self
+        if isscalarlike(other):
+            if other == 0:
+                return -self.copy()
+            raise NotImplementedError('subtracting a sparse array from a '
+                                      'nonzero scalar is not supported')
+        elif isdense(other):
+            other = np.broadcast_to(other, self.shape)
+            return self._rsub_dense(other)
+        else:
+            return NotImplemented
+
+    def _matmul_dispatch(self, other):
+        """np.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented`
+
+        interpret other and call one of the following
+        self._mul_scalar()
+        self._matmul_vector()
+        self._matmul_multivector()
+        self._matmul_sparse()
+        """
+        # This method has to be different from `__matmul__` because it is also
+        # called by sparse matrix classes.
+
+        # Currently matrix multiplication is only supported
+        # for 2D arrays. Hence we unpacked and use only the
+        # two last axes' lengths.
+        M, N = self._shape_as_2d
+
+        if other.__class__ is np.ndarray:
+            # Fast path for the most common case
+            if other.shape == (N,):
+                return self._matmul_vector(other)
+            elif other.shape == (N, 1):
+                result = self._matmul_vector(other.ravel())
+                if self.ndim == 1:
+                    return result.reshape(1)
+                return result.reshape(M, 1)
+            elif other.ndim == 2 and other.shape[0] == N:
+                return self._matmul_multivector(other)
+
+        if isscalarlike(other):
+            # scalar value
+            return self._mul_scalar(other)
+
+        err_prefix = "matmul: dimension mismatch with signature"
+        if issparse(other):
+            if N != other.shape[0]:
+                raise ValueError(
+                    f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)"
+                )
+            return self._matmul_sparse(other)
+
+        # If it's a list or whatever, treat it like an array
+        other_a = np.asanyarray(other)
+
+        if other_a.ndim == 0 and other_a.dtype == np.object_:
+            # Not interpretable as an array; return NotImplemented so that
+            # other's __rmatmul__ can kick in if that's implemented.
+            return NotImplemented
+
+        try:
+            other.shape
+        except AttributeError:
+            other = other_a
+
+        if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
+            # dense row or column vector
+            if other.shape[0] != N:
+                raise ValueError(
+                    f"{err_prefix} (n,k={N}),(k={other.shape[0]},1?)->(n,1?)"
+                )
+
+            result = self._matmul_vector(np.ravel(other))
+
+            if isinstance(other, np.matrix):
+                result = self._ascontainer(result)
+
+            if other.ndim == 2 and other.shape[1] == 1:
+                # If 'other' was an (nx1) column vector, reshape the result
+                if self.ndim == 1:
+                    result = result.reshape(1)
+                else:
+                    result = result.reshape(-1, 1)
+
+            return result
+
+        elif other.ndim == 2:
+            ##
+            # dense 2D array or matrix ("multivector")
+
+            if other.shape[0] != N:
+                raise ValueError(
+                    f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)"
+                )
+
+            result = self._matmul_multivector(np.asarray(other))
+
+            if isinstance(other, np.matrix):
+                result = self._ascontainer(result)
+
+            return result
+
+        else:
+            raise ValueError('could not interpret dimensions')
+
+    def __mul__(self, other):
+        return self.multiply(other)
+
+    def __rmul__(self, other):  # other * self
+        return self.multiply(other)
+
+    # by default, use CSR for __mul__ handlers
+    def _mul_scalar(self, other):
+        return self.tocsr()._mul_scalar(other)
+
+    def _matmul_vector(self, other):
+        return self.tocsr()._matmul_vector(other)
+
+    def _matmul_multivector(self, other):
+        return self.tocsr()._matmul_multivector(other)
+
+    def _matmul_sparse(self, other):
+        return self.tocsr()._matmul_sparse(other)
+
+    def _rmatmul_dispatch(self, other):
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        else:
+            # Don't use asarray unless we have to
+            try:
+                tr = other.transpose()
+            except AttributeError:
+                tr = np.asarray(other).transpose()
+            ret = self.transpose()._matmul_dispatch(tr)
+            if ret is NotImplemented:
+                return NotImplemented
+            return ret.transpose()
+
+    #######################
+    # matmul (@) operator #
+    #######################
+
+    def __matmul__(self, other):
+        if isscalarlike(other):
+            raise ValueError("Scalar operands are not allowed, "
+                             "use '*' instead")
+        return self._matmul_dispatch(other)
+
+    def __rmatmul__(self, other):
+        if isscalarlike(other):
+            raise ValueError("Scalar operands are not allowed, "
+                             "use '*' instead")
+        return self._rmatmul_dispatch(other)
+
+    ####################
+    # Other Arithmetic #
+    ####################
+
+    def _divide(self, other, true_divide=False, rdivide=False):
+        if isscalarlike(other):
+            if rdivide:
+                if true_divide:
+                    return np.true_divide(other, self.todense())
+                else:
+                    return np.divide(other, self.todense())
+
+            if true_divide and np.can_cast(self.dtype, np.float64):
+                return self.astype(np.float64)._mul_scalar(1./other)
+            else:
+                r = self._mul_scalar(1./other)
+
+                scalar_dtype = np.asarray(other).dtype
+                if (np.issubdtype(self.dtype, np.integer) and
+                        np.issubdtype(scalar_dtype, np.integer)):
+                    return r.astype(self.dtype)
+                else:
+                    return r
+
+        elif isdense(other):
+            if not rdivide:
+                if true_divide:
+                    recip = np.true_divide(1., other)
+                else:
+                    recip = np.divide(1., other)
+                return self.multiply(recip)
+            else:
+                if true_divide:
+                    return np.true_divide(other, self.todense())
+                else:
+                    return np.divide(other, self.todense())
+        elif issparse(other):
+            if rdivide:
+                return other._divide(self, true_divide, rdivide=False)
+
+            self_csr = self.tocsr()
+            if true_divide and np.can_cast(self.dtype, np.float64):
+                return self_csr.astype(np.float64)._divide_sparse(other)
+            else:
+                return self_csr._divide_sparse(other)
+        else:
+            return NotImplemented
+
+    def __truediv__(self, other):
+        return self._divide(other, true_divide=True)
+
+    def __div__(self, other):
+        # Always do true division
+        return self._divide(other, true_divide=True)
+
+    def __rtruediv__(self, other):
+        # Implementing this as the inverse would be too magical -- bail out
+        return NotImplemented
+
+    def __rdiv__(self, other):
+        # Implementing this as the inverse would be too magical -- bail out
+        return NotImplemented
+
+    def __neg__(self):
+        return -self.tocsr()
+
+    def __iadd__(self, other):
+        return NotImplemented
+
+    def __isub__(self, other):
+        return NotImplemented
+
+    def __imul__(self, other):
+        return NotImplemented
+
+    def __idiv__(self, other):
+        return self.__itruediv__(other)
+
+    def __itruediv__(self, other):
+        return NotImplemented
+
+    def __pow__(self, *args, **kwargs):
+        return self.power(*args, **kwargs)
+
+    def transpose(self, axes=None, copy=False):
+        """
+        Reverses the dimensions of the sparse array/matrix.
+
+        Parameters
+        ----------
+        axes : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except
+            for the default value.
+        copy : bool, optional
+            Indicates whether or not attributes of `self` should be
+            copied whenever possible. The degree to which attributes
+            are copied varies depending on the type of sparse array/matrix
+            being used.
+
+        Returns
+        -------
+        p : `self` with the dimensions reversed.
+
+        Notes
+        -----
+        If `self` is a `csr_array` or a `csc_array`, then this will return a
+        `csc_array` or a `csr_array`, respectively.
+
+        See Also
+        --------
+        numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
+        """
+        return self.tocsr(copy=copy).transpose(axes=axes, copy=False)
+
+    def conjugate(self, copy=True):
+        """Element-wise complex conjugation.
+
+        If the array/matrix is of non-complex data type and `copy` is False,
+        this method does nothing and the data is not copied.
+
+        Parameters
+        ----------
+        copy : bool, optional
+            If True, the result is guaranteed to not share data with self.
+
+        Returns
+        -------
+        A : The element-wise complex conjugate.
+
+        """
+        if np.issubdtype(self.dtype, np.complexfloating):
+            return self.tocsr(copy=copy).conjugate(copy=False)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    def conj(self, copy=True):
+        return self.conjugate(copy=copy)
+
+    conj.__doc__ = conjugate.__doc__
+
+    def _real(self):
+        return self.tocsr()._real()
+
+    def _imag(self):
+        return self.tocsr()._imag()
+
+    def nonzero(self):
+        """Nonzero indices of the array/matrix.
+
+        Returns a tuple of arrays (row,col) containing the indices
+        of the non-zero elements of the array.
+
+        Examples
+        --------
+        >>> from scipy.sparse import csr_array
+        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> A.nonzero()
+        (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32))
+
+        """
+
+        # convert to COOrdinate format
+        A = self.tocoo()
+        nz_mask = A.data != 0
+        return tuple(idx[nz_mask] for idx in A.coords)
+
+    def _getcol(self, j):
+        """Returns a copy of column j of the array, as an (m x 1) sparse
+        array (column vector).
+        """
+        if self.ndim == 1:
+            raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
+        # Subclasses should override this method for efficiency.
+        # Post-multiply by a (n x 1) column vector 'a' containing all zeros
+        # except for a_j = 1
+        N = self.shape[-1]
+        if j < 0:
+            j += N
+        if j < 0 or j >= N:
+            raise IndexError("index out of bounds")
+        col_selector = self._csc_container(([1], [[j], [0]]),
+                                           shape=(N, 1), dtype=self.dtype)
+        result = self @ col_selector
+        return result
+
+    def _getrow(self, i):
+        """Returns a copy of row i of the array, as a (1 x n) sparse
+        array (row vector).
+        """
+        if self.ndim == 1:
+            raise ValueError("getrow not meaningful for a 1d array")
+        # Subclasses should override this method for efficiency.
+        # Pre-multiply by a (1 x m) row vector 'a' containing all zeros
+        # except for a_i = 1
+        M = self.shape[0]
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError("index out of bounds")
+        row_selector = self._csr_container(([1], [[0], [i]]),
+                                           shape=(1, M), dtype=self.dtype)
+        return row_selector @ self
+
+    # The following dunder methods cannot be implemented.
+    #
+    # def __array__(self):
+    #     # Sparse matrices rely on NumPy wrapping them in object arrays under
+    #     # the hood to make unary ufuncs work on them. So we cannot raise
+    #     # TypeError here - which would be handy to not give users object
+    #     # arrays they probably don't want (they're looking for `.toarray()`).
+    #     #
+    #     # Conversion with `toarray()` would also break things because of the
+    #     # behavior discussed above, plus we want to avoid densification by
+    #     # accident because that can too easily blow up memory.
+    #
+    # def __array_ufunc__(self):
+    #     # We cannot implement __array_ufunc__ due to mismatching semantics.
+    #     # See gh-7707 and gh-7349 for details.
+    #
+    # def __array_function__(self):
+    #     # We cannot implement __array_function__ due to mismatching semantics.
+    #     # See gh-10362 for details.
+
+    def todense(self, order=None, out=None):
+        """
+        Return a dense representation of this sparse array.
+
+        Parameters
+        ----------
+        order : {'C', 'F'}, optional
+            Whether to store multi-dimensional data in C (row-major)
+            or Fortran (column-major) order in memory. The default
+            is 'None', which provides no ordering guarantees.
+            Cannot be specified in conjunction with the `out`
+            argument.
+
+        out : ndarray, 2-D, optional
+            If specified, uses this array as the output buffer
+            instead of allocating a new array to return. The
+            provided array must have the same shape and dtype as
+            the sparse array on which you are calling the method.
+
+        Returns
+        -------
+        arr : ndarray, 2-D
+            An array with the same shape and containing the same
+            data represented by the sparse array, with the requested
+            memory order. If `out` was passed, the same object is
+            returned after being modified in-place to contain the
+            appropriate values.
+        """
+        return self._ascontainer(self.toarray(order=order, out=out))
+
+    def toarray(self, order=None, out=None):
+        """
+        Return a dense ndarray representation of this sparse array/matrix.
+
+        Parameters
+        ----------
+        order : {'C', 'F'}, optional
+            Whether to store multidimensional data in C (row-major)
+            or Fortran (column-major) order in memory. The default
+            is 'None', which provides no ordering guarantees.
+            Cannot be specified in conjunction with the `out`
+            argument.
+
+        out : ndarray, 2-D, optional
+            If specified, uses this array as the output buffer
+            instead of allocating a new array to return. The provided
+            array must have the same shape and dtype as the sparse
+            array/matrix on which you are calling the method. For most
+            sparse types, `out` is required to be memory contiguous
+            (either C or Fortran ordered).
+
+        Returns
+        -------
+        arr : ndarray, 2-D
+            An array with the same shape and containing the same
+            data represented by the sparse array/matrix, with the requested
+            memory order. If `out` was passed, the same object is
+            returned after being modified in-place to contain the
+            appropriate values.
+        """
+        return self.tocoo(copy=False).toarray(order=order, out=out)
+
+    # Any sparse array format deriving from _spbase must define one of
+    # tocsr or tocoo. The other conversion methods may be implemented for
+    # efficiency, but are not required.
+    def tocsr(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Row format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant csr_array/matrix.
+        """
+        return self.tocoo(copy=copy).tocsr(copy=False)
+
+    def todok(self, copy=False):
+        """Convert this array/matrix to Dictionary Of Keys format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant dok_array/matrix.
+        """
+        return self.tocoo(copy=copy).todok(copy=False)
+
+    def tocoo(self, copy=False):
+        """Convert this array/matrix to COOrdinate format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant coo_array/matrix.
+        """
+        return self.tocsr(copy=False).tocoo(copy=copy)
+
+    def tolil(self, copy=False):
+        """Convert this array/matrix to List of Lists format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant lil_array/matrix.
+        """
+        return self.tocsr(copy=False).tolil(copy=copy)
+
+    def todia(self, copy=False):
+        """Convert this array/matrix to sparse DIAgonal format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant dia_array/matrix.
+        """
+        return self.tocoo(copy=copy).todia(copy=False)
+
+    def tobsr(self, blocksize=None, copy=False):
+        """Convert this array/matrix to Block Sparse Row format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant bsr_array/matrix.
+
+        When blocksize=(R, C) is provided, it will be used for construction of
+        the bsr_array/matrix.
+        """
+        return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy)
+
+    def tocsc(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Column format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant csc_array/matrix.
+        """
+        return self.tocsr(copy=copy).tocsc(copy=False)
+
+    def copy(self):
+        """Returns a copy of this array/matrix.
+
+        No data/indices will be shared between the returned value and current
+        array/matrix.
+        """
+        return self.__class__(self, copy=True)
+
+    def sum(self, axis=None, dtype=None, out=None):
+        """
+        Sum the array/matrix elements over a given axis.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the sum is computed. The default is to
+            compute the sum of all the array/matrix elements, returning a scalar
+            (i.e., `axis` = `None`).
+        dtype : dtype, optional
+            The type of the returned array/matrix and of the accumulator in which
+            the elements are summed.  The dtype of `a` is used by default
+            unless `a` has an integer dtype of less precision than the default
+            platform integer.  In that case, if `a` is signed then the platform
+            integer is used while if `a` is unsigned then an unsigned integer
+            of the same precision as the platform integer is used.
+
+            .. versionadded:: 0.18.0
+
+        out : np.matrix, optional
+            Alternative output matrix in which to place the result. It must
+            have the same shape as the expected output, but the type of the
+            output values will be cast if necessary.
+
+            .. versionadded:: 0.18.0
+
+        Returns
+        -------
+        sum_along_axis : np.matrix
+            A matrix with the same shape as `self`, with the specified
+            axis removed.
+
+        See Also
+        --------
+        numpy.matrix.sum : NumPy's implementation of 'sum' for matrices
+
+        """
+        validateaxis(axis)
+
+        # Mimic numpy's casting.
+        res_dtype = get_sum_dtype(self.dtype)
+
+        if self.ndim == 1:
+            if axis not in (None, -1, 0):
+                raise ValueError("axis must be None, -1 or 0")
+            res = self @ np.ones(self.shape, dtype=res_dtype)
+            return res.sum(dtype=dtype, out=out)
+
+        # We use multiplication by a matrix of ones to achieve this.
+        # For some sparse array formats more efficient methods are
+        # possible -- these should override this function.
+        M, N = self.shape
+
+        if axis is None:
+            # sum over rows and columns
+            return (
+                self @ self._ascontainer(np.ones((N, 1), dtype=res_dtype))
+            ).sum(dtype=dtype, out=out)
+
+        if axis < 0:
+            axis += 2
+
+        # axis = 0 or 1 now
+        if axis == 0:
+            # sum over columns
+            ret = self._ascontainer(
+                np.ones((1, M), dtype=res_dtype)
+            ) @ self
+        else:
+            # sum over rows
+            ret = self @ self._ascontainer(
+                np.ones((N, 1), dtype=res_dtype)
+            )
+
+        return ret.sum(axis=axis, dtype=dtype, out=out)
+
+    def mean(self, axis=None, dtype=None, out=None):
+        """
+        Compute the arithmetic mean along the specified axis.
+
+        Returns the average of the array/matrix elements. The average is taken
+        over all elements in the array/matrix by default, otherwise over the
+        specified axis. `float64` intermediate and return values are used
+        for integer inputs.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the mean is computed. The default is to compute
+            the mean of all elements in the array/matrix (i.e., `axis` = `None`).
+        dtype : data-type, optional
+            Type to use in computing the mean. For integer inputs, the default
+            is `float64`; for floating point inputs, it is the same as the
+            input dtype.
+
+            .. versionadded:: 0.18.0
+
+        out : np.matrix, optional
+            Alternative output matrix in which to place the result. It must
+            have the same shape as the expected output, but the type of the
+            output values will be cast if necessary.
+
+            .. versionadded:: 0.18.0
+
+        Returns
+        -------
+        m : np.matrix
+
+        See Also
+        --------
+        numpy.matrix.mean : NumPy's implementation of 'mean' for matrices
+
+        """
+        validateaxis(axis)
+
+        res_dtype = self.dtype.type
+        integral = (np.issubdtype(self.dtype, np.integer) or
+                    np.issubdtype(self.dtype, np.bool_))
+
+        # output dtype
+        if dtype is None:
+            if integral:
+                res_dtype = np.float64
+        else:
+            res_dtype = np.dtype(dtype).type
+
+        # intermediate dtype for summation
+        inter_dtype = np.float64 if integral else res_dtype
+        inter_self = self.astype(inter_dtype)
+
+        if self.ndim == 1:
+            if axis not in (None, -1, 0):
+                raise ValueError("axis must be None, -1 or 0")
+            res = inter_self / self.shape[-1]
+            return res.sum(dtype=res_dtype, out=out)
+
+        if axis is None:
+            return (inter_self / (self.shape[0] * self.shape[1]))\
+                .sum(dtype=res_dtype, out=out)
+
+        if axis < 0:
+            axis += 2
+
+        # axis = 0 or 1 now
+        if axis == 0:
+            return (inter_self * (1.0 / self.shape[0])).sum(
+                axis=0, dtype=res_dtype, out=out)
+        else:
+            return (inter_self * (1.0 / self.shape[1])).sum(
+                axis=1, dtype=res_dtype, out=out)
+
+    def diagonal(self, k=0):
+        """Returns the kth diagonal of the array/matrix.
+
+        Parameters
+        ----------
+        k : int, optional
+            Which diagonal to get, corresponding to elements a[i, i+k].
+            Default: 0 (the main diagonal).
+
+            .. versionadded:: 1.0
+
+        See also
+        --------
+        numpy.diagonal : Equivalent numpy function.
+
+        Examples
+        --------
+        >>> from scipy.sparse import csr_array
+        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> A.diagonal()
+        array([1, 0, 5])
+        >>> A.diagonal(k=1)
+        array([2, 3])
+        """
+        return self.tocsr().diagonal(k=k)
+
+    def trace(self, offset=0):
+        """Returns the sum along diagonals of the sparse array/matrix.
+
+        Parameters
+        ----------
+        offset : int, optional
+            Which diagonal to get, corresponding to elements a[i, i+offset].
+            Default: 0 (the main diagonal).
+
+        """
+        return self.diagonal(k=offset).sum()
+
+    def setdiag(self, values, k=0):
+        """
+        Set diagonal or off-diagonal elements of the array/matrix.
+
+        Parameters
+        ----------
+        values : array_like
+            New values of the diagonal elements.
+
+            Values may have any length. If the diagonal is longer than values,
+            then the remaining diagonal entries will not be set. If values are
+            longer than the diagonal, then the remaining values are ignored.
+
+            If a scalar value is given, all of the diagonal is set to it.
+
+        k : int, optional
+            Which off-diagonal to set, corresponding to elements a[i,i+k].
+            Default: 0 (the main diagonal).
+
+        """
+        M, N = self.shape
+        if (k > 0 and k >= N) or (k < 0 and -k >= M):
+            raise ValueError("k exceeds array dimensions")
+        self._setdiag(np.asarray(values), k)
+
+    def _setdiag(self, values, k):
+        """This part of the implementation gets overridden by the
+        different formats.
+        """
+        M, N = self.shape
+        if k < 0:
+            if values.ndim == 0:
+                # broadcast
+                max_index = min(M+k, N)
+                for i in range(max_index):
+                    self[i - k, i] = values
+            else:
+                max_index = min(M+k, N, len(values))
+                if max_index <= 0:
+                    return
+                for i, v in enumerate(values[:max_index]):
+                    self[i - k, i] = v
+        else:
+            if values.ndim == 0:
+                # broadcast
+                max_index = min(M, N-k)
+                for i in range(max_index):
+                    self[i, i + k] = values
+            else:
+                max_index = min(M, N-k, len(values))
+                if max_index <= 0:
+                    return
+                for i, v in enumerate(values[:max_index]):
+                    self[i, i + k] = v
+
+    def _process_toarray_args(self, order, out):
+        if out is not None:
+            if order is not None:
+                raise ValueError('order cannot be specified if out '
+                                 'is not None')
+            if out.shape != self.shape or out.dtype != self.dtype:
+                raise ValueError('out array must be same dtype and shape as '
+                                 'sparse array')
+            out[...] = 0.
+            return out
+        else:
+            return np.zeros(self.shape, dtype=self.dtype, order=order)
+
+    def _get_index_dtype(self, arrays=(), maxval=None, check_contents=False):
+        """
+        Determine index dtype for array.
+
+        This wraps _sputils.get_index_dtype, providing compatibility for both
+        array and matrix API sparse matrices. Matrix API sparse matrices would
+        attempt to downcast the indices - which can be computationally
+        expensive and undesirable for users. The array API changes this
+        behaviour.
+
+        See discussion: https://github.com/scipy/scipy/issues/16774
+
+        The get_index_dtype import is due to implementation details of the test
+        suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a
+        lower int32 max value for checks on the matrix API's downcasting
+        behaviour.
+        """
+        from ._sputils import get_index_dtype
+
+        # Don't check contents for array API
+        return get_index_dtype(arrays,
+                               maxval,
+                               (check_contents and not isinstance(self, sparray)))
+
+
+class sparray:
+    """A namespace class to separate sparray from spmatrix"""
+
+
+sparray.__doc__ = _spbase.__doc__
+
+
+def issparse(x):
+    """Is `x` of a sparse array or sparse matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a sparse array or sparse matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a sparse array or a sparse matrix, False otherwise
+
+    Notes
+    -----
+    Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
+    Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array, csr_matrix, issparse
+    >>> issparse(csr_matrix([[5]]))
+    True
+    >>> issparse(csr_array([[5]]))
+    True
+    >>> issparse(np.array([[5]]))
+    False
+    >>> issparse(5)
+    False
+    """
+    return isinstance(x, _spbase)
+
+
+def isspmatrix(x):
+    """Is `x` of a sparse matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a sparse matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a sparse matrix, False otherwise
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
+    >>> isspmatrix(csr_matrix([[5]]))
+    True
+    >>> isspmatrix(csr_array([[5]]))
+    False
+    >>> isspmatrix(np.array([[5]]))
+    False
+    >>> isspmatrix(5)
+    False
+    """
+    return isinstance(x, spmatrix)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_bsr.py b/venv/lib/python3.10/site-packages/scipy/sparse/_bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..14cf85f8ccf8d7d2b4c63d19938b215e54a9736b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_bsr.py
@@ -0,0 +1,877 @@
+"""Compressed Block Sparse Row format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['bsr_array', 'bsr_matrix', 'isspmatrix_bsr']
+
+from warnings import warn
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._data import _data_matrix, _minmax_mixin
+from ._compressed import _cs_matrix
+from ._base import issparse, _formats, _spbase, sparray
+from ._sputils import (isshape, getdtype, getdata, to_native, upcast,
+                       check_shape)
+from . import _sparsetools
+from ._sparsetools import (bsr_matvec, bsr_matvecs, csr_matmat_maxnnz,
+                           bsr_matmat, bsr_transpose, bsr_sort_indices,
+                           bsr_tocsr)
+
+
+class _bsr_base(_cs_matrix, _minmax_mixin):
+    _format = 'bsr'
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False,
+                 blocksize=None, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+
+        if issparse(arg1):
+            if arg1.format == self.format and copy:
+                arg1 = arg1.copy()
+            else:
+                arg1 = arg1.tobsr(blocksize=blocksize)
+            self.indptr, self.indices, self.data, self._shape = (
+                arg1.indptr, arg1.indices, arg1.data, arg1._shape
+            )
+
+        elif isinstance(arg1,tuple):
+            if isshape(arg1):
+                # it's a tuple of matrix dimensions (M,N)
+                self._shape = check_shape(arg1)
+                M,N = self.shape
+                # process blocksize
+                if blocksize is None:
+                    blocksize = (1,1)
+                else:
+                    if not isshape(blocksize):
+                        raise ValueError(f'invalid blocksize={blocksize}')
+                    blocksize = tuple(blocksize)
+                self.data = np.zeros((0,) + blocksize, getdtype(dtype, default=float))
+
+                R,C = blocksize
+                if (M % R) != 0 or (N % C) != 0:
+                    raise ValueError('shape must be multiple of blocksize')
+
+                # Select index dtype large enough to pass array and
+                # scalar parameters to sparsetools
+                idx_dtype = self._get_index_dtype(maxval=max(M//R, N//C, R, C))
+                self.indices = np.zeros(0, dtype=idx_dtype)
+                self.indptr = np.zeros(M//R + 1, dtype=idx_dtype)
+
+            elif len(arg1) == 2:
+                # (data,(row,col)) format
+                coo = self._coo_container(arg1, dtype=dtype, shape=shape)
+                bsr = coo.tobsr(blocksize=blocksize)
+                self.indptr, self.indices, self.data, self._shape = (
+                    bsr.indptr, bsr.indices, bsr.data, bsr._shape
+                )
+
+            elif len(arg1) == 3:
+                # (data,indices,indptr) format
+                (data, indices, indptr) = arg1
+
+                # Select index dtype large enough to pass array and
+                # scalar parameters to sparsetools
+                maxval = 1
+                if shape is not None:
+                    maxval = max(shape)
+                if blocksize is not None:
+                    maxval = max(maxval, max(blocksize))
+                idx_dtype = self._get_index_dtype((indices, indptr), maxval=maxval,
+                                                  check_contents=True)
+                if not copy:
+                    copy = copy_if_needed
+                self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
+                self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
+                self.data = getdata(data, copy=copy, dtype=dtype)
+                if self.data.ndim != 3:
+                    raise ValueError(
+                        f'BSR data must be 3-dimensional, got shape={self.data.shape}'
+                    )
+                if blocksize is not None:
+                    if not isshape(blocksize):
+                        raise ValueError(f'invalid blocksize={blocksize}')
+                    if tuple(blocksize) != self.data.shape[1:]:
+                        raise ValueError(
+                            f'mismatching blocksize={blocksize}'
+                            f' vs {self.data.shape[1:]}'
+                        )
+            else:
+                raise ValueError('unrecognized bsr_array constructor usage')
+        else:
+            # must be dense
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise ValueError("unrecognized form for "
+                                 f"{self.format}_matrix constructor") from e
+            if isinstance(self, sparray) and arg1.ndim != 2:
+                raise ValueError(f"BSR arrays don't support {arg1.ndim}D input. Use 2D")
+            arg1 = self._coo_container(arg1, dtype=dtype).tobsr(blocksize=blocksize)
+            self.indptr, self.indices, self.data, self._shape = (
+                arg1.indptr, arg1.indices, arg1.data, arg1._shape
+            )
+
+        if shape is not None:
+            self._shape = check_shape(shape)
+        else:
+            if self.shape is None:
+                # shape not already set, try to infer dimensions
+                try:
+                    M = len(self.indptr) - 1
+                    N = self.indices.max() + 1
+                except Exception as e:
+                    raise ValueError('unable to infer matrix dimensions') from e
+                else:
+                    R,C = self.blocksize
+                    self._shape = check_shape((M*R,N*C))
+
+        if self.shape is None:
+            if shape is None:
+                # TODO infer shape here
+                raise ValueError('need to infer shape')
+            else:
+                self._shape = check_shape(shape)
+
+        if dtype is not None:
+            self.data = self.data.astype(getdtype(dtype, self.data), copy=False)
+
+        self.check_format(full_check=False)
+
+    def check_format(self, full_check=True):
+        """Check whether the array/matrix respects the BSR format.
+
+        Parameters
+        ----------
+        full_check : bool, optional
+            If `True`, run rigorous check, scanning arrays for valid values.
+            Note that activating those check might copy arrays for casting,
+            modifying indices and index pointers' inplace.
+            If `False`, run basic checks on attributes. O(1) operations.
+            Default is `True`.
+        """
+        M,N = self.shape
+        R,C = self.blocksize
+
+        # index arrays should have integer data types
+        if self.indptr.dtype.kind != 'i':
+            warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
+                 stacklevel=2)
+        if self.indices.dtype.kind != 'i':
+            warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
+                 stacklevel=2)
+
+        # check array shapes
+        if self.indices.ndim != 1 or self.indptr.ndim != 1:
+            raise ValueError("indices, and indptr should be 1-D")
+        if self.data.ndim != 3:
+            raise ValueError("data should be 3-D")
+
+        # check index pointer
+        if (len(self.indptr) != M//R + 1):
+            raise ValueError("index pointer size (%d) should be (%d)" %
+                                (len(self.indptr), M//R + 1))
+        if (self.indptr[0] != 0):
+            raise ValueError("index pointer should start with 0")
+
+        # check index and data arrays
+        if (len(self.indices) != len(self.data)):
+            raise ValueError("indices and data should have the same size")
+        if (self.indptr[-1] > len(self.indices)):
+            raise ValueError("Last value of index pointer should be less than "
+                                "the size of index and data arrays")
+
+        self.prune()
+
+        if full_check:
+            # check format validity (more expensive)
+            if self.nnz > 0:
+                if self.indices.max() >= N//C:
+                    raise ValueError("column index values must be < %d (now max %d)"
+                                     % (N//C, self.indices.max()))
+                if self.indices.min() < 0:
+                    raise ValueError("column index values must be >= 0")
+                if np.diff(self.indptr).min() < 0:
+                    raise ValueError("index pointer values must form a "
+                                        "non-decreasing sequence")
+
+            idx_dtype = self._get_index_dtype((self.indices, self.indptr))
+            self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+            self.indices = np.asarray(self.indices, dtype=idx_dtype)
+            self.data = to_native(self.data)
+        # if not self.has_sorted_indices():
+        #    warn('Indices were not in sorted order. Sorting indices.')
+        #    self.sort_indices(check_first=False)
+
+    @property
+    def blocksize(self) -> tuple:
+        """Block size of the matrix."""
+        return self.data.shape[1:]
+
+    def _getnnz(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError("_getnnz over an axis is not implemented "
+                                      "for BSR format")
+        R, C = self.blocksize
+        return int(self.indptr[-1]) * R * C
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "count_nonzero over axis is not implemented for BSR format."
+            )
+        return np.count_nonzero(self._deduped_data())
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def __repr__(self):
+        _, fmt = _formats[self.format]
+        sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+        b = 'x'.join(str(x) for x in self.blocksize)
+        return (
+            f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+            f"\twith {self.nnz} stored elements (blocksize={b}) and shape {self.shape}>"
+        )
+
+    def diagonal(self, k=0):
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        R, C = self.blocksize
+        y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
+                     dtype=upcast(self.dtype))
+        _sparsetools.bsr_diagonal(k, rows // R, cols // C, R, C,
+                                  self.indptr, self.indices,
+                                  np.ravel(self.data), y)
+        return y
+
+    diagonal.__doc__ = _spbase.diagonal.__doc__
+
+    ##########################
+    # NotImplemented methods #
+    ##########################
+
+    def __getitem__(self,key):
+        raise NotImplementedError
+
+    def __setitem__(self,key,val):
+        raise NotImplementedError
+
+    ######################
+    # Arithmetic methods #
+    ######################
+
+    def _add_dense(self, other):
+        return self.tocoo(copy=False)._add_dense(other)
+
+    def _matmul_vector(self, other):
+        M,N = self.shape
+        R,C = self.blocksize
+
+        result = np.zeros(self.shape[0], dtype=upcast(self.dtype, other.dtype))
+
+        bsr_matvec(M//R, N//C, R, C,
+            self.indptr, self.indices, self.data.ravel(),
+            other, result)
+
+        return result
+
+    def _matmul_multivector(self,other):
+        R,C = self.blocksize
+        M,N = self.shape
+        n_vecs = other.shape[1]  # number of column vectors
+
+        result = np.zeros((M,n_vecs), dtype=upcast(self.dtype,other.dtype))
+
+        bsr_matvecs(M//R, N//C, n_vecs, R, C,
+                self.indptr, self.indices, self.data.ravel(),
+                other.ravel(), result.ravel())
+
+        return result
+
+    def _matmul_sparse(self, other):
+        M, K1 = self.shape
+        K2, N = other.shape
+
+        R,n = self.blocksize
+
+        # convert to this format
+        if other.format == "bsr":
+            C = other.blocksize[1]
+        else:
+            C = 1
+
+        if other.format == "csr" and n == 1:
+            other = other.tobsr(blocksize=(n,C), copy=False)  # lightweight conversion
+        else:
+            other = other.tobsr(blocksize=(n,C))
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                           other.indptr, other.indices))
+
+        bnnz = csr_matmat_maxnnz(M//R, N//C,
+                                 self.indptr.astype(idx_dtype),
+                                 self.indices.astype(idx_dtype),
+                                 other.indptr.astype(idx_dtype),
+                                 other.indices.astype(idx_dtype))
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                           other.indptr, other.indices),
+                                          maxval=bnnz)
+        indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+        indices = np.empty(bnnz, dtype=idx_dtype)
+        data = np.empty(R*C*bnnz, dtype=upcast(self.dtype,other.dtype))
+
+        bsr_matmat(bnnz, M//R, N//C, R, C, n,
+                   self.indptr.astype(idx_dtype),
+                   self.indices.astype(idx_dtype),
+                   np.ravel(self.data),
+                   other.indptr.astype(idx_dtype),
+                   other.indices.astype(idx_dtype),
+                   np.ravel(other.data),
+                   indptr,
+                   indices,
+                   data)
+
+        data = data.reshape(-1,R,C)
+
+        # TODO eliminate zeros
+
+        return self._bsr_container(
+            (data, indices, indptr), shape=(M, N), blocksize=(R, C)
+        )
+
+    ######################
+    # Conversion methods #
+    ######################
+
+    def tobsr(self, blocksize=None, copy=False):
+        """Convert this array/matrix into Block Sparse Row Format.
+
+        With copy=False, the data/indices may be shared between this
+        array/matrix and the resultant bsr_array/bsr_matrix.
+
+        If blocksize=(R, C) is provided, it will be used for determining
+        block size of the bsr_array/bsr_matrix.
+        """
+        if blocksize not in [None, self.blocksize]:
+            return self.tocsr().tobsr(blocksize=blocksize)
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    def tocsr(self, copy=False):
+        M, N = self.shape
+        R, C = self.blocksize
+        nnz = self.nnz
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                          maxval=max(nnz, N))
+        indptr = np.empty(M + 1, dtype=idx_dtype)
+        indices = np.empty(nnz, dtype=idx_dtype)
+        data = np.empty(nnz, dtype=upcast(self.dtype))
+
+        bsr_tocsr(M // R,  # n_brow
+                  N // C,  # n_bcol
+                  R, C,
+                  self.indptr.astype(idx_dtype, copy=False),
+                  self.indices.astype(idx_dtype, copy=False),
+                  self.data,
+                  indptr,
+                  indices,
+                  data)
+        return self._csr_container((data, indices, indptr), shape=self.shape)
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+    def tocsc(self, copy=False):
+        return self.tocsr(copy=False).tocsc(copy=copy)
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tocoo(self, copy=True):
+        """Convert this array/matrix to COOrdinate format.
+
+        When copy=False the data array will be shared between
+        this array/matrix and the resultant coo_array/coo_matrix.
+        """
+
+        M,N = self.shape
+        R,C = self.blocksize
+
+        indptr_diff = np.diff(self.indptr)
+        if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize:
+            # Check for potential overflow
+            indptr_diff_limited = indptr_diff.astype(np.intp)
+            if np.any(indptr_diff_limited != indptr_diff):
+                raise ValueError("Matrix too big to convert")
+            indptr_diff = indptr_diff_limited
+
+        idx_dtype = self._get_index_dtype(maxval=max(M, N))
+        row = (R * np.arange(M//R, dtype=idx_dtype)).repeat(indptr_diff)
+        row = row.repeat(R*C).reshape(-1,R,C)
+        row += np.tile(np.arange(R, dtype=idx_dtype).reshape(-1,1), (1,C))
+        row = row.reshape(-1)
+
+        col = ((C * self.indices).astype(idx_dtype, copy=False)
+               .repeat(R*C).reshape(-1,R,C))
+        col += np.tile(np.arange(C, dtype=idx_dtype), (R,1))
+        col = col.reshape(-1)
+
+        data = self.data.reshape(-1)
+
+        if copy:
+            data = data.copy()
+
+        return self._coo_container(
+            (data, (row, col)), shape=self.shape
+        )
+
+    def toarray(self, order=None, out=None):
+        return self.tocoo(copy=False).toarray(order=order, out=out)
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        R, C = self.blocksize
+        M, N = self.shape
+        NBLK = self.nnz//(R*C)
+
+        if self.nnz == 0:
+            return self._bsr_container((N, M), blocksize=(C, R),
+                                       dtype=self.dtype, copy=copy)
+
+        indptr = np.empty(N//C + 1, dtype=self.indptr.dtype)
+        indices = np.empty(NBLK, dtype=self.indices.dtype)
+        data = np.empty((NBLK, C, R), dtype=self.data.dtype)
+
+        bsr_transpose(M//R, N//C, R, C,
+                      self.indptr, self.indices, self.data.ravel(),
+                      indptr, indices, data.ravel())
+
+        return self._bsr_container((data, indices, indptr),
+                                   shape=(N, M), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    ##############################################################
+    # methods that examine or modify the internal data structure #
+    ##############################################################
+
+    def eliminate_zeros(self):
+        """Remove zero elements in-place."""
+
+        if not self.nnz:
+            return  # nothing to do
+
+        R,C = self.blocksize
+        M,N = self.shape
+
+        mask = (self.data != 0).reshape(-1,R*C).sum(axis=1)  # nonzero blocks
+
+        nonzero_blocks = mask.nonzero()[0]
+
+        self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks]
+
+        # modifies self.indptr and self.indices *in place*
+        _sparsetools.csr_eliminate_zeros(M//R, N//C, self.indptr,
+                                         self.indices, mask)
+        self.prune()
+
+    def sum_duplicates(self):
+        """Eliminate duplicate array/matrix entries by adding them together
+
+        The is an *in place* operation
+        """
+        if self.has_canonical_format:
+            return
+        self.sort_indices()
+        R, C = self.blocksize
+        M, N = self.shape
+
+        # port of _sparsetools.csr_sum_duplicates
+        n_row = M // R
+        nnz = 0
+        row_end = 0
+        for i in range(n_row):
+            jj = row_end
+            row_end = self.indptr[i+1]
+            while jj < row_end:
+                j = self.indices[jj]
+                x = self.data[jj]
+                jj += 1
+                while jj < row_end and self.indices[jj] == j:
+                    x += self.data[jj]
+                    jj += 1
+                self.indices[nnz] = j
+                self.data[nnz] = x
+                nnz += 1
+            self.indptr[i+1] = nnz
+
+        self.prune()  # nnz may have changed
+        self.has_canonical_format = True
+
+    def sort_indices(self):
+        """Sort the indices of this array/matrix *in place*
+        """
+        if self.has_sorted_indices:
+            return
+
+        R,C = self.blocksize
+        M,N = self.shape
+
+        bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel())
+
+        self.has_sorted_indices = True
+
+    def prune(self):
+        """Remove empty space after all non-zero elements.
+        """
+
+        R,C = self.blocksize
+        M,N = self.shape
+
+        if len(self.indptr) != M//R + 1:
+            raise ValueError("index pointer has invalid length")
+
+        bnnz = self.indptr[-1]
+
+        if len(self.indices) < bnnz:
+            raise ValueError("indices array has too few elements")
+        if len(self.data) < bnnz:
+            raise ValueError("data array has too few elements")
+
+        self.data = self.data[:bnnz]
+        self.indices = self.indices[:bnnz]
+
+    # utility functions
+    def _binopt(self, other, op, in_shape=None, out_shape=None):
+        """Apply the binary operation fn to two sparse matrices."""
+
+        # Ideally we'd take the GCDs of the blocksize dimensions
+        # and explode self and other to match.
+        other = self.__class__(other, blocksize=self.blocksize)
+
+        # e.g. bsr_plus_bsr, etc.
+        fn = getattr(_sparsetools, self.format + op + self.format)
+
+        R,C = self.blocksize
+
+        max_bnnz = len(self.data) + len(other.data)
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                           other.indptr, other.indices),
+                                          maxval=max_bnnz)
+        indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+        indices = np.empty(max_bnnz, dtype=idx_dtype)
+
+        bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
+        if op in bool_ops:
+            data = np.empty(R*C*max_bnnz, dtype=np.bool_)
+        else:
+            data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype))
+
+        fn(self.shape[0]//R, self.shape[1]//C, R, C,
+           self.indptr.astype(idx_dtype),
+           self.indices.astype(idx_dtype),
+           self.data,
+           other.indptr.astype(idx_dtype),
+           other.indices.astype(idx_dtype),
+           np.ravel(other.data),
+           indptr,
+           indices,
+           data)
+
+        actual_bnnz = indptr[-1]
+        indices = indices[:actual_bnnz]
+        data = data[:R*C*actual_bnnz]
+
+        if actual_bnnz < max_bnnz/2:
+            indices = indices.copy()
+            data = data.copy()
+
+        data = data.reshape(-1,R,C)
+
+        return self.__class__((data, indices, indptr), shape=self.shape)
+
+    # needed by _data_matrix
+    def _with_data(self,data,copy=True):
+        """Returns a matrix with the same sparsity structure as self,
+        but with different data.  By default the structure arrays
+        (i.e. .indptr and .indices) are copied.
+        """
+        if copy:
+            return self.__class__((data,self.indices.copy(),self.indptr.copy()),
+                                   shape=self.shape,dtype=data.dtype)
+        else:
+            return self.__class__((data,self.indices,self.indptr),
+                                   shape=self.shape,dtype=data.dtype)
+
+#    # these functions are used by the parent class
+#    # to remove redundancy between bsc_matrix and bsr_matrix
+#    def _swap(self,x):
+#        """swap the members of x if this is a column-oriented matrix
+#        """
+#        return (x[0],x[1])
+
+    def _broadcast_to(self, shape, copy=False):
+        return _spbase._broadcast_to(self, shape, copy)
+
+
+def isspmatrix_bsr(x):
+    """Is `x` of a bsr_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a bsr matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a bsr matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import bsr_array, bsr_matrix, csr_matrix, isspmatrix_bsr
+    >>> isspmatrix_bsr(bsr_matrix([[5]]))
+    True
+    >>> isspmatrix_bsr(bsr_array([[5]]))
+    False
+    >>> isspmatrix_bsr(csr_matrix([[5]]))
+    False
+    """
+    return isinstance(x, bsr_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class bsr_array(_bsr_base, sparray):
+    """
+    Block Sparse Row format sparse array.
+
+    This can be instantiated in several ways:
+        bsr_array(D, [blocksize=(R,C)])
+            where D is a 2-D ndarray.
+
+        bsr_array(S, [blocksize=(R,C)])
+            with another sparse array or matrix S (equivalent to S.tobsr())
+
+        bsr_array((M, N), [blocksize=(R,C), dtype])
+            to construct an empty sparse array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        bsr_array((data, ij), [blocksize=(R,C), shape=(M, N)])
+            where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
+
+        bsr_array((data, indices, indptr), [shape=(M, N)])
+            is the standard BSR representation where the block column
+            indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding block values are stored in
+            ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
+            supplied, the array dimensions are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        BSR format data array of the array
+    indices
+        BSR format index array of the array
+    indptr
+        BSR format index pointer array of the array
+    blocksize
+        Block size
+    has_sorted_indices : bool
+        Whether indices are sorted
+    has_canonical_format : bool
+    T
+
+    Notes
+    -----
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    **Summary of BSR format**
+
+    The Block Sparse Row (BSR) format is very similar to the Compressed
+    Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
+    sub matrices like the last example below. Such sparse block matrices often
+    arise in vector-valued finite element discretizations. In such cases, BSR is
+    considerably more efficient than CSR and CSC for many sparse arithmetic
+    operations.
+
+    **Blocksize**
+
+    The blocksize (R,C) must evenly divide the shape of the sparse array (M,N).
+    That is, R and C must satisfy the relationship ``M % R = 0`` and
+    ``N % C = 0``.
+
+    If no blocksize is specified, a simple heuristic is applied to determine
+    an appropriate blocksize.
+
+    **Canonical Format**
+
+    In canonical format, there are no duplicate blocks and indices are sorted
+    per row.
+
+    **Limitations**
+
+    Block Sparse Row format sparse arrays do not support slicing.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import bsr_array
+    >>> bsr_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3 ,4, 5, 6])
+    >>> bsr_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
+    >>> bsr_array((data,indices,indptr), shape=(6, 6)).toarray()
+    array([[1, 1, 0, 0, 2, 2],
+           [1, 1, 0, 0, 2, 2],
+           [0, 0, 0, 0, 3, 3],
+           [0, 0, 0, 0, 3, 3],
+           [4, 4, 5, 5, 6, 6],
+           [4, 4, 5, 5, 6, 6]])
+
+    """
+
+
+class bsr_matrix(spmatrix, _bsr_base):
+    """
+    Block Sparse Row format sparse matrix.
+
+    This can be instantiated in several ways:
+        bsr_matrix(D, [blocksize=(R,C)])
+            where D is a 2-D ndarray.
+
+        bsr_matrix(S, [blocksize=(R,C)])
+            with another sparse array or matrix S (equivalent to S.tobsr())
+
+        bsr_matrix((M, N), [blocksize=(R,C), dtype])
+            to construct an empty sparse matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)])
+            where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
+
+        bsr_matrix((data, indices, indptr), [shape=(M, N)])
+            is the standard BSR representation where the block column
+            indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding block values are stored in
+            ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
+            supplied, the matrix dimensions are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        BSR format data array of the matrix
+    indices
+        BSR format index array of the matrix
+    indptr
+        BSR format index pointer array of the matrix
+    blocksize
+        Block size
+    has_sorted_indices : bool
+        Whether indices are sorted
+    has_canonical_format : bool
+    T
+
+    Notes
+    -----
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    **Summary of BSR format**
+
+    The Block Sparse Row (BSR) format is very similar to the Compressed
+    Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
+    sub matrices like the last example below. Such sparse block matrices often
+    arise in vector-valued finite element discretizations. In such cases, BSR is
+    considerably more efficient than CSR and CSC for many sparse arithmetic
+    operations.
+
+    **Blocksize**
+
+    The blocksize (R,C) must evenly divide the shape of the sparse matrix (M,N).
+    That is, R and C must satisfy the relationship ``M % R = 0`` and
+    ``N % C = 0``.
+
+    If no blocksize is specified, a simple heuristic is applied to determine
+    an appropriate blocksize.
+
+    **Canonical Format**
+
+    In canonical format, there are no duplicate blocks and indices are sorted
+    per row.
+
+    **Limitations**
+
+    Block Sparse Row format sparse matrices do not support slicing.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import bsr_matrix
+    >>> bsr_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3 ,4, 5, 6])
+    >>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
+    >>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
+    array([[1, 1, 0, 0, 2, 2],
+           [1, 1, 0, 0, 2, 2],
+           [0, 0, 0, 0, 3, 3],
+           [0, 0, 0, 0, 3, 3],
+           [4, 4, 5, 5, 6, 6],
+           [4, 4, 5, 5, 6, 6]])
+
+    """
+
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_compressed.py b/venv/lib/python3.10/site-packages/scipy/sparse/_compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5f43c16bd924ac6bd70cfd4634dc3afcd298391
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_compressed.py
@@ -0,0 +1,1500 @@
+"""Base class for sparse matrix formats using compressed storage."""
+__all__ = []
+
+from warnings import warn
+import itertools
+import operator
+
+import numpy as np
+from scipy._lib._util import _prune_array, copy_if_needed
+
+from ._base import _spbase, issparse, sparray, SparseEfficiencyWarning
+from ._data import _data_matrix, _minmax_mixin
+from . import _sparsetools
+from ._sparsetools import (get_csr_submatrix, csr_sample_offsets, csr_todense,
+                           csr_sample_values, csr_row_index, csr_row_slice,
+                           csr_column_index1, csr_column_index2)
+from ._index import IndexMixin
+from ._sputils import (upcast, upcast_char, to_native, isdense, isshape,
+                       getdtype, isscalarlike, isintlike, downcast_intp_index,
+                       get_sum_dtype, check_shape, get_index_dtype, broadcast_shapes,
+                       is_pydata_spmatrix)
+
+
+class _cs_matrix(_data_matrix, _minmax_mixin, IndexMixin):
+    """
+    base array/matrix class for compressed row- and column-oriented arrays/matrices
+    """
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+
+        if issparse(arg1):
+            if arg1.format == self.format and copy:
+                arg1 = arg1.copy()
+            else:
+                arg1 = arg1.asformat(self.format)
+            self.indptr, self.indices, self.data, self._shape = (
+                arg1.indptr, arg1.indices, arg1.data, arg1._shape
+            )
+
+        elif isinstance(arg1, tuple):
+            if isshape(arg1, allow_nd=self._allow_nd):
+                # It's a tuple of matrix dimensions (M, N)
+                # create empty matrix
+                self._shape = check_shape(arg1, allow_nd=self._allow_nd)
+                M, N = self._swap(self._shape_as_2d)
+                # Select index dtype large enough to pass array and
+                # scalar parameters to sparsetools
+                idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+                self.data = np.zeros(0, getdtype(dtype, default=float))
+                self.indices = np.zeros(0, idx_dtype)
+                self.indptr = np.zeros(M + 1, dtype=idx_dtype)
+            else:
+                if len(arg1) == 2:
+                    # (data, ij) format
+                    coo = self._coo_container(arg1, shape=shape, dtype=dtype)
+                    arrays = coo._coo_to_compressed(self._swap)
+                    self.indptr, self.indices, self.data, self._shape = arrays
+                    self.sum_duplicates()
+                elif len(arg1) == 3:
+                    # (data, indices, indptr) format
+                    (data, indices, indptr) = arg1
+
+                    # Select index dtype large enough to pass array and
+                    # scalar parameters to sparsetools
+                    maxval = None
+                    if shape is not None and 0 not in shape:
+                        maxval = max(shape)
+                    idx_dtype = self._get_index_dtype((indices, indptr),
+                                                maxval=maxval,
+                                                check_contents=True)
+
+                    if not copy:
+                        copy = copy_if_needed
+                    self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
+                    self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
+                    self.data = np.array(data, copy=copy, dtype=dtype)
+                else:
+                    raise ValueError(f"unrecognized {self.__class__.__name__} "
+                                     f"constructor input: {arg1}")
+
+        else:
+            # must be dense
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise ValueError(f"unrecognized {self.__class__.__name__} "
+                                 f"constructor input: {arg1}") from e
+            if isinstance(self, sparray) and arg1.ndim != 2 and self.format == "csc":
+                raise ValueError(f"CSC arrays don't support {arg1.ndim}D input. Use 2D")
+            if arg1.ndim > 2:
+                raise ValueError(f"CSR arrays don't yet support {arg1.ndim}D.")
+
+            coo = self._coo_container(arg1, dtype=dtype)
+            arrays = coo._coo_to_compressed(self._swap)
+            self.indptr, self.indices, self.data, self._shape = arrays
+
+        # Read matrix dimensions given, if any
+        if shape is not None:
+            self._shape = check_shape(shape, allow_nd=self._allow_nd)
+        elif self.shape is None:
+            # shape not already set, try to infer dimensions
+            try:
+                M = len(self.indptr) - 1
+                N = self.indices.max() + 1
+            except Exception as e:
+                raise ValueError('unable to infer matrix dimensions') from e
+
+            self._shape = check_shape(self._swap((M, N)), allow_nd=self._allow_nd)
+
+        if dtype is not None:
+            newdtype = getdtype(dtype)
+            self.data = self.data.astype(newdtype, copy=False)
+
+        self.check_format(full_check=False)
+
+    def _getnnz(self, axis=None):
+        if axis is None:
+            return int(self.indptr[-1])
+        elif self.ndim == 1:
+            if axis in (0, -1):
+                return int(self.indptr[-1])
+            raise ValueError('axis out of bounds')
+        else:
+            if axis < 0:
+                axis += 2
+            axis, _ = self._swap((axis, 1 - axis))
+            _, N = self._swap(self.shape)
+            if axis == 0:
+                return np.bincount(downcast_intp_index(self.indices), minlength=N)
+            elif axis == 1:
+                return np.diff(self.indptr)
+            raise ValueError('axis out of bounds')
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        self.sum_duplicates()
+        if axis is None:
+            return np.count_nonzero(self.data)
+
+        if self.ndim == 1:
+            if axis not in (0, -1):
+                raise ValueError('axis out of bounds')
+            return np.count_nonzero(self.data)
+
+        if axis < 0:
+            axis += 2
+        axis, _ = self._swap((axis, 1 - axis))
+        if axis == 0:
+            _, N = self._swap(self.shape)
+            mask = self.data != 0
+            idx = self.indices if mask.all() else self.indices[mask]
+            return np.bincount(downcast_intp_index(idx), minlength=N)
+        elif axis == 1:
+            if self.data.all():
+                return np.diff(self.indptr)
+            pairs = itertools.pairwise(self.indptr)
+            return np.array([np.count_nonzero(self.data[i:j]) for i, j in pairs])
+        else:
+            raise ValueError('axis out of bounds')
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def check_format(self, full_check=True):
+        """Check whether the array/matrix respects the CSR or CSC format.
+
+        Parameters
+        ----------
+        full_check : bool, optional
+            If `True`, run rigorous check, scanning arrays for valid values.
+            Note that activating those check might copy arrays for casting,
+            modifying indices and index pointers' inplace.
+            If `False`, run basic checks on attributes. O(1) operations.
+            Default is `True`.
+        """
+        # index arrays should have integer data types
+        if self.indptr.dtype.kind != 'i':
+            warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
+                 stacklevel=3)
+        if self.indices.dtype.kind != 'i':
+            warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
+                 stacklevel=3)
+
+        # check array shapes
+        for x in [self.data.ndim, self.indices.ndim, self.indptr.ndim]:
+            if x != 1:
+                raise ValueError('data, indices, and indptr should be 1-D')
+
+        # check index pointer. Use _swap to determine proper bounds
+        M, N = self._swap(self._shape_as_2d)
+
+        if (len(self.indptr) != M + 1):
+            raise ValueError(f"index pointer size {len(self.indptr)} should be {M + 1}")
+        if (self.indptr[0] != 0):
+            raise ValueError("index pointer should start with 0")
+
+        # check index and data arrays
+        if (len(self.indices) != len(self.data)):
+            raise ValueError("indices and data should have the same size")
+        if (self.indptr[-1] > len(self.indices)):
+            raise ValueError("Last value of index pointer should be less than "
+                             "the size of index and data arrays")
+
+        self.prune()
+
+        if full_check:
+            # check format validity (more expensive)
+            if self.nnz > 0:
+                if self.indices.max() >= N:
+                    raise ValueError(f"indices must be < {N}")
+                if self.indices.min() < 0:
+                    raise ValueError("indices must be >= 0")
+                if np.diff(self.indptr).min() < 0:
+                    raise ValueError("indptr must be a non-decreasing sequence")
+
+            idx_dtype = self._get_index_dtype((self.indptr, self.indices))
+            self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+            self.indices = np.asarray(self.indices, dtype=idx_dtype)
+            self.data = to_native(self.data)
+
+        # if not self.has_sorted_indices():
+        #    warn('Indices were not in sorted order.  Sorting indices.')
+        #    self.sort_indices()
+        #    assert(self.has_sorted_indices())
+        # TODO check for duplicates?
+
+    #######################
+    # Boolean comparisons #
+    #######################
+
+    def _scalar_binopt(self, other, op):
+        """Scalar version of self._binopt, for cases in which no new nonzeros
+        are added. Produces a new sparse array in canonical form.
+        """
+        self.sum_duplicates()
+        res = self._with_data(op(self.data, other), copy=True)
+        res.eliminate_zeros()
+        return res
+
+    def __eq__(self, other):
+        # Scalar other.
+        if isscalarlike(other):
+            if np.isnan(other):
+                return self.__class__(self.shape, dtype=np.bool_)
+
+            if other == 0:
+                warn("Comparing a sparse matrix with 0 using == is inefficient"
+                     ", try using != instead.", SparseEfficiencyWarning,
+                     stacklevel=3)
+                all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+                inv = self._scalar_binopt(other, operator.ne)
+                return all_true - inv
+            else:
+                return self._scalar_binopt(other, operator.eq)
+        # Dense other.
+        elif isdense(other):
+            return self.todense() == other
+        # Pydata sparse other.
+        elif is_pydata_spmatrix(other):
+            return NotImplemented
+        # Sparse other.
+        elif issparse(other):
+            warn("Comparing sparse matrices using == is inefficient, try using"
+                 " != instead.", SparseEfficiencyWarning, stacklevel=3)
+            # TODO sparse broadcasting
+            if self.shape != other.shape:
+                return False
+            elif self.format != other.format:
+                other = other.asformat(self.format)
+            res = self._binopt(other, '_ne_')
+            all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+            return all_true - res
+        else:
+            return NotImplemented
+
+    def __ne__(self, other):
+        # Scalar other.
+        if isscalarlike(other):
+            if np.isnan(other):
+                warn("Comparing a sparse matrix with nan using != is"
+                     " inefficient", SparseEfficiencyWarning, stacklevel=3)
+                all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+                return all_true
+            elif other != 0:
+                warn("Comparing a sparse matrix with a nonzero scalar using !="
+                     " is inefficient, try using == instead.",
+                     SparseEfficiencyWarning, stacklevel=3)
+                all_true = self.__class__(np.ones(self.shape), dtype=np.bool_)
+                inv = self._scalar_binopt(other, operator.eq)
+                return all_true - inv
+            else:
+                return self._scalar_binopt(other, operator.ne)
+        # Dense other.
+        elif isdense(other):
+            return self.todense() != other
+        # Pydata sparse other.
+        elif is_pydata_spmatrix(other):
+            return NotImplemented
+        # Sparse other.
+        elif issparse(other):
+            # TODO sparse broadcasting
+            if self.shape != other.shape:
+                return True
+            elif self.format != other.format:
+                other = other.asformat(self.format)
+            return self._binopt(other, '_ne_')
+        else:
+            return NotImplemented
+
+    def _inequality(self, other, op, op_name, bad_scalar_msg):
+        # Scalar other.
+        if isscalarlike(other):
+            if 0 == other and op_name in ('_le_', '_ge_'):
+                raise NotImplementedError(" >= and <= don't work with 0.")
+            elif op(0, other):
+                warn(bad_scalar_msg, SparseEfficiencyWarning, stacklevel=3)
+                other_arr = np.empty(self.shape, dtype=np.result_type(other))
+                other_arr.fill(other)
+                other_arr = self.__class__(other_arr)
+                return self._binopt(other_arr, op_name)
+            else:
+                return self._scalar_binopt(other, op)
+        # Dense other.
+        elif isdense(other):
+            return op(self.todense(), other)
+        # Sparse other.
+        elif issparse(other):
+            # TODO sparse broadcasting
+            if self.shape != other.shape:
+                raise ValueError("inconsistent shapes")
+            elif self.format != other.format:
+                other = other.asformat(self.format)
+            if op_name not in ('_ge_', '_le_'):
+                return self._binopt(other, op_name)
+
+            warn("Comparing sparse matrices using >= and <= is inefficient, "
+                 "using <, >, or !=, instead.",
+                 SparseEfficiencyWarning, stacklevel=3)
+            all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+            res = self._binopt(other, '_gt_' if op_name == '_le_' else '_lt_')
+            return all_true - res
+        else:
+            return NotImplemented
+
+    def __lt__(self, other):
+        return self._inequality(other, operator.lt, '_lt_',
+                                "Comparing a sparse matrix with a scalar "
+                                "greater than zero using < is inefficient, "
+                                "try using >= instead.")
+
+    def __gt__(self, other):
+        return self._inequality(other, operator.gt, '_gt_',
+                                "Comparing a sparse matrix with a scalar "
+                                "less than zero using > is inefficient, "
+                                "try using <= instead.")
+
+    def __le__(self, other):
+        return self._inequality(other, operator.le, '_le_',
+                                "Comparing a sparse matrix with a scalar "
+                                "greater than zero using <= is inefficient, "
+                                "try using > instead.")
+
+    def __ge__(self, other):
+        return self._inequality(other, operator.ge, '_ge_',
+                                "Comparing a sparse matrix with a scalar "
+                                "less than zero using >= is inefficient, "
+                                "try using < instead.")
+
+    #################################
+    # Arithmetic operator overrides #
+    #################################
+
+    def _add_dense(self, other):
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        dtype = upcast_char(self.dtype.char, other.dtype.char)
+        order = self._swap('CF')[0]
+        result = np.array(other, dtype=dtype, order=order, copy=True)
+        y = result if result.flags.c_contiguous else result.T
+        M, N = self._swap(self._shape_as_2d)
+        csr_todense(M, N, self.indptr, self.indices, self.data, y)
+        return self._container(result, copy=False)
+
+    def _add_sparse(self, other):
+        return self._binopt(other, '_plus_')
+
+    def _sub_sparse(self, other):
+        return self._binopt(other, '_minus_')
+
+    def multiply(self, other):
+        """Point-wise multiplication by array/matrix, vector, or scalar."""
+        # Scalar multiplication.
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        # Sparse matrix or vector.
+        if issparse(other):
+            if self.shape == other.shape:
+                other = self.__class__(other)
+                return self._binopt(other, '_elmul_')
+            # Single element.
+            if other.shape == (1, 1):
+                result = self._mul_scalar(other.toarray()[0, 0])
+                if self.ndim == 1:
+                    return result.reshape((1, self.shape[0]))
+                return result
+            if other.shape == (1,):
+                return self._mul_scalar(other.toarray()[0])
+            if self.shape in ((1,), (1, 1)):
+                return other._mul_scalar(self.data.sum())
+
+            # broadcast. treat 1d like a row
+            sM, sN = self._shape_as_2d
+            oM, oN = other._shape_as_2d
+            # A row times a column.
+            if sM == 1 and oN == 1:
+                return other._matmul_sparse(self.reshape(sM, sN).tocsc())
+            if sN == 1 and oM == 1:
+                return self._matmul_sparse(other.reshape(oM, oN).tocsc())
+
+            is_array = isinstance(self, sparray)
+            # Other is a row.
+            if oM == 1 and sN == oN:
+                new_other = _make_diagonal_csr(other.toarray().ravel(), is_array)
+                result = self._matmul_sparse(new_other)
+                return result if self.ndim == 2 else result.reshape((1, oN))
+            # self is a row.
+            if sM == 1 and sN == oN:
+                copy = _make_diagonal_csr(self.toarray().ravel(), is_array)
+                return other._matmul_sparse(copy)
+
+            # Other is a column.
+            if oN == 1 and sM == oM:
+                new_other = _make_diagonal_csr(other.toarray().ravel(), is_array)
+                return new_other._matmul_sparse(self)
+            # self is a column.
+            if sN == 1 and sM == oM:
+                new_self = _make_diagonal_csr(self.toarray().ravel(), is_array)
+                return new_self._matmul_sparse(other)
+            raise ValueError("inconsistent shapes")
+
+        # Assume other is a dense matrix/array, which produces a single-item
+        # object array if other isn't convertible to ndarray.
+        other = np.asanyarray(other)
+
+        if other.ndim > 2:
+            return np.multiply(self.toarray(), other)
+        # Single element / wrapped object.
+        if other.size == 1:
+            if other.dtype == np.object_:
+                # 'other' not convertible to ndarray.
+                return NotImplemented
+            bshape = broadcast_shapes(self.shape, other.shape)
+            return self._mul_scalar(other.flat[0]).reshape(bshape)
+        # Fast case for trivial sparse matrix.
+        if self.shape in ((1,), (1, 1)):
+            bshape = broadcast_shapes(self.shape, other.shape)
+            return np.multiply(self.data.sum(), other).reshape(bshape)
+
+        ret = self.tocoo()
+        # Matching shapes.
+        if self.shape == other.shape:
+            data = np.multiply(ret.data, other[ret.coords])
+            ret.data = data.view(np.ndarray).ravel()
+            return ret
+
+        # convert other to 2d
+        other2d = np.atleast_2d(other)
+        # Sparse row vector times...
+        if self.shape[0] == 1 or self.ndim == 1:
+            if other2d.shape[1] == 1:  # Dense column vector.
+                data = np.multiply(ret.data, other2d)
+            elif other2d.shape[1] == self.shape[-1]:  # Dense 2d matrix.
+                data = np.multiply(ret.data, other2d[:, ret.col])
+            else:
+                raise ValueError("inconsistent shapes")
+            idx_dtype = self._get_index_dtype(ret.col,
+                                              maxval=ret.nnz * other2d.shape[0])
+            row = np.repeat(np.arange(other2d.shape[0], dtype=idx_dtype), ret.nnz)
+            col = np.tile(ret.col.astype(idx_dtype, copy=False), other2d.shape[0])
+            return self._coo_container(
+                (data.view(np.ndarray).ravel(), (row, col)),
+                shape=(other2d.shape[0], self.shape[-1]),
+                copy=False
+            )
+        # Sparse column vector times...
+        if self.shape[1] == 1:
+            if other2d.shape[0] == 1:  # Dense row vector.
+                data = np.multiply(ret.data[:, None], other2d)
+            elif other2d.shape[0] == self.shape[0]:  # Dense 2d array.
+                data = np.multiply(ret.data[:, None], other2d[ret.row])
+            else:
+                raise ValueError("inconsistent shapes")
+            idx_dtype = self._get_index_dtype(ret.row,
+                                              maxval=ret.nnz * other2d.shape[1])
+            row = np.repeat(ret.row.astype(idx_dtype, copy=False), other2d.shape[1])
+            col = np.tile(np.arange(other2d.shape[1], dtype=idx_dtype), ret.nnz)
+            return self._coo_container(
+                (data.view(np.ndarray).ravel(), (row, col)),
+                shape=(self.shape[0], other2d.shape[1]),
+                copy=False
+            )
+        # Sparse matrix times dense row vector.
+        if other2d.shape[0] == 1 and self.shape[1] == other2d.shape[1]:
+            data = np.multiply(ret.data, other2d[:, ret.col].ravel())
+        # Sparse matrix times dense column vector.
+        elif other2d.shape[1] == 1 and self.shape[0] == other2d.shape[0]:
+            data = np.multiply(ret.data, other2d[ret.row].ravel())
+        else:
+            raise ValueError("inconsistent shapes")
+        ret.data = data.view(np.ndarray).ravel()
+        return ret
+
+    ###########################
+    # Multiplication handlers #
+    ###########################
+
+    def _matmul_vector(self, other):
+        M, N = self._shape_as_2d
+
+        # output array
+        result = np.zeros(M, dtype=upcast_char(self.dtype.char, other.dtype.char))
+
+        # csr_matvec or csc_matvec
+        fn = getattr(_sparsetools, self.format + '_matvec')
+        fn(M, N, self.indptr, self.indices, self.data, other, result)
+
+        return result[0] if self.ndim == 1 else result
+
+    def _matmul_multivector(self, other):
+        M, N = self._shape_as_2d
+        n_vecs = other.shape[-1]  # number of column vectors
+
+        result = np.zeros((M, n_vecs),
+                          dtype=upcast_char(self.dtype.char, other.dtype.char))
+
+        # csr_matvecs or csc_matvecs
+        fn = getattr(_sparsetools, self.format + '_matvecs')
+        fn(M, N, n_vecs, self.indptr, self.indices, self.data,
+           other.ravel(), result.ravel())
+
+        if self.ndim == 1:
+            return result.reshape((n_vecs,))
+        return result
+
+    def _matmul_sparse(self, other):
+        M, K1 = self._shape_as_2d
+        # if other is 1d, treat as a **column**
+        o_ndim = other.ndim
+        if o_ndim == 1:
+            # convert 1d array to a 2d column when on the right of @
+            other = other.reshape((1, other.shape[0])).T  # Note: converts to CSC
+        K2, N = other._shape if other.ndim == 2 else (other.shape[0], 1)
+
+        # find new_shape: (M, N), (M,), (N,) or ()
+        new_shape = ()
+        if self.ndim == 2:
+            new_shape += (M,)
+        if o_ndim == 2:
+            new_shape += (N,)
+        faux_shape = (M if self.ndim == 2 else 1, N if o_ndim == 2 else 1)
+
+        major_dim = self._swap((M, N))[0]
+        other = self.__class__(other)  # convert to this format
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                     other.indptr, other.indices))
+
+        fn = getattr(_sparsetools, self.format + '_matmat_maxnnz')
+        nnz = fn(M, N,
+                 np.asarray(self.indptr, dtype=idx_dtype),
+                 np.asarray(self.indices, dtype=idx_dtype),
+                 np.asarray(other.indptr, dtype=idx_dtype),
+                 np.asarray(other.indices, dtype=idx_dtype))
+        if nnz == 0:
+            if new_shape == ():
+                return np.array(0, dtype=upcast(self.dtype, other.dtype))
+            return self.__class__(new_shape, dtype=upcast(self.dtype, other.dtype))
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                     other.indptr, other.indices),
+                                    maxval=nnz)
+
+        indptr = np.empty(major_dim + 1, dtype=idx_dtype)
+        indices = np.empty(nnz, dtype=idx_dtype)
+        data = np.empty(nnz, dtype=upcast(self.dtype, other.dtype))
+
+        fn = getattr(_sparsetools, self.format + '_matmat')
+        fn(M, N, np.asarray(self.indptr, dtype=idx_dtype),
+           np.asarray(self.indices, dtype=idx_dtype),
+           self.data,
+           np.asarray(other.indptr, dtype=idx_dtype),
+           np.asarray(other.indices, dtype=idx_dtype),
+           other.data,
+           indptr, indices, data)
+
+        if new_shape == ():
+            return np.array(data[0])
+        res = self.__class__((data, indices, indptr), shape=faux_shape)
+        if faux_shape != new_shape:
+            if res.format != 'csr':
+                res = res.tocsr()
+            res = res.reshape(new_shape)
+        return res
+
+    def diagonal(self, k=0):
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        fn = getattr(_sparsetools, self.format + "_diagonal")
+        y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),
+                     dtype=upcast(self.dtype))
+        fn(k, self.shape[0], self.shape[1], self.indptr, self.indices,
+           self.data, y)
+        return y
+
+    diagonal.__doc__ = _spbase.diagonal.__doc__
+
+    #####################
+    # Other binary ops  #
+    #####################
+
+    def _maximum_minimum(self, other, npop, op_name, dense_check):
+        if isscalarlike(other):
+            if dense_check(other):
+                warn("Taking maximum (minimum) with > 0 (< 0) number results"
+                     " to a dense matrix.", SparseEfficiencyWarning,
+                     stacklevel=3)
+                other_arr = np.empty(self.shape, dtype=np.asarray(other).dtype)
+                other_arr.fill(other)
+                other_arr = self.__class__(other_arr)
+                return self._binopt(other_arr, op_name)
+            else:
+                self.sum_duplicates()
+                new_data = npop(self.data, np.asarray(other))
+                mat = self.__class__((new_data, self.indices, self.indptr),
+                                     dtype=new_data.dtype, shape=self.shape)
+                return mat
+        elif isdense(other):
+            return npop(self.todense(), other)
+        elif issparse(other):
+            return self._binopt(other, op_name)
+        else:
+            raise ValueError("Operands not compatible.")
+
+    def maximum(self, other):
+        return self._maximum_minimum(other, np.maximum,
+                                     '_maximum_', lambda x: np.asarray(x) > 0)
+
+    maximum.__doc__ = _spbase.maximum.__doc__
+
+    def minimum(self, other):
+        return self._maximum_minimum(other, np.minimum,
+                                     '_minimum_', lambda x: np.asarray(x) < 0)
+
+    minimum.__doc__ = _spbase.minimum.__doc__
+
+    #####################
+    # Reduce operations #
+    #####################
+
+    def sum(self, axis=None, dtype=None, out=None):
+        """Sum the array/matrix over the given axis.  If the axis is None, sum
+        over both rows and columns, returning a scalar.
+        """
+        # The _spbase base class already does axis=0 and axis=1 efficiently
+        # so we only do the case axis=None here
+        if (self.ndim == 2 and not hasattr(self, 'blocksize') and
+                axis in self._swap(((1, -1), (0, -2)))[0]):
+            # faster than multiplication for large minor axis in CSC/CSR
+            res_dtype = get_sum_dtype(self.dtype)
+            ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype)
+
+            major_index, value = self._minor_reduce(np.add)
+            ret[major_index] = value
+            ret = self._ascontainer(ret)
+            if axis % 2 == 1:
+                ret = ret.T
+
+            return ret.sum(axis=(), dtype=dtype, out=out)
+        else:
+            # _spbase handles the situations when axis is in {None, -2, -1, 0, 1}
+            return _spbase.sum(self, axis=axis, dtype=dtype, out=out)
+
+    sum.__doc__ = _spbase.sum.__doc__
+
+    def _minor_reduce(self, ufunc, data=None):
+        """Reduce nonzeros with a ufunc over the minor axis when non-empty
+
+        Can be applied to a function of self.data by supplying data parameter.
+
+        Warning: this does not call sum_duplicates()
+
+        Returns
+        -------
+        major_index : array of ints
+            Major indices where nonzero
+
+        value : array of self.dtype
+            Reduce result for nonzeros in each major_index
+        """
+        if data is None:
+            data = self.data
+        major_index = np.flatnonzero(np.diff(self.indptr))
+        value = ufunc.reduceat(data,
+                               downcast_intp_index(self.indptr[major_index]))
+        return major_index, value
+
+    #######################
+    # Getting and Setting #
+    #######################
+
+    def _get_intXint(self, row, col):
+        M, N = self._swap(self.shape)
+        major, minor = self._swap((row, col))
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data,
+            major, major + 1, minor, minor + 1)
+        return data.sum(dtype=self.dtype)
+
+    def _get_sliceXslice(self, row, col):
+        major, minor = self._swap((row, col))
+        if major.step in (1, None) and minor.step in (1, None):
+            return self._get_submatrix(major, minor, copy=True)
+        return self._major_slice(major)._minor_slice(minor)
+
+    def _get_arrayXarray(self, row, col):
+        # inner indexing
+        idx_dtype = self.indices.dtype
+        M, N = self._swap(self.shape)
+        major, minor = self._swap((row, col))
+        major = np.asarray(major, dtype=idx_dtype)
+        minor = np.asarray(minor, dtype=idx_dtype)
+
+        val = np.empty(major.size, dtype=self.dtype)
+        csr_sample_values(M, N, self.indptr, self.indices, self.data,
+                          major.size, major.ravel(), minor.ravel(), val)
+        if major.ndim == 1:
+            return self._ascontainer(val)
+        return self.__class__(val.reshape(major.shape))
+
+    def _get_columnXarray(self, row, col):
+        # outer indexing
+        major, minor = self._swap((row, col))
+        return self._major_index_fancy(major)._minor_index_fancy(minor)
+
+    def _major_index_fancy(self, idx):
+        """Index along the major axis where idx is an array of ints.
+        """
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices))
+        indices = np.asarray(idx, dtype=idx_dtype).ravel()
+
+        N = self._swap(self._shape_as_2d)[1]
+        M = len(indices)
+        new_shape = self._swap((M, N)) if self.ndim == 2 else (M,)
+        if M == 0:
+            return self.__class__(new_shape, dtype=self.dtype)
+
+        row_nnz = (self.indptr[indices + 1] - self.indptr[indices]).astype(idx_dtype)
+        res_indptr = np.zeros(M + 1, dtype=idx_dtype)
+        np.cumsum(row_nnz, out=res_indptr[1:])
+
+        nnz = res_indptr[-1]
+        res_indices = np.empty(nnz, dtype=idx_dtype)
+        res_data = np.empty(nnz, dtype=self.dtype)
+        csr_row_index(
+            M,
+            indices,
+            self.indptr.astype(idx_dtype, copy=False),
+            self.indices.astype(idx_dtype, copy=False),
+            self.data,
+            res_indices,
+            res_data
+        )
+
+        return self.__class__((res_data, res_indices, res_indptr),
+                              shape=new_shape, copy=False)
+
+    def _major_slice(self, idx, copy=False):
+        """Index along the major axis where idx is a slice object.
+        """
+        if idx == slice(None):
+            return self.copy() if copy else self
+
+        M, N = self._swap(self._shape_as_2d)
+        start, stop, step = idx.indices(M)
+        M = len(range(start, stop, step))
+        new_shape = self._swap((M, N)) if self.ndim == 2 else (M,)
+        if M == 0:
+            return self.__class__(new_shape, dtype=self.dtype)
+
+        # Work out what slices are needed for `row_nnz`
+        # start,stop can be -1, only if step is negative
+        start0, stop0 = start, stop
+        if stop == -1 and start >= 0:
+            stop0 = None
+        start1, stop1 = start + 1, stop + 1
+
+        row_nnz = self.indptr[start1:stop1:step] - \
+            self.indptr[start0:stop0:step]
+        idx_dtype = self.indices.dtype
+        res_indptr = np.zeros(M+1, dtype=idx_dtype)
+        np.cumsum(row_nnz, out=res_indptr[1:])
+
+        if step == 1:
+            all_idx = slice(self.indptr[start], self.indptr[stop])
+            res_indices = np.array(self.indices[all_idx], copy=copy)
+            res_data = np.array(self.data[all_idx], copy=copy)
+        else:
+            nnz = res_indptr[-1]
+            res_indices = np.empty(nnz, dtype=idx_dtype)
+            res_data = np.empty(nnz, dtype=self.dtype)
+            csr_row_slice(start, stop, step, self.indptr, self.indices,
+                          self.data, res_indices, res_data)
+
+        return self.__class__((res_data, res_indices, res_indptr),
+                              shape=new_shape, copy=False)
+
+    def _minor_index_fancy(self, idx):
+        """Index along the minor axis where idx is an array of ints.
+        """
+        idx_dtype = self._get_index_dtype((self.indices, self.indptr))
+        indices = self.indices.astype(idx_dtype, copy=False)
+        indptr = self.indptr.astype(idx_dtype, copy=False)
+
+        idx = np.asarray(idx, dtype=idx_dtype).ravel()
+
+        M, N = self._swap(self._shape_as_2d)
+        k = len(idx)
+        new_shape = self._swap((M, k)) if self.ndim == 2 else (k,)
+        if k == 0:
+            return self.__class__(new_shape, dtype=self.dtype)
+
+        # pass 1: count idx entries and compute new indptr
+        col_offsets = np.zeros(N, dtype=idx_dtype)
+        res_indptr = np.empty_like(self.indptr, dtype=idx_dtype)
+        csr_column_index1(
+            k,
+            idx,
+            M,
+            N,
+            indptr,
+            indices,
+            col_offsets,
+            res_indptr,
+        )
+
+        # pass 2: copy indices/data for selected idxs
+        col_order = np.argsort(idx).astype(idx_dtype, copy=False)
+        nnz = res_indptr[-1]
+        res_indices = np.empty(nnz, dtype=idx_dtype)
+        res_data = np.empty(nnz, dtype=self.dtype)
+        csr_column_index2(col_order, col_offsets, len(self.indices),
+                          indices, self.data, res_indices, res_data)
+        return self.__class__((res_data, res_indices, res_indptr),
+                              shape=new_shape, copy=False)
+
+    def _minor_slice(self, idx, copy=False):
+        """Index along the minor axis where idx is a slice object.
+        """
+        if idx == slice(None):
+            return self.copy() if copy else self
+
+        M, N = self._swap(self._shape_as_2d)
+        start, stop, step = idx.indices(N)
+        N = len(range(start, stop, step))
+        if N == 0:
+            return self.__class__(self._swap((M, N)), dtype=self.dtype)
+        if step == 1:
+            return self._get_submatrix(minor=idx, copy=copy)
+        # TODO: don't fall back to fancy indexing here
+        return self._minor_index_fancy(np.arange(start, stop, step))
+
+    def _get_submatrix(self, major=None, minor=None, copy=False):
+        """Return a submatrix of this matrix.
+
+        major, minor: None, int, or slice with step 1
+        """
+        M, N = self._swap(self._shape_as_2d)
+        i0, i1 = _process_slice(major, M)
+        j0, j1 = _process_slice(minor, N)
+
+        if i0 == 0 and j0 == 0 and i1 == M and j1 == N:
+            return self.copy() if copy else self
+
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data, i0, i1, j0, j1)
+
+        shape = self._swap((i1 - i0, j1 - j0))
+        if self.ndim == 1:
+            shape = (shape[1],)
+        return self.__class__((data, indices, indptr), shape=shape,
+                              dtype=self.dtype, copy=False)
+
+    def _set_intXint(self, row, col, x):
+        i, j = self._swap((row, col))
+        self._set_many(i, j, x)
+
+    def _set_arrayXarray(self, row, col, x):
+        i, j = self._swap((row, col))
+        self._set_many(i, j, x)
+
+    def _set_arrayXarray_sparse(self, row, col, x):
+        # clear entries that will be overwritten
+        self._zero_many(*self._swap((row, col)))
+
+        M, N = row.shape  # matches col.shape
+        broadcast_row = M != 1 and x.shape[0] == 1
+        broadcast_col = N != 1 and x.shape[1] == 1
+        r, c = x.row, x.col
+
+        x = np.asarray(x.data, dtype=self.dtype)
+        if x.size == 0:
+            return
+
+        if broadcast_row:
+            r = np.repeat(np.arange(M), len(r))
+            c = np.tile(c, M)
+            x = np.tile(x, M)
+        if broadcast_col:
+            r = np.repeat(r, N)
+            c = np.tile(np.arange(N), len(c))
+            x = np.repeat(x, N)
+        # only assign entries in the new sparsity structure
+        i, j = self._swap((row[r, c], col[r, c]))
+        self._set_many(i, j, x)
+
+    def _setdiag(self, values, k):
+        if 0 in self.shape:
+            return
+        if self.ndim == 1:
+            raise NotImplementedError('diagonals cant be set in 1d arrays')
+
+        M, N = self.shape
+        broadcast = (values.ndim == 0)
+
+        if k < 0:
+            if broadcast:
+                max_index = min(M + k, N)
+            else:
+                max_index = min(M + k, N, len(values))
+            i = np.arange(-k, max_index - k, dtype=self.indices.dtype)
+            j = np.arange(max_index, dtype=self.indices.dtype)
+
+        else:
+            if broadcast:
+                max_index = min(M, N - k)
+            else:
+                max_index = min(M, N - k, len(values))
+            i = np.arange(max_index, dtype=self.indices.dtype)
+            j = np.arange(k, k + max_index, dtype=self.indices.dtype)
+
+        if not broadcast:
+            values = values[:len(i)]
+
+        x = np.atleast_1d(np.asarray(values, dtype=self.dtype)).ravel()
+        if x.squeeze().shape != i.squeeze().shape:
+            x = np.broadcast_to(x, i.shape)
+        if x.size == 0:
+            return
+
+        M, N = self._swap((M, N))
+        i, j = self._swap((i, j))
+        n_samples = x.size
+        offsets = np.empty(n_samples, dtype=self.indices.dtype)
+        ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                                 i, j, offsets)
+        if ret == 1:
+            # rinse and repeat
+            self.sum_duplicates()
+            csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                               i, j, offsets)
+        if -1 not in offsets:
+            # only affects existing non-zero cells
+            self.data[offsets] = x
+            return
+
+        mask = (offsets >= 0)
+        # Boundary between csc and convert to coo
+        # The value 0.001 is justified in gh-19962#issuecomment-1920499678
+        if self.nnz - mask.sum() < self.nnz * 0.001:
+            # replace existing entries
+            self.data[offsets[mask]] = x[mask]
+            # create new entries
+            mask = ~mask
+            i = i[mask]
+            j = j[mask]
+            self._insert_many(i, j, x[mask])
+        else:
+            # convert to coo for _set_diag
+            coo = self.tocoo()
+            coo._setdiag(values, k)
+            arrays = coo._coo_to_compressed(self._swap)
+            self.indptr, self.indices, self.data, _ = arrays
+
+    def _prepare_indices(self, i, j):
+        M, N = self._swap(self._shape_as_2d)
+
+        def check_bounds(indices, bound):
+            idx = indices.max()
+            if idx >= bound:
+                raise IndexError(f'index ({idx}) out of range (>= {bound})')
+            idx = indices.min()
+            if idx < -bound:
+                raise IndexError(f'index ({idx}) out of range (< -{bound})')
+
+        i = np.atleast_1d(np.asarray(i, dtype=self.indices.dtype)).ravel()
+        j = np.atleast_1d(np.asarray(j, dtype=self.indices.dtype)).ravel()
+        check_bounds(i, M)
+        check_bounds(j, N)
+        return i, j, M, N
+
+    def _set_many(self, i, j, x):
+        """Sets value at each (i, j) to x
+
+        Here (i,j) index major and minor respectively, and must not contain
+        duplicate entries.
+        """
+        i, j, M, N = self._prepare_indices(i, j)
+        x = np.atleast_1d(np.asarray(x, dtype=self.dtype)).ravel()
+
+        n_samples = x.size
+        offsets = np.empty(n_samples, dtype=self.indices.dtype)
+        ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                                 i, j, offsets)
+        if ret == 1:
+            # rinse and repeat
+            self.sum_duplicates()
+            csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                               i, j, offsets)
+
+        if -1 not in offsets:
+            # only affects existing non-zero cells
+            self.data[offsets] = x
+            return
+
+        else:
+            warn(f"Changing the sparsity structure of a {self.__class__.__name__} is"
+                 " expensive. lil and dok are more efficient.",
+                 SparseEfficiencyWarning, stacklevel=3)
+            # replace where possible
+            mask = offsets > -1
+            self.data[offsets[mask]] = x[mask]
+            # only insertions remain
+            mask = ~mask
+            i = i[mask]
+            i[i < 0] += M
+            j = j[mask]
+            j[j < 0] += N
+            self._insert_many(i, j, x[mask])
+
+    def _zero_many(self, i, j):
+        """Sets value at each (i, j) to zero, preserving sparsity structure.
+
+        Here (i,j) index major and minor respectively.
+        """
+        i, j, M, N = self._prepare_indices(i, j)
+
+        n_samples = len(i)
+        offsets = np.empty(n_samples, dtype=self.indices.dtype)
+        ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                                 i, j, offsets)
+        if ret == 1:
+            # rinse and repeat
+            self.sum_duplicates()
+            csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                               i, j, offsets)
+
+        # only assign zeros to the existing sparsity structure
+        self.data[offsets[offsets > -1]] = 0
+
+    def _insert_many(self, i, j, x):
+        """Inserts new nonzero at each (i, j) with value x
+
+        Here (i,j) index major and minor respectively.
+        i, j and x must be non-empty, 1d arrays.
+        Inserts each major group (e.g. all entries per row) at a time.
+        Maintains has_sorted_indices property.
+        Modifies i, j, x in place.
+        """
+        order = np.argsort(i, kind='mergesort')  # stable for duplicates
+        i = i.take(order, mode='clip')
+        j = j.take(order, mode='clip')
+        x = x.take(order, mode='clip')
+
+        do_sort = self.has_sorted_indices
+
+        # Update index data type
+        idx_dtype = self._get_index_dtype((self.indices, self.indptr),
+                                    maxval=(self.indptr[-1] + x.size))
+        self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+        self.indices = np.asarray(self.indices, dtype=idx_dtype)
+        i = np.asarray(i, dtype=idx_dtype)
+        j = np.asarray(j, dtype=idx_dtype)
+
+        # Collate old and new in chunks by major index
+        indices_parts = []
+        data_parts = []
+        ui, ui_indptr = np.unique(i, return_index=True)
+        ui_indptr = np.append(ui_indptr, len(j))
+        new_nnzs = np.diff(ui_indptr)
+        prev = 0
+        for c, (ii, js, je) in enumerate(zip(ui, ui_indptr, ui_indptr[1:])):
+            # old entries
+            start = self.indptr[prev]
+            stop = self.indptr[ii]
+            indices_parts.append(self.indices[start:stop])
+            data_parts.append(self.data[start:stop])
+
+            # handle duplicate j: keep last setting
+            uj, uj_indptr = np.unique(j[js:je][::-1], return_index=True)
+            if len(uj) == je - js:
+                indices_parts.append(j[js:je])
+                data_parts.append(x[js:je])
+            else:
+                indices_parts.append(j[js:je][::-1][uj_indptr])
+                data_parts.append(x[js:je][::-1][uj_indptr])
+                new_nnzs[c] = len(uj)
+
+            prev = ii
+
+        # remaining old entries
+        start = self.indptr[ii]
+        indices_parts.append(self.indices[start:])
+        data_parts.append(self.data[start:])
+
+        # update attributes
+        self.indices = np.concatenate(indices_parts)
+        self.data = np.concatenate(data_parts)
+        nnzs = np.empty(self.indptr.shape, dtype=idx_dtype)
+        nnzs[0] = idx_dtype(0)
+        indptr_diff = np.diff(self.indptr)
+        indptr_diff[ui] += new_nnzs
+        nnzs[1:] = indptr_diff
+        self.indptr = np.cumsum(nnzs, out=nnzs)
+
+        if do_sort:
+            # TODO: only sort where necessary
+            self.has_sorted_indices = False
+            self.sort_indices()
+
+        self.check_format(full_check=False)
+
+    ######################
+    # Conversion methods #
+    ######################
+
+    def tocoo(self, copy=True):
+        if self.ndim == 1:
+            csr = self.tocsr()
+            return self._coo_container((csr.data, (csr.indices,)), csr.shape, copy=copy)
+        major_dim, minor_dim = self._swap(self.shape)
+        minor_indices = self.indices
+        major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)
+        _sparsetools.expandptr(major_dim, self.indptr, major_indices)
+        coords = self._swap((major_indices, minor_indices))
+
+        return self._coo_container(
+            (self.data, coords), self.shape, copy=copy, dtype=self.dtype
+        )
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    def toarray(self, order=None, out=None):
+        if out is None and order is None:
+            order = self._swap('cf')[0]
+        out = self._process_toarray_args(order, out)
+        if not (out.flags.c_contiguous or out.flags.f_contiguous):
+            raise ValueError('Output array must be C or F contiguous')
+        # align ideal order with output array order
+        if out.flags.c_contiguous:
+            x = self.tocsr()
+            y = out
+        else:
+            x = self.tocsc()
+            y = out.T
+        M, N = x._swap(x._shape_as_2d)
+        csr_todense(M, N, x.indptr, x.indices, x.data, y)
+        return out
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    ##############################################################
+    # methods that examine or modify the internal data structure #
+    ##############################################################
+
+    def eliminate_zeros(self):
+        """Remove zero entries from the array/matrix
+
+        This is an *in place* operation.
+        """
+        M, N = self._swap(self._shape_as_2d)
+        _sparsetools.csr_eliminate_zeros(M, N, self.indptr, self.indices, self.data)
+        self.prune()  # nnz may have changed
+
+    @property
+    def has_canonical_format(self) -> bool:
+        """Whether the array/matrix has sorted indices and no duplicates
+
+        Returns
+            - True: if the above applies
+            - False: otherwise
+
+        has_canonical_format implies has_sorted_indices, so if the latter flag
+        is False, so will the former be; if the former is found True, the
+        latter flag is also set.
+        """
+        # first check to see if result was cached
+        if not getattr(self, '_has_sorted_indices', True):
+            # not sorted => not canonical
+            self._has_canonical_format = False
+        elif not hasattr(self, '_has_canonical_format'):
+            self.has_canonical_format = bool(
+                _sparsetools.csr_has_canonical_format(
+                    len(self.indptr) - 1, self.indptr, self.indices)
+                )
+        return self._has_canonical_format
+
+    @has_canonical_format.setter
+    def has_canonical_format(self, val: bool):
+        self._has_canonical_format = bool(val)
+        if val:
+            self.has_sorted_indices = True
+
+    def sum_duplicates(self):
+        """Eliminate duplicate entries by adding them together
+
+        This is an *in place* operation.
+        """
+        if self.has_canonical_format:
+            return
+        self.sort_indices()
+
+        M, N = self._swap(self._shape_as_2d)
+        _sparsetools.csr_sum_duplicates(M, N, self.indptr, self.indices, self.data)
+
+        self.prune()  # nnz may have changed
+        self.has_canonical_format = True
+
+    @property
+    def has_sorted_indices(self) -> bool:
+        """Whether the indices are sorted
+
+        Returns
+            - True: if the indices of the array/matrix are in sorted order
+            - False: otherwise
+        """
+        # first check to see if result was cached
+        if not hasattr(self, '_has_sorted_indices'):
+            self._has_sorted_indices = bool(
+                _sparsetools.csr_has_sorted_indices(
+                    len(self.indptr) - 1, self.indptr, self.indices)
+                )
+        return self._has_sorted_indices
+
+    @has_sorted_indices.setter
+    def has_sorted_indices(self, val: bool):
+        self._has_sorted_indices = bool(val)
+
+
+    def sorted_indices(self):
+        """Return a copy of this array/matrix with sorted indices
+        """
+        A = self.copy()
+        A.sort_indices()
+        return A
+
+        # an alternative that has linear complexity is the following
+        # although the previous option is typically faster
+        # return self.toother().toother()
+
+    def sort_indices(self):
+        """Sort the indices of this array/matrix *in place*
+        """
+
+        if not self.has_sorted_indices:
+            _sparsetools.csr_sort_indices(len(self.indptr) - 1, self.indptr,
+                                          self.indices, self.data)
+            self.has_sorted_indices = True
+
+    def prune(self):
+        """Remove empty space after all non-zero elements.
+        """
+        major_dim = self._swap(self._shape_as_2d)[0]
+
+        if len(self.indptr) != major_dim + 1:
+            raise ValueError('index pointer has invalid length')
+        if len(self.indices) < self.nnz:
+            raise ValueError('indices array has fewer than nnz elements')
+        if len(self.data) < self.nnz:
+            raise ValueError('data array has fewer than nnz elements')
+
+        self.indices = _prune_array(self.indices[:self.nnz])
+        self.data = _prune_array(self.data[:self.nnz])
+
+    def resize(self, *shape):
+        shape = check_shape(shape, allow_nd=self._allow_nd)
+
+        if hasattr(self, 'blocksize'):
+            bm, bn = self.blocksize
+            new_M, rm = divmod(shape[0], bm)
+            new_N, rn = divmod(shape[1], bn)
+            if rm or rn:
+                raise ValueError(f"shape must be divisible into {self.blocksize}"
+                                 f" blocks. Got {shape}")
+            M, N = self.shape[0] // bm, self.shape[1] // bn
+        else:
+            new_M, new_N = self._swap(shape if len(shape)>1 else (1, shape[0]))
+            M, N = self._swap(self._shape_as_2d)
+
+        if new_M < M:
+            self.indices = self.indices[:self.indptr[new_M]]
+            self.data = self.data[:self.indptr[new_M]]
+            self.indptr = self.indptr[:new_M + 1]
+        elif new_M > M:
+            self.indptr = np.resize(self.indptr, new_M + 1)
+            self.indptr[M + 1:].fill(self.indptr[M])
+
+        if new_N < N:
+            mask = self.indices < new_N
+            if not np.all(mask):
+                self.indices = self.indices[mask]
+                self.data = self.data[mask]
+                major_index, val = self._minor_reduce(np.add, mask)
+                self.indptr.fill(0)
+                self.indptr[1:][major_index] = val
+                np.cumsum(self.indptr, out=self.indptr)
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    ###################
+    # utility methods #
+    ###################
+
+    # needed by _data_matrix
+    def _with_data(self, data, copy=True):
+        """Returns a matrix with the same sparsity structure as self,
+        but with different data.  By default the structure arrays
+        (i.e. .indptr and .indices) are copied.
+        """
+        if copy:
+            return self.__class__((data, self.indices.copy(),
+                                   self.indptr.copy()),
+                                  shape=self.shape,
+                                  dtype=data.dtype)
+        else:
+            return self.__class__((data, self.indices, self.indptr),
+                                  shape=self.shape, dtype=data.dtype)
+
+    def _binopt(self, other, op):
+        """apply the binary operation fn to two sparse matrices."""
+        other = self.__class__(other)
+
+        # e.g. csr_plus_csr, csr_minus_csr, etc.
+        fn = getattr(_sparsetools, self.format + op + self.format)
+
+        maxnnz = self.nnz + other.nnz
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                     other.indptr, other.indices),
+                                    maxval=maxnnz)
+        indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+        indices = np.empty(maxnnz, dtype=idx_dtype)
+
+        bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
+        if op in bool_ops:
+            data = np.empty(maxnnz, dtype=np.bool_)
+        else:
+            data = np.empty(maxnnz, dtype=upcast(self.dtype, other.dtype))
+
+        M, N = self._shape_as_2d
+        fn(M, N,
+           np.asarray(self.indptr, dtype=idx_dtype),
+           np.asarray(self.indices, dtype=idx_dtype),
+           self.data,
+           np.asarray(other.indptr, dtype=idx_dtype),
+           np.asarray(other.indices, dtype=idx_dtype),
+           other.data,
+           indptr, indices, data)
+
+        A = self.__class__((data, indices, indptr), shape=self.shape)
+        A.prune()
+
+        return A
+
+    def _divide_sparse(self, other):
+        """
+        Divide this matrix by a second sparse matrix.
+        """
+        if other.shape != self.shape:
+            raise ValueError('inconsistent shapes')
+
+        r = self._binopt(other, '_eldiv_')
+
+        if np.issubdtype(r.dtype, np.inexact):
+            # Eldiv leaves entries outside the combined sparsity
+            # pattern empty, so they must be filled manually.
+            # Everything outside of other's sparsity is NaN, and everything
+            # inside it is either zero or defined by eldiv.
+            out = np.empty(self.shape, dtype=self.dtype)
+            out.fill(np.nan)
+            coords = other.nonzero()
+            if self.ndim == 1:
+                coords = (coords[-1],)
+            out[coords] = 0
+            r = r.tocoo()
+            out[r.coords] = r.data
+            return self._container(out)
+        else:
+            # integers types go with nan <-> 0
+            out = r
+            return out
+
+    def _broadcast_to(self, shape, copy=False):
+        if self.shape == shape:
+            return self.copy() if copy else self
+
+        shape = check_shape(shape, allow_nd=(self._allow_nd))
+
+        if broadcast_shapes(self.shape, shape) != shape:
+            raise ValueError("cannot be broadcast")
+
+        if len(self.shape) == 1 and len(shape) == 1:
+            self.sum_duplicates()
+            if self.nnz == 0: # array has no non zero elements
+                return self.__class__(shape, dtype=self.dtype, copy=False)
+
+            N = shape[0]
+            data = np.full(N, self.data[0])
+            indices = np.arange(0,N)
+            indptr = np.array([0, N])
+            return self._csr_container((data, indices, indptr), shape=shape, copy=False)
+
+        # treat 1D as a 2D row
+        old_shape = self._shape_as_2d
+
+        if len(shape) != 2:
+            ndim = len(shape)
+            raise ValueError(f'CSR/CSC broadcast_to cannot have shape >2D. Got {ndim}D')
+
+        if self.nnz == 0: # array has no non zero elements
+            return self.__class__(shape, dtype=self.dtype, copy=False)
+
+        self.sum_duplicates()
+        M, N = self._swap(shape)
+        oM, oN = self._swap(old_shape)
+        if all(s == 1 for s in old_shape):
+            # Broadcast a single element to the entire shape
+            data = np.full(M * N, self.data[0])
+            indices = np.tile(np.arange(N), M)
+            indptr = np.arange(0, len(data) + 1, N)
+        elif oM == 1 and oN == N:
+            # Broadcast row-wise (columns for CSC)
+            data = np.tile(self.data, M)
+            indices = np.tile(self.indices, M)
+            indptr = np.arange(0, len(data) + 1, len(self.data))
+        elif oN == 1 and oM == M:
+            # Broadcast column-wise (rows for CSC)
+            data = np.repeat(self.data, N)
+            indices = np.tile(np.arange(N), len(self.data))
+            indptr = self.indptr * N
+        return self.__class__((data, indices, indptr), shape=shape, copy=False)
+
+
+def _make_diagonal_csr(data, is_array=False):
+    """build diagonal csc_array/csr_array => self._csr_container
+
+    Parameter `data` should be a raveled numpy array holding the
+    values on the diagonal of the resulting sparse matrix.
+    """
+    from ._csr import csr_array, csr_matrix
+    csr_array = csr_array if is_array else csr_matrix
+
+    N = len(data)
+    idx_dtype = get_index_dtype(maxval=N)
+    indptr = np.arange(N + 1, dtype=idx_dtype)
+    indices = indptr[:-1]
+
+    return csr_array((data, indices, indptr), shape=(N, N))
+
+
+def _process_slice(sl, num):
+    if sl is None:
+        i0, i1 = 0, num
+    elif isinstance(sl, slice):
+        i0, i1, stride = sl.indices(num)
+        if stride != 1:
+            raise ValueError('slicing with step != 1 not supported')
+        i0 = min(i0, i1)  # give an empty slice when i0 > i1
+    elif isintlike(sl):
+        if sl < 0:
+            sl += num
+        i0, i1 = sl, sl + 1
+        if i0 < 0 or i1 > num:
+            raise IndexError(f'index out of bounds: 0 <= {i0} < {i1} <= {num}')
+    else:
+        raise TypeError('expected slice or scalar')
+
+    return i0, i1
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_construct.py b/venv/lib/python3.10/site-packages/scipy/sparse/_construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..f483976badb771d777c9dba0eecfbeb94d2e76fd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_construct.py
@@ -0,0 +1,1402 @@
+"""Functions to construct sparse matrices and arrays
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['spdiags', 'eye', 'identity', 'kron', 'kronsum',
+           'hstack', 'vstack', 'bmat', 'rand', 'random', 'diags', 'block_diag',
+           'diags_array', 'block_array', 'eye_array', 'random_array']
+
+import numbers
+import math
+import numpy as np
+
+from scipy._lib._util import check_random_state, rng_integers, _transition_to_rng
+from ._sputils import upcast, get_index_dtype, isscalarlike
+
+from ._sparsetools import csr_hstack
+from ._bsr import bsr_matrix, bsr_array
+from ._coo import coo_matrix, coo_array
+from ._csc import csc_matrix, csc_array
+from ._csr import csr_matrix, csr_array
+from ._dia import dia_matrix, dia_array
+
+from ._base import issparse, sparray
+
+
+def spdiags(data, diags, m=None, n=None, format=None):
+    """
+    Return a sparse matrix from diagonals.
+
+    Parameters
+    ----------
+    data : array_like
+        Matrix diagonals stored row-wise
+    diags : sequence of int or an int
+        Diagonals to set:
+
+        * k = 0  the main diagonal
+        * k > 0  the kth upper diagonal
+        * k < 0  the kth lower diagonal
+    m, n : int, tuple, optional
+        Shape of the result. If `n` is None and `m` is a given tuple,
+        the shape is this tuple. If omitted, the matrix is square and
+        its shape is len(data[0]).
+    format : str, optional
+        Format of the result. By default (format=None) an appropriate sparse
+        matrix format is returned. This choice is subject to change.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``dia_array`` to take advantage
+        of the sparse array functionality.
+
+    Notes
+    -----
+    This function can be replaced by an equivalent call to ``dia_matrix``
+    as::
+
+        dia_matrix((data, diags), shape=(m, n)).asformat(format)
+
+    See Also
+    --------
+    diags_array : more convenient form of this function
+    diags : matrix version of diags_array
+    dia_matrix : the sparse DIAgonal format.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import spdiags
+    >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
+    >>> diags = np.array([0, -1, 2])
+    >>> spdiags(data, diags, 4, 4).toarray()
+    array([[1, 0, 3, 0],
+           [1, 2, 0, 4],
+           [0, 2, 3, 0],
+           [0, 0, 3, 4]])
+
+    """
+    if m is None and n is None:
+        m = n = len(data[0])
+    elif n is None:
+        m, n = m
+    return dia_matrix((data, diags), shape=(m, n)).asformat(format)
+
+
+def diags_array(diagonals, /, *, offsets=0, shape=None, format=None, dtype=None):
+    """
+    Construct a sparse array from diagonals.
+
+    Parameters
+    ----------
+    diagonals : sequence of array_like
+        Sequence of arrays containing the array diagonals,
+        corresponding to `offsets`.
+    offsets : sequence of int or an int, optional
+        Diagonals to set (repeated offsets are not allowed):
+          - k = 0  the main diagonal (default)
+          - k > 0  the kth upper diagonal
+          - k < 0  the kth lower diagonal
+    shape : tuple of int, optional
+        Shape of the result. If omitted, a square array large enough
+        to contain the diagonals is returned.
+    format : {"dia", "csr", "csc", "lil", ...}, optional
+        Matrix format of the result. By default (format=None) an
+        appropriate sparse array format is returned. This choice is
+        subject to change.
+    dtype : dtype, optional
+        Data type of the array.
+
+    Notes
+    -----
+    Repeated diagonal offsets are disallowed.
+
+    The result from `diags_array` is the sparse equivalent of::
+
+        np.diag(diagonals[0], offsets[0])
+        + ...
+        + np.diag(diagonals[k], offsets[k])
+
+    ``diags_array`` differs from `dia_array` in the way it handles off-diagonals.
+    Specifically, `dia_array` assumes the data input includes padding
+    (ignored values) at the start/end of the rows for positive/negative
+    offset, while ``diags_array` assumes the input data has no padding.
+    Each value in the input ``diagonals`` is used.
+
+    .. versionadded:: 1.11
+
+    Examples
+    --------
+    >>> from scipy.sparse import diags_array
+    >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
+    >>> diags_array(diagonals, offsets=[0, -1, 2]).toarray()
+    array([[1., 0., 1., 0.],
+           [1., 2., 0., 2.],
+           [0., 2., 3., 0.],
+           [0., 0., 3., 4.]])
+
+    Broadcasting of scalars is supported (but shape needs to be
+    specified):
+
+    >>> diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)).toarray()
+    array([[-2.,  1.,  0.,  0.],
+           [ 1., -2.,  1.,  0.],
+           [ 0.,  1., -2.,  1.],
+           [ 0.,  0.,  1., -2.]])
+
+
+    If only one diagonal is wanted (as in `numpy.diag`), the following
+    works as well:
+
+    >>> diags_array([1, 2, 3], offsets=1).toarray()
+    array([[ 0.,  1.,  0.,  0.],
+           [ 0.,  0.,  2.,  0.],
+           [ 0.,  0.,  0.,  3.],
+           [ 0.,  0.,  0.,  0.]])
+
+    """
+    # if offsets is not a sequence, assume that there's only one diagonal
+    if isscalarlike(offsets):
+        # now check that there's actually only one diagonal
+        if len(diagonals) == 0 or isscalarlike(diagonals[0]):
+            diagonals = [np.atleast_1d(diagonals)]
+        else:
+            raise ValueError("Different number of diagonals and offsets.")
+    else:
+        diagonals = list(map(np.atleast_1d, diagonals))
+
+    offsets = np.atleast_1d(offsets)
+
+    # Basic check
+    if len(diagonals) != len(offsets):
+        raise ValueError("Different number of diagonals and offsets.")
+
+    # Determine shape, if omitted
+    if shape is None:
+        m = len(diagonals[0]) + abs(int(offsets[0]))
+        shape = (m, m)
+
+    # Determine data type, if omitted
+    if dtype is None:
+        dtype = np.common_type(*diagonals)
+
+    # Construct data array
+    m, n = shape
+
+    M = max([min(m + offset, n - offset) + max(0, offset)
+             for offset in offsets])
+    M = max(0, M)
+    data_arr = np.zeros((len(offsets), M), dtype=dtype)
+
+    K = min(m, n)
+
+    for j, diagonal in enumerate(diagonals):
+        offset = offsets[j]
+        k = max(0, offset)
+        length = min(m + offset, n - offset, K)
+        if length < 0:
+            raise ValueError(f"Offset {offset} (index {j}) out of bounds")
+        try:
+            data_arr[j, k:k+length] = diagonal[...,:length]
+        except ValueError as e:
+            if len(diagonal) != length and len(diagonal) != 1:
+                raise ValueError(
+                    f"Diagonal length (index {j}: {len(diagonal)} at"
+                    f" offset {offset}) does not agree with array size ({m}, {n})."
+                ) from e
+            raise
+
+    return dia_array((data_arr, offsets), shape=(m, n)).asformat(format)
+
+
+def diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
+    """
+    Construct a sparse matrix from diagonals.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``diags_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    diagonals : sequence of array_like
+        Sequence of arrays containing the matrix diagonals,
+        corresponding to `offsets`.
+    offsets : sequence of int or an int, optional
+        Diagonals to set (repeated offsets are not allowed):
+          - k = 0  the main diagonal (default)
+          - k > 0  the kth upper diagonal
+          - k < 0  the kth lower diagonal
+    shape : tuple of int, optional
+        Shape of the result. If omitted, a square matrix large enough
+        to contain the diagonals is returned.
+    format : {"dia", "csr", "csc", "lil", ...}, optional
+        Matrix format of the result. By default (format=None) an
+        appropriate sparse matrix format is returned. This choice is
+        subject to change.
+    dtype : dtype, optional
+        Data type of the matrix.
+
+    See Also
+    --------
+    spdiags : construct matrix from diagonals
+    diags_array : construct sparse array instead of sparse matrix
+
+    Notes
+    -----
+    Repeated diagonal offsets are disallowed.
+
+    The result from `diags` is the sparse equivalent of::
+
+        np.diag(diagonals[0], offsets[0])
+        + ...
+        + np.diag(diagonals[k], offsets[k])
+
+    ``diags`` differs from ``dia_matrix`` in the way it handles off-diagonals.
+    Specifically, `dia_matrix` assumes the data input includes padding
+    (ignored values) at the start/end of the rows for positive/negative
+    offset, while ``diags` assumes the input data has no padding.
+    Each value in the input ``diagonals`` is used.
+
+    .. versionadded:: 0.11
+
+    Examples
+    --------
+    >>> from scipy.sparse import diags
+    >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
+    >>> diags(diagonals, [0, -1, 2]).toarray()
+    array([[1., 0., 1., 0.],
+           [1., 2., 0., 2.],
+           [0., 2., 3., 0.],
+           [0., 0., 3., 4.]])
+
+    Broadcasting of scalars is supported (but shape needs to be
+    specified):
+
+    >>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray()
+    array([[-2.,  1.,  0.,  0.],
+           [ 1., -2.,  1.,  0.],
+           [ 0.,  1., -2.,  1.],
+           [ 0.,  0.,  1., -2.]])
+
+
+    If only one diagonal is wanted (as in `numpy.diag`), the following
+    works as well:
+
+    >>> diags([1, 2, 3], 1).toarray()
+    array([[ 0.,  1.,  0.,  0.],
+           [ 0.,  0.,  2.,  0.],
+           [ 0.,  0.,  0.,  3.],
+           [ 0.,  0.,  0.,  0.]])
+
+    """
+    A = diags_array(diagonals, offsets=offsets, shape=shape, dtype=dtype)
+    return dia_matrix(A).asformat(format)
+
+
+def identity(n, dtype='d', format=None):
+    """Identity matrix in sparse format
+
+    Returns an identity matrix with shape (n,n) using a given
+    sparse format and dtype. This differs from `eye_array` in
+    that it has a square shape with ones only on the main diagonal.
+    It is thus the multiplicative identity. `eye_array` allows
+    rectangular shapes and the diagonal can be offset from the main one.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``eye_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    n : int
+        Shape of the identity matrix.
+    dtype : dtype, optional
+        Data type of the matrix
+    format : str, optional
+        Sparse format of the result, e.g., format="csr", etc.
+
+    Examples
+    --------
+    >>> import scipy as sp
+    >>> sp.sparse.identity(3).toarray()
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> sp.sparse.identity(3, dtype='int8', format='dia')
+    
+    >>> sp.sparse.eye_array(3, dtype='int8', format='dia')
+    
+
+    """
+    return eye(n, n, dtype=dtype, format=format)
+
+
+def eye_array(m, n=None, *, k=0, dtype=float, format=None):
+    """Identity matrix in sparse array format
+
+    Return a sparse array with ones on diagonal.
+    Specifically a sparse array (m x n) where the kth diagonal
+    is all ones and everything else is zeros.
+
+    Parameters
+    ----------
+    m : int
+        Number of rows requested.
+    n : int, optional
+        Number of columns. Default: `m`.
+    k : int, optional
+        Diagonal to place ones on. Default: 0 (main diagonal).
+    dtype : dtype, optional
+        Data type of the array
+    format : str, optional (default: "dia")
+        Sparse format of the result, e.g., format="csr", etc.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sp.sparse.eye_array(3).toarray()
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> sp.sparse.eye_array(3, dtype=np.int8)
+    
+
+    """
+    # TODO: delete next 15 lines [combine with _eye()] once spmatrix removed
+    return _eye(m, n, k, dtype, format)
+
+
+def _eye(m, n, k, dtype, format, as_sparray=True):
+    if as_sparray:
+        csr_sparse = csr_array
+        csc_sparse = csc_array
+        coo_sparse = coo_array
+        diags_sparse = diags_array
+    else:
+        csr_sparse = csr_matrix
+        csc_sparse = csc_matrix
+        coo_sparse = coo_matrix
+        diags_sparse = diags
+
+    if n is None:
+        n = m
+    m, n = int(m), int(n)
+
+    if m == n and k == 0:
+        # fast branch for special formats
+        if format in ['csr', 'csc']:
+            idx_dtype = get_index_dtype(maxval=n)
+            indptr = np.arange(n+1, dtype=idx_dtype)
+            indices = np.arange(n, dtype=idx_dtype)
+            data = np.ones(n, dtype=dtype)
+            cls = {'csr': csr_sparse, 'csc': csc_sparse}[format]
+            return cls((data, indices, indptr), (n, n))
+
+        elif format == 'coo':
+            idx_dtype = get_index_dtype(maxval=n)
+            row = np.arange(n, dtype=idx_dtype)
+            col = np.arange(n, dtype=idx_dtype)
+            data = np.ones(n, dtype=dtype)
+            return coo_sparse((data, (row, col)), (n, n))
+
+    data = np.ones((1, max(0, min(m + k, n))), dtype=dtype)
+    return diags_sparse(data, offsets=[k], shape=(m, n), dtype=dtype).asformat(format)
+
+
+def eye(m, n=None, k=0, dtype=float, format=None):
+    """Sparse matrix with ones on diagonal
+
+    Returns a sparse matrix (m x n) where the kth diagonal
+    is all ones and everything else is zeros.
+
+    Parameters
+    ----------
+    m : int
+        Number of rows in the matrix.
+    n : int, optional
+        Number of columns. Default: `m`.
+    k : int, optional
+        Diagonal to place ones on. Default: 0 (main diagonal).
+    dtype : dtype, optional
+        Data type of the matrix.
+    format : str, optional
+        Sparse format of the result, e.g., format="csr", etc.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``eye_array`` to take advantage
+        of the sparse array functionality.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sp.sparse.eye(3).toarray()
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> sp.sparse.eye(3, dtype=np.int8)
+    
+
+    """
+    return _eye(m, n, k, dtype, format, False)
+
+
+def kron(A, B, format=None):
+    """kronecker product of sparse matrices A and B
+
+    Parameters
+    ----------
+    A : sparse or dense matrix
+        first matrix of the product
+    B : sparse or dense matrix
+        second matrix of the product
+    format : str, optional (default: 'bsr' or 'coo')
+        format of the result (e.g. "csr")
+        If None, choose 'bsr' for relatively dense array and 'coo' for others
+
+    Returns
+    -------
+    kronecker product in a sparse format.
+    Returns a sparse matrix unless either A or B is a
+    sparse array in which case returns a sparse array.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> A = sp.sparse.csr_array(np.array([[0, 2], [5, 0]]))
+    >>> B = sp.sparse.csr_array(np.array([[1, 2], [3, 4]]))
+    >>> sp.sparse.kron(A, B).toarray()
+    array([[ 0,  0,  2,  4],
+           [ 0,  0,  6,  8],
+           [ 5, 10,  0,  0],
+           [15, 20,  0,  0]])
+
+    >>> sp.sparse.kron(A, [[1, 2], [3, 4]]).toarray()
+    array([[ 0,  0,  2,  4],
+           [ 0,  0,  6,  8],
+           [ 5, 10,  0,  0],
+           [15, 20,  0,  0]])
+
+    """
+    # TODO: delete next 10 lines and replace _sparse with _array when spmatrix removed
+    if isinstance(A, sparray) or isinstance(B, sparray):
+        # convert to local variables
+        bsr_sparse = bsr_array
+        csr_sparse = csr_array
+        coo_sparse = coo_array
+    else:  # use spmatrix
+        bsr_sparse = bsr_matrix
+        csr_sparse = csr_matrix
+        coo_sparse = coo_matrix
+
+    B = coo_sparse(B)
+    if B.ndim != 2:
+        raise ValueError(f"kron requires 2D input arrays. `B` is {B.ndim}D.")
+
+    # B is fairly dense, use BSR
+    if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]:
+        A = csr_sparse(A,copy=True)
+        if A.ndim != 2:
+            raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.")
+        output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1])
+
+        if A.nnz == 0 or B.nnz == 0:
+            # kronecker product is the zero matrix
+            return coo_sparse(output_shape).asformat(format)
+
+        B = B.toarray()
+        data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1])
+        data = data * B
+
+        return bsr_sparse((data,A.indices,A.indptr), shape=output_shape)
+    else:
+        # use COO
+        A = coo_sparse(A)
+        if A.ndim != 2:
+            raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.")
+        output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1])
+
+        if A.nnz == 0 or B.nnz == 0:
+            # kronecker product is the zero matrix
+            return coo_sparse(output_shape).asformat(format)
+
+        # expand entries of a into blocks
+        idx_dtype = get_index_dtype(A.coords, maxval=max(output_shape))
+        row = np.asarray(A.row, dtype=idx_dtype).repeat(B.nnz)
+        col = np.asarray(A.col, dtype=idx_dtype).repeat(B.nnz)
+        data = A.data.repeat(B.nnz)
+
+        row *= B.shape[0]
+        col *= B.shape[1]
+
+        # increment block indices
+        row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz)
+        row += B.row
+        col += B.col
+        row,col = row.reshape(-1),col.reshape(-1)
+
+        # compute block entries
+        data = data.reshape(-1,B.nnz) * B.data
+        data = data.reshape(-1)
+
+        return coo_sparse((data,(row,col)), shape=output_shape).asformat(format)
+
+
+def kronsum(A, B, format=None):
+    """kronecker sum of square sparse matrices A and B
+
+    Kronecker sum of two sparse matrices is a sum of two Kronecker
+    products kron(I_n,A) + kron(B,I_m) where A has shape (m,m)
+    and B has shape (n,n) and I_m and I_n are identity matrices
+    of shape (m,m) and (n,n), respectively.
+
+    Parameters
+    ----------
+    A
+        square matrix
+    B
+        square matrix
+    format : str
+        format of the result (e.g. "csr")
+
+    Returns
+    -------
+    kronecker sum in a sparse matrix format
+
+    """
+    # TODO: delete next 8 lines and replace _sparse with _array when spmatrix removed
+    if isinstance(A, sparray) or isinstance(B, sparray):
+        # convert to local variables
+        coo_sparse = coo_array
+        identity_sparse = eye_array
+    else:
+        coo_sparse = coo_matrix
+        identity_sparse = identity
+
+    A = coo_sparse(A)
+    B = coo_sparse(B)
+
+    if A.ndim != 2:
+        raise ValueError(f"kronsum requires 2D inputs. `A` is {A.ndim}D.")
+    if B.ndim != 2:
+        raise ValueError(f"kronsum requires 2D inputs. `B` is {B.ndim}D.")
+    if A.shape[0] != A.shape[1]:
+        raise ValueError('A is not square')
+    if B.shape[0] != B.shape[1]:
+        raise ValueError('B is not square')
+
+    dtype = upcast(A.dtype, B.dtype)
+
+    I_n = identity_sparse(A.shape[0], dtype=dtype)
+    I_m = identity_sparse(B.shape[0], dtype=dtype)
+    L = kron(I_m, A, format='coo')
+    R = kron(B, I_n, format='coo')
+
+    return (L + R).asformat(format)
+
+
+def _compressed_sparse_stack(blocks, axis, return_spmatrix):
+    """
+    Stacking fast path for CSR/CSC matrices or arrays
+    (i) vstack for CSR, (ii) hstack for CSC.
+    """
+    other_axis = 1 if axis == 0 else 0
+    data = np.concatenate([b.data for b in blocks])
+    constant_dim = blocks[0]._shape_as_2d[other_axis]
+    idx_dtype = get_index_dtype(arrays=[b.indptr for b in blocks],
+                                maxval=max(data.size, constant_dim))
+    indices = np.empty(data.size, dtype=idx_dtype)
+    indptr = np.empty(sum(b._shape_as_2d[axis] for b in blocks) + 1, dtype=idx_dtype)
+    last_indptr = idx_dtype(0)
+    sum_dim = 0
+    sum_indices = 0
+    for b in blocks:
+        if b._shape_as_2d[other_axis] != constant_dim:
+            raise ValueError(f'incompatible dimensions for axis {other_axis}')
+        indices[sum_indices:sum_indices+b.indices.size] = b.indices
+        sum_indices += b.indices.size
+        idxs = slice(sum_dim, sum_dim + b._shape_as_2d[axis])
+        indptr[idxs] = b.indptr[:-1]
+        indptr[idxs] += last_indptr
+        sum_dim += b._shape_as_2d[axis]
+        last_indptr += b.indptr[-1]
+    indptr[-1] = last_indptr
+    # TODO remove this if-structure when sparse matrices removed
+    if return_spmatrix:
+        if axis == 0:
+            return csr_matrix((data, indices, indptr),
+                              shape=(sum_dim, constant_dim))
+        else:
+            return csc_matrix((data, indices, indptr),
+                              shape=(constant_dim, sum_dim))
+
+    if axis == 0:
+        return csr_array((data, indices, indptr),
+                          shape=(sum_dim, constant_dim))
+    else:
+        return csc_array((data, indices, indptr),
+                          shape=(constant_dim, sum_dim))
+
+
+def _stack_along_minor_axis(blocks, axis):
+    """
+    Stacking fast path for CSR/CSC matrices along the minor axis
+    (i) hstack for CSR, (ii) vstack for CSC.
+    """
+    n_blocks = len(blocks)
+    if n_blocks == 0:
+        raise ValueError('Missing block matrices')
+
+    if n_blocks == 1:
+        return blocks[0]
+
+    # check for incompatible dimensions
+    other_axis = 1 if axis == 0 else 0
+    other_axis_dims = {b._shape_as_2d[other_axis] for b in blocks}
+    if len(other_axis_dims) > 1:
+        raise ValueError(f'Mismatching dimensions along axis {other_axis}: '
+                         f'{other_axis_dims}')
+    constant_dim, = other_axis_dims
+
+    # Do the stacking
+    indptr_list = [b.indptr for b in blocks]
+    data_cat = np.concatenate([b.data for b in blocks])
+
+    # Need to check if any indices/indptr, would be too large post-
+    # concatenation for np.int32:
+    # - The max value of indices is the output array's stacking-axis length - 1
+    # - The max value in indptr is the number of non-zero entries. This is
+    #   exceedingly unlikely to require int64, but is checked out of an
+    #   abundance of caution.
+    sum_dim = sum(b._shape_as_2d[axis] for b in blocks)
+    nnz = sum(len(b.indices) for b in blocks)
+    idx_dtype = get_index_dtype(indptr_list, maxval=max(sum_dim - 1, nnz))
+    stack_dim_cat = np.array([b._shape_as_2d[axis] for b in blocks], dtype=idx_dtype)
+    if data_cat.size > 0:
+        indptr_cat = np.concatenate(indptr_list, dtype=idx_dtype)
+        indices_cat = np.concatenate([b.indices for b in blocks], dtype=idx_dtype)
+        indptr = np.empty(constant_dim + 1, dtype=idx_dtype)
+        indices = np.empty_like(indices_cat)
+        data = np.empty_like(data_cat)
+        csr_hstack(n_blocks, constant_dim, stack_dim_cat,
+                   indptr_cat, indices_cat, data_cat,
+                   indptr, indices, data)
+    else:
+        indptr = np.zeros(constant_dim + 1, dtype=idx_dtype)
+        indices = np.empty(0, dtype=idx_dtype)
+        data = np.empty(0, dtype=data_cat.dtype)
+
+    if axis == 0:
+        return blocks[0]._csc_container((data, indices, indptr),
+                          shape=(sum_dim, constant_dim))
+    else:
+        return blocks[0]._csr_container((data, indices, indptr),
+                          shape=(constant_dim, sum_dim))
+
+
+def hstack(blocks, format=None, dtype=None):
+    """
+    Stack sparse matrices horizontally (column wise)
+
+    Parameters
+    ----------
+    blocks
+        sequence of sparse matrices with compatible shapes
+    format : str
+        sparse format of the result (e.g., "csr")
+        by default an appropriate sparse matrix format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output matrix. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    new_array : sparse matrix or array
+        If any block in blocks is a sparse array, return a sparse array.
+        Otherwise return a sparse matrix.
+
+        If you want a sparse array built from blocks that are not sparse
+        arrays, use ``block(hstack(blocks))`` or convert one block
+        e.g. ``blocks[0] = csr_array(blocks[0])``.
+
+    See Also
+    --------
+    vstack : stack sparse matrices vertically (row wise)
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_matrix, hstack
+    >>> A = coo_matrix([[1, 2], [3, 4]])
+    >>> B = coo_matrix([[5], [6]])
+    >>> hstack([A,B]).toarray()
+    array([[1, 2, 5],
+           [3, 4, 6]])
+
+    """
+    blocks = np.asarray(blocks, dtype='object')
+    if any(isinstance(b, sparray) for b in blocks.flat):
+        return _block([blocks], format, dtype)
+    else:
+        return _block([blocks], format, dtype, return_spmatrix=True)
+
+
+def vstack(blocks, format=None, dtype=None):
+    """
+    Stack sparse arrays vertically (row wise)
+
+    Parameters
+    ----------
+    blocks
+        sequence of sparse arrays with compatible shapes
+    format : str, optional
+        sparse format of the result (e.g., "csr")
+        by default an appropriate sparse array format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output array. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    new_array : sparse matrix or array
+        If any block in blocks is a sparse array, return a sparse array.
+        Otherwise return a sparse matrix.
+
+        If you want a sparse array built from blocks that are not sparse
+        arrays, use ``block(vstack(blocks))`` or convert one block
+        e.g. `blocks[0] = csr_array(blocks[0])`.
+
+    See Also
+    --------
+    hstack : stack sparse matrices horizontally (column wise)
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, vstack
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5, 6]])
+    >>> vstack([A, B]).toarray()
+    array([[1, 2],
+           [3, 4],
+           [5, 6]])
+
+    """
+    blocks = np.asarray(blocks, dtype='object')
+    if any(isinstance(b, sparray) for b in blocks.flat):
+        return _block([[b] for b in blocks], format, dtype)
+    else:
+        return _block([[b] for b in blocks], format, dtype, return_spmatrix=True)
+
+
+def bmat(blocks, format=None, dtype=None):
+    """
+    Build a sparse array or matrix from sparse sub-blocks
+
+    Note: `block_array` is preferred over `bmat`. They are the same function
+    except that `bmat` can return a deprecated sparse matrix.
+    `bmat` returns a coo_matrix if none of the inputs are a sparse array.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``block_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    blocks : array_like
+        Grid of sparse matrices with compatible shapes.
+        An entry of None implies an all-zero matrix.
+    format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional
+        The sparse format of the result (e.g. "csr"). By default an
+        appropriate sparse matrix format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output matrix. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    bmat : sparse matrix or array
+        If any block in blocks is a sparse array, return a sparse array.
+        Otherwise return a sparse matrix.
+
+        If you want a sparse array built from blocks that are not sparse
+        arrays, use ``block_array()``.
+
+    See Also
+    --------
+    block_array
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, bmat
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5], [6]])
+    >>> C = coo_array([[7]])
+    >>> bmat([[A, B], [None, C]]).toarray()
+    array([[1, 2, 5],
+           [3, 4, 6],
+           [0, 0, 7]])
+
+    >>> bmat([[A, None], [None, C]]).toarray()
+    array([[1, 2, 0],
+           [3, 4, 0],
+           [0, 0, 7]])
+
+    """
+    blocks = np.asarray(blocks, dtype='object')
+    if any(isinstance(b, sparray) for b in blocks.flat):
+        return _block(blocks, format, dtype)
+    else:
+        return _block(blocks, format, dtype, return_spmatrix=True)
+
+
+def block_array(blocks, *, format=None, dtype=None):
+    """
+    Build a sparse array from sparse sub-blocks
+
+    Parameters
+    ----------
+    blocks : array_like
+        Grid of sparse arrays with compatible shapes.
+        An entry of None implies an all-zero array.
+    format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional
+        The sparse format of the result (e.g. "csr"). By default an
+        appropriate sparse array format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output array. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    block : sparse array
+
+    See Also
+    --------
+    block_diag : specify blocks along the main diagonals
+    diags : specify (possibly offset) diagonals
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, block_array
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5], [6]])
+    >>> C = coo_array([[7]])
+    >>> block_array([[A, B], [None, C]]).toarray()
+    array([[1, 2, 5],
+           [3, 4, 6],
+           [0, 0, 7]])
+
+    >>> block_array([[A, None], [None, C]]).toarray()
+    array([[1, 2, 0],
+           [3, 4, 0],
+           [0, 0, 7]])
+
+    """
+    return _block(blocks, format, dtype)
+
+
+def _block(blocks, format, dtype, return_spmatrix=False):
+    blocks = np.asarray(blocks, dtype='object')
+
+    if blocks.ndim != 2:
+        raise ValueError('blocks must be 2-D')
+
+    M,N = blocks.shape
+
+    # check for fast path cases
+    if (format in (None, 'csr') and
+        all(issparse(b) and b.format == 'csr' for b in blocks.flat)
+    ):
+        if N > 1:
+            # stack along columns (axis 1): must have shape (M, 1)
+            blocks = [[_stack_along_minor_axis(blocks[b, :], 1)] for b in range(M)]
+            blocks = np.asarray(blocks, dtype='object')
+
+        # stack along rows (axis 0):
+        A = _compressed_sparse_stack(blocks[:, 0], 0, return_spmatrix)
+        if dtype is not None:
+            A = A.astype(dtype, copy=False)
+        return A
+    elif (format in (None, 'csc') and
+          all(issparse(b) and b.format == 'csc' for b in blocks.flat)
+    ):
+        if M > 1:
+            # stack along rows (axis 0): must have shape (1, N)
+            blocks = [[_stack_along_minor_axis(blocks[:, b], 0) for b in range(N)]]
+            blocks = np.asarray(blocks, dtype='object')
+
+        # stack along columns (axis 1):
+        A = _compressed_sparse_stack(blocks[0, :], 1, return_spmatrix)
+        if dtype is not None:
+            A = A.astype(dtype, copy=False)
+        return A
+
+    block_mask = np.zeros(blocks.shape, dtype=bool)
+    brow_lengths = np.zeros(M, dtype=np.int64)
+    bcol_lengths = np.zeros(N, dtype=np.int64)
+
+    # convert everything to COO format
+    for i in range(M):
+        for j in range(N):
+            if blocks[i,j] is not None:
+                A = coo_array(blocks[i,j])
+                blocks[i,j] = A
+                block_mask[i,j] = True
+
+                if brow_lengths[i] == 0:
+                    brow_lengths[i] = A._shape_as_2d[0]
+                elif brow_lengths[i] != A._shape_as_2d[0]:
+                    msg = (f'blocks[{i},:] has incompatible row dimensions. '
+                           f'Got blocks[{i},{j}].shape[0] == {A._shape_as_2d[0]}, '
+                           f'expected {brow_lengths[i]}.')
+                    raise ValueError(msg)
+
+                if bcol_lengths[j] == 0:
+                    bcol_lengths[j] = A._shape_as_2d[1]
+                elif bcol_lengths[j] != A._shape_as_2d[1]:
+                    msg = (f'blocks[:,{j}] has incompatible column '
+                           f'dimensions. '
+                           f'Got blocks[{i},{j}].shape[1] == {A._shape_as_2d[1]}, '
+                           f'expected {bcol_lengths[j]}.')
+                    raise ValueError(msg)
+
+    nnz = sum(block.nnz for block in blocks[block_mask])
+    if dtype is None:
+        all_dtypes = [blk.dtype for blk in blocks[block_mask]]
+        dtype = upcast(*all_dtypes) if all_dtypes else None
+
+    row_offsets = np.append(0, np.cumsum(brow_lengths))
+    col_offsets = np.append(0, np.cumsum(bcol_lengths))
+
+    shape = (row_offsets[-1], col_offsets[-1])
+
+    data = np.empty(nnz, dtype=dtype)
+    idx_dtype = get_index_dtype([b.coords[0] for b in blocks[block_mask]],
+                                maxval=max(shape))
+    row = np.empty(nnz, dtype=idx_dtype)
+    col = np.empty(nnz, dtype=idx_dtype)
+
+    nnz = 0
+    ii, jj = np.nonzero(block_mask)
+    for i, j in zip(ii, jj):
+        B = blocks[i, j]
+        idx = slice(nnz, nnz + B.nnz)
+        data[idx] = B.data
+        np.add(B.row, row_offsets[i], out=row[idx], dtype=idx_dtype)
+        np.add(B.col, col_offsets[j], out=col[idx], dtype=idx_dtype)
+        nnz += B.nnz
+
+    if return_spmatrix:
+        return coo_matrix((data, (row, col)), shape=shape).asformat(format)
+    return coo_array((data, (row, col)), shape=shape).asformat(format)
+
+
+def block_diag(mats, format=None, dtype=None):
+    """
+    Build a block diagonal sparse matrix or array from provided matrices.
+
+    Parameters
+    ----------
+    mats : sequence of matrices or arrays
+        Input matrices or arrays.
+    format : str, optional
+        The sparse format of the result (e.g., "csr"). If not given, the result
+        is returned in "coo" format.
+    dtype : dtype specifier, optional
+        The data-type of the output. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    res : sparse matrix or array
+        If at least one input is a sparse array, the output is a sparse array.
+        Otherwise the output is a sparse matrix.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.11.0
+
+    See Also
+    --------
+    block_array
+    diags_array
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, block_diag
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5], [6]])
+    >>> C = coo_array([[7]])
+    >>> block_diag((A, B, C)).toarray()
+    array([[1, 2, 0, 0],
+           [3, 4, 0, 0],
+           [0, 0, 5, 0],
+           [0, 0, 6, 0],
+           [0, 0, 0, 7]])
+
+    """
+    if any(isinstance(a, sparray) for a in mats):
+        container = coo_array
+    else:
+        container = coo_matrix
+
+    row = []
+    col = []
+    data = []
+    idx_arrays = []  # track idx_dtype of incoming sparse arrays
+    r_idx = 0
+    c_idx = 0
+    for a in mats:
+        if isinstance(a, (list | numbers.Number)):
+            a = coo_array(np.atleast_2d(a))
+        if issparse(a):
+            a = a.tocoo()
+            if not idx_arrays and a.coords[0].dtype == np.int64:
+                idx_arrays.append(a.coords[0])
+            nrows, ncols = a._shape_as_2d
+            row.append(a.row + r_idx)
+            col.append(a.col + c_idx)
+            data.append(a.data)
+        else:
+            nrows, ncols = a.shape
+            a_row, a_col = np.divmod(np.arange(nrows*ncols), ncols)
+            row.append(a_row + r_idx)
+            col.append(a_col + c_idx)
+            data.append(a.ravel())
+        r_idx += nrows
+        c_idx += ncols
+    idx_dtype = get_index_dtype(idx_arrays, maxval=max(r_idx, c_idx))
+    row = np.concatenate(row, dtype=idx_dtype)
+    col = np.concatenate(col, dtype=idx_dtype)
+    data = np.concatenate(data)
+    new_shape = (r_idx, c_idx)
+
+    return container((data, (row, col)), shape=new_shape, dtype=dtype).asformat(format)
+
+
+@_transition_to_rng("random_state")
+def random_array(shape, *, density=0.01, format='coo', dtype=None,
+                 rng=None, data_sampler=None):
+    """Return a sparse array of uniformly random numbers in [0, 1)
+
+    Returns a sparse array with the given shape and density
+    where values are generated uniformly randomly in the range [0, 1).
+
+    Parameters
+    ----------
+    shape : int or tuple of ints
+        shape of the array
+    density : real, optional (default: 0.01)
+        density of the generated matrix: density equal to one means a full
+        matrix, density of 0 means a matrix with no non-zero items.
+    format : str, optional (default: 'coo')
+        sparse matrix format.
+    dtype : dtype, optional (default: np.float64)
+        type of the returned matrix values.
+    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``.
+
+        This random state will be used for sampling `indices` (the sparsity
+        structure), and by default for the data values too (see `data_sampler`).
+    data_sampler : callable, optional (default depends on dtype)
+        Sampler of random data values with keyword arg `size`.
+        This function should take a single keyword argument `size` specifying
+        the length of its returned ndarray. It is used to generate the nonzero
+        values in the matrix after the locations of those values are chosen.
+        By default, uniform [0, 1) random values are used unless `dtype` is
+        an integer (default uniform integers from that dtype) or
+        complex (default uniform over the unit square in the complex plane).
+        For these, the `rng` is used e.g. ``rng.uniform(size=size)``.
+
+    Returns
+    -------
+    res : sparse array
+
+    Examples
+    --------
+
+    Passing a ``np.random.Generator`` instance for better performance:
+
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> rng = np.random.default_rng()
+
+    Default sampling uniformly from [0, 1):
+
+    >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng)
+
+    Providing a sampler for the values:
+
+    >>> rvs = sp.stats.poisson(25, loc=10).rvs
+    >>> S = sp.sparse.random_array((3, 4), density=0.25,
+    ...                            rng=rng, data_sampler=rvs)
+    >>> S.toarray()
+    array([[ 36.,   0.,  33.,   0.],   # random
+           [  0.,   0.,   0.,   0.],
+           [  0.,   0.,  36.,   0.]])
+
+    Building a custom distribution.
+    This example builds a squared normal from np.random:
+
+    >>> def np_normal_squared(size=None, rng=rng):
+    ...     return rng.standard_normal(size) ** 2
+    >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+    ...                            data_sampler=np_normal_squared)
+
+    Or we can build it from sp.stats style rvs functions:
+
+    >>> def sp_stats_normal_squared(size=None, rng=rng):
+    ...     std_normal = sp.stats.distributions.norm_gen().rvs
+    ...     return std_normal(size=size, random_state=rng) ** 2
+    >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+    ...                            data_sampler=sp_stats_normal_squared)
+
+    Or we can subclass sp.stats rv_continuous or rv_discrete:
+
+    >>> class NormalSquared(sp.stats.rv_continuous):
+    ...     def _rvs(self,  size=None, random_state=rng):
+    ...         return rng.standard_normal(size) ** 2
+    >>> X = NormalSquared()
+    >>> Y = X().rvs
+    >>> S = sp.sparse.random_array((3, 4), density=0.25,
+    ...                            rng=rng, data_sampler=Y)
+    """
+    data, ind = _random(shape, density, format, dtype, rng, data_sampler)
+
+    # downcast, if safe, before calling coo_constructor
+    idx_dtype = get_index_dtype(maxval=max(shape))
+    ind = tuple(np.asarray(co, dtype=idx_dtype) for co in ind)
+    return coo_array((data, ind), shape=shape).asformat(format)
+
+
+def _random(shape, density=0.01, format=None, dtype=None,
+            rng=None, data_sampler=None):
+    if density < 0 or density > 1:
+        raise ValueError("density expected to be 0 <= density <= 1")
+
+    tot_prod = math.prod(shape)  # use `math` for when prod is >= 2**64
+
+    # Number of non zero values
+    size = int(round(density * tot_prod))
+
+    rng = check_random_state(rng)
+
+    if data_sampler is None:
+        if np.issubdtype(dtype, np.integer):
+            def data_sampler(size):
+                return rng_integers(rng,
+                                    np.iinfo(dtype).min,
+                                    np.iinfo(dtype).max,
+                                    size,
+                                    dtype=dtype)
+        elif np.issubdtype(dtype, np.complexfloating):
+            def data_sampler(size):
+                return (rng.uniform(size=size) +
+                        rng.uniform(size=size) * 1j)
+        else:
+            data_sampler = rng.uniform
+
+    idx_dtype = get_index_dtype(maxval=max(shape))
+    # rng.choice uses int64 if first arg is an int
+    if tot_prod <= np.iinfo(np.int64).max:
+        raveled_ind = rng.choice(tot_prod, size=size, replace=False)
+        ind = np.unravel_index(raveled_ind, shape=shape, order='F')
+        ind = tuple(np.asarray(co, idx_dtype) for co in ind)
+    else:
+        # for ravel indices bigger than dtype max, use sets to remove duplicates
+        ndim = len(shape)
+        seen = set()
+        while len(seen) < size:
+            dsize = size - len(seen)
+            seen.update(map(tuple, rng_integers(rng, shape, size=(dsize, ndim))))
+        ind = tuple(np.array(list(seen), dtype=idx_dtype).T)
+
+    # size kwarg allows eg data_sampler=partial(np.random.poisson, lam=5)
+    vals = data_sampler(size=size).astype(dtype, copy=False)
+    return vals, ind
+
+
+@_transition_to_rng("random_state", position_num=5)
+def random(m, n, density=0.01, format='coo', dtype=None,
+           rng=None, data_rvs=None):
+    """Generate a sparse matrix of the given shape and density with randomly
+    distributed values.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``random_array`` to take advantage of the
+        sparse array functionality.
+
+    Parameters
+    ----------
+    m, n : int
+        shape of the matrix
+    density : real, optional
+        density of the generated matrix: density equal to one means a full
+        matrix, density of 0 means a matrix with no non-zero items.
+    format : str, optional
+        sparse matrix format.
+    dtype : dtype, optional
+        type of the returned matrix values.
+    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``.
+
+        This random state will be used for sampling the sparsity structure, but
+        not necessarily for sampling the values of the structurally nonzero
+        entries of the matrix.
+    data_rvs : callable, optional
+        Samples a requested number of random values.
+        This function should take a single argument specifying the length
+        of the ndarray that it will return. The structurally nonzero entries
+        of the sparse random matrix will be taken from the array sampled
+        by this function. By default, uniform [0, 1) random values will be
+        sampled using the same random state as is used for sampling
+        the sparsity structure.
+
+    Returns
+    -------
+    res : sparse matrix
+
+    See Also
+    --------
+    random_array : constructs sparse arrays instead of sparse matrices
+
+    Examples
+    --------
+
+    Passing a ``np.random.Generator`` instance for better performance:
+
+    >>> import scipy as sp
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng)
+
+    Providing a sampler for the values:
+
+    >>> rvs = sp.stats.poisson(25, loc=10).rvs
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=rvs)
+    >>> S.toarray()
+    array([[ 36.,   0.,  33.,   0.],   # random
+           [  0.,   0.,   0.,   0.],
+           [  0.,   0.,  36.,   0.]])
+
+    Building a custom distribution.
+    This example builds a squared normal from np.random:
+
+    >>> def np_normal_squared(size=None, rng=rng):
+    ...     return rng.standard_normal(size) ** 2
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng,
+    ...                      data_rvs=np_normal_squared)
+
+    Or we can build it from sp.stats style rvs functions:
+
+    >>> def sp_stats_normal_squared(size=None, rng=rng):
+    ...     std_normal = sp.stats.distributions.norm_gen().rvs
+    ...     return std_normal(size=size, random_state=rng) ** 2
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng,
+    ...                      data_rvs=sp_stats_normal_squared)
+
+    Or we can subclass sp.stats rv_continuous or rv_discrete:
+
+    >>> class NormalSquared(sp.stats.rv_continuous):
+    ...     def _rvs(self,  size=None, random_state=rng):
+    ...         return rng.standard_normal(size) ** 2
+    >>> X = NormalSquared()
+    >>> Y = X()  # get a frozen version of the distribution
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=Y.rvs)
+    """
+    if n is None:
+        n = m
+    m, n = int(m), int(n)
+    # make keyword syntax work for data_rvs e.g. data_rvs(size=7)
+    if data_rvs is not None:
+        def data_rvs_kw(size):
+            return data_rvs(size)
+    else:
+        data_rvs_kw = None
+    vals, ind = _random((m, n), density, format, dtype, rng, data_rvs_kw)
+    return coo_matrix((vals, ind), shape=(m, n)).asformat(format)
+
+
+@_transition_to_rng("random_state", position_num=5)
+def rand(m, n, density=0.01, format="coo", dtype=None, rng=None):
+    """Generate a sparse matrix of the given shape and density with uniformly
+    distributed values.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``random_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    m, n : int
+        shape of the matrix
+    density : real, optional
+        density of the generated matrix: density equal to one means a full
+        matrix, density of 0 means a matrix with no non-zero items.
+    format : str, optional
+        sparse matrix format.
+    dtype : dtype, optional
+        type of the returned matrix values.
+    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``.
+
+    Returns
+    -------
+    res : sparse matrix
+
+    Notes
+    -----
+    Only float types are supported for now.
+
+    See Also
+    --------
+    random : Similar function allowing a custom random data sampler
+    random_array : Similar to random() but returns a sparse array
+
+    Examples
+    --------
+    >>> from scipy.sparse import rand
+    >>> matrix = rand(3, 4, density=0.25, format="csr", rng=42)
+    >>> matrix
+    
+    >>> matrix.toarray()
+    array([[0.05641158, 0.        , 0.        , 0.65088847],  # random
+           [0.        , 0.        , 0.        , 0.14286682],
+           [0.        , 0.        , 0.        , 0.        ]])
+
+    """
+    return random(m, n, density, format, dtype, rng)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_csc.py b/venv/lib/python3.10/site-packages/scipy/sparse/_csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a03f50f6a29c71a838e6a9c93d61c20114bb432
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_csc.py
@@ -0,0 +1,367 @@
+"""Compressed Sparse Column matrix format"""
+__docformat__ = "restructuredtext en"
+
+__all__ = ['csc_array', 'csc_matrix', 'isspmatrix_csc']
+
+
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray
+from ._sparsetools import csc_tocsr, expandptr
+from ._sputils import upcast
+
+from ._compressed import _cs_matrix
+
+
+class _csc_base(_cs_matrix):
+    _format = 'csc'
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse arrays/matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        M, N = self.shape
+
+        return self._csr_container((self.data, self.indices,
+                                    self.indptr), (N, M), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def __iter__(self):
+        yield from self.tocsr()
+
+    def tocsc(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tocsr(self, copy=False):
+        M,N = self.shape
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                    maxval=max(self.nnz, N))
+        indptr = np.empty(M + 1, dtype=idx_dtype)
+        indices = np.empty(self.nnz, dtype=idx_dtype)
+        data = np.empty(self.nnz, dtype=upcast(self.dtype))
+
+        csc_tocsr(M, N,
+                  self.indptr.astype(idx_dtype),
+                  self.indices.astype(idx_dtype),
+                  self.data,
+                  indptr,
+                  indices,
+                  data)
+
+        A = self._csr_container(
+            (data, indices, indptr),
+            shape=self.shape, copy=False
+        )
+        A.has_sorted_indices = True
+        return A
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+    def nonzero(self):
+        # CSC can't use _cs_matrix's .nonzero method because it
+        # returns the indices sorted for self transposed.
+
+        # Get row and col indices, from _cs_matrix.tocoo
+        major_dim, minor_dim = self._swap(self.shape)
+        minor_indices = self.indices
+        major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)
+        expandptr(major_dim, self.indptr, major_indices)
+        row, col = self._swap((major_indices, minor_indices))
+
+        # Remove explicit zeros
+        nz_mask = self.data != 0
+        row = row[nz_mask]
+        col = col[nz_mask]
+
+        # Sort them to be in C-style order
+        ind = np.argsort(row, kind='mergesort')
+        row = row[ind]
+        col = col[ind]
+
+        return row, col
+
+    nonzero.__doc__ = _cs_matrix.nonzero.__doc__
+
+    def _getrow(self, i):
+        """Returns a copy of row i of the matrix, as a (1 x n)
+        CSR matrix (row vector).
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError('index (%d) out of range' % i)
+        return self._get_submatrix(minor=i).tocsr()
+
+    def _getcol(self, i):
+        """Returns a copy of column i of the matrix, as a (m x 1)
+        CSC matrix (column vector).
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += N
+        if i < 0 or i >= N:
+            raise IndexError('index (%d) out of range' % i)
+        return self._get_submatrix(major=i, copy=True)
+
+    def _get_intXarray(self, row, col):
+        return self._major_index_fancy(col)._get_submatrix(minor=row)
+
+    def _get_intXslice(self, row, col):
+        if col.step in (1, None):
+            return self._get_submatrix(major=col, minor=row, copy=True)
+        return self._major_slice(col)._get_submatrix(minor=row)
+
+    def _get_sliceXint(self, row, col):
+        if row.step in (1, None):
+            return self._get_submatrix(major=col, minor=row, copy=True)
+        return self._get_submatrix(major=col)._minor_slice(row)
+
+    def _get_sliceXarray(self, row, col):
+        return self._major_index_fancy(col)._minor_slice(row)
+
+    def _get_arrayXint(self, row, col):
+        res = self._get_submatrix(major=col)._minor_index_fancy(row)
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_arrayXslice(self, row, col):
+        return self._major_slice(col)._minor_index_fancy(row)
+
+    # these functions are used by the parent class (_cs_matrix)
+    # to remove redundancy between csc_array and csr_matrix
+    @staticmethod
+    def _swap(x):
+        """swap the members of x if this is a column-oriented matrix
+        """
+        return x[1], x[0]
+
+
+def isspmatrix_csc(x):
+    """Is `x` of csc_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a csc matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a csc matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import csc_array, csc_matrix, coo_matrix, isspmatrix_csc
+    >>> isspmatrix_csc(csc_matrix([[5]]))
+    True
+    >>> isspmatrix_csc(csc_array([[5]]))
+    False
+    >>> isspmatrix_csc(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, csc_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class csc_array(_csc_base, sparray):
+    """
+    Compressed Sparse Column array.
+
+    This can be instantiated in several ways:
+        csc_array(D)
+            where D is a 2-D ndarray
+
+        csc_array(S)
+            with another sparse array or matrix S (equivalent to S.tocsc())
+
+        csc_array((M, N), [dtype])
+            to construct an empty array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csc_array((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csc_array((data, indices, indptr), [shape=(M, N)])
+            is the standard CSC representation where the row indices for
+            column i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding values are stored in
+            ``data[indptr[i]:indptr[i+1]]``.  If the shape parameter is
+            not supplied, the array dimensions are inferred from
+            the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSC format data array of the array
+    indices
+        CSC format index array of the array
+    indptr
+        CSC format index pointer array of the array
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSC format
+        - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
+        - efficient column slicing
+        - fast matrix vector products (CSR, BSR may be faster)
+
+    Disadvantages of the CSC format
+      - slow row slicing operations (consider CSR)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical format
+      - Within each column, indices are sorted by row.
+      - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> csc_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 2, 2, 0, 1, 2])
+    >>> col = np.array([0, 0, 1, 2, 2, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_array((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    """
+
+
+class csc_matrix(spmatrix, _csc_base):
+    """
+    Compressed Sparse Column matrix.
+
+    This can be instantiated in several ways:
+        csc_matrix(D)
+            where D is a 2-D ndarray
+
+        csc_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tocsc())
+
+        csc_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csc_matrix((data, indices, indptr), [shape=(M, N)])
+            is the standard CSC representation where the row indices for
+            column i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding values are stored in
+            ``data[indptr[i]:indptr[i+1]]``.  If the shape parameter is
+            not supplied, the matrix dimensions are inferred from
+            the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSC format data array of the matrix
+    indices
+        CSC format index array of the matrix
+    indptr
+        CSC format index pointer array of the matrix
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSC format
+        - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
+        - efficient column slicing
+        - fast matrix vector products (CSR, BSR may be faster)
+
+    Disadvantages of the CSC format
+      - slow row slicing operations (consider CSR)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical format
+      - Within each column, indices are sorted by row.
+      - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_matrix
+    >>> csc_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 2, 2, 0, 1, 2])
+    >>> col = np.array([0, 0, 1, 2, 2, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    """
+
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_csr.py b/venv/lib/python3.10/site-packages/scipy/sparse/_csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..52ce35cdb1fbf75c26a08b4e13b93d236566ab0b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_csr.py
@@ -0,0 +1,558 @@
+"""Compressed Sparse Row matrix format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['csr_array', 'csr_matrix', 'isspmatrix_csr']
+
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray
+from ._sparsetools import (csr_tocsc, csr_tobsr, csr_count_blocks,
+                           get_csr_submatrix, csr_sample_values)
+from ._sputils import upcast
+
+from ._compressed import _cs_matrix
+
+
+class _csr_base(_cs_matrix):
+    _format = 'csr'
+    _allow_nd = (1, 2)
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse arrays/matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        if self.ndim == 1:
+            return self.copy() if copy else self
+        M, N = self.shape
+        return self._csc_container((self.data, self.indices,
+                                    self.indptr), shape=(N, M), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def tolil(self, copy=False):
+        if self.ndim != 2:
+            raise ValueError("Cannot convert a 1d sparse array to lil format")
+        lil = self._lil_container(self.shape, dtype=self.dtype)
+
+        self.sum_duplicates()
+        ptr,ind,dat = self.indptr,self.indices,self.data
+        rows, data = lil.rows, lil.data
+
+        for n in range(self.shape[0]):
+            start = ptr[n]
+            end = ptr[n+1]
+            rows[n] = ind[start:end].tolist()
+            data[n] = dat[start:end].tolist()
+
+        return lil
+
+    tolil.__doc__ = _spbase.tolil.__doc__
+
+    def tocsr(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+    def tocsc(self, copy=False):
+        if self.ndim != 2:
+            raise ValueError("Cannot convert a 1d sparse array to csc format")
+        M, N = self.shape
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                    maxval=max(self.nnz, M))
+        indptr = np.empty(N + 1, dtype=idx_dtype)
+        indices = np.empty(self.nnz, dtype=idx_dtype)
+        data = np.empty(self.nnz, dtype=upcast(self.dtype))
+
+        csr_tocsc(M, N,
+                  self.indptr.astype(idx_dtype),
+                  self.indices.astype(idx_dtype),
+                  self.data,
+                  indptr,
+                  indices,
+                  data)
+
+        A = self._csc_container((data, indices, indptr), shape=self.shape)
+        A.has_sorted_indices = True
+        return A
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tobsr(self, blocksize=None, copy=True):
+        if self.ndim != 2:
+            raise ValueError("Cannot convert a 1d sparse array to bsr format")
+        if blocksize is None:
+            from ._spfuncs import estimate_blocksize
+            return self.tobsr(blocksize=estimate_blocksize(self))
+
+        elif blocksize == (1,1):
+            arg1 = (self.data.reshape(-1,1,1),self.indices,self.indptr)
+            return self._bsr_container(arg1, shape=self.shape, copy=copy)
+
+        else:
+            R,C = blocksize
+            M,N = self.shape
+
+            if R < 1 or C < 1 or M % R != 0 or N % C != 0:
+                raise ValueError(f'invalid blocksize {blocksize}')
+
+            blks = csr_count_blocks(M,N,R,C,self.indptr,self.indices)
+
+            idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                        maxval=max(N//C, blks))
+            indptr = np.empty(M//R+1, dtype=idx_dtype)
+            indices = np.empty(blks, dtype=idx_dtype)
+            data = np.zeros((blks,R,C), dtype=self.dtype)
+
+            csr_tobsr(M, N, R, C,
+                      self.indptr.astype(idx_dtype),
+                      self.indices.astype(idx_dtype),
+                      self.data,
+                      indptr, indices, data.ravel())
+
+            return self._bsr_container(
+                (data, indices, indptr), shape=self.shape
+            )
+
+    tobsr.__doc__ = _spbase.tobsr.__doc__
+
+    # these functions are used by the parent class (_cs_matrix)
+    # to remove redundancy between csc_matrix and csr_array
+    @staticmethod
+    def _swap(x):
+        """swap the members of x if this is a column-oriented matrix
+        """
+        return x
+
+    def __iter__(self):
+        if self.ndim == 1:
+            zero = self.dtype.type(0)
+            u = 0
+            for v, d in zip(self.indices, self.data):
+                for _ in range(v - u):
+                    yield zero
+                yield d
+                u = v + 1
+            for _ in range(self.shape[0] - u):
+                yield zero
+            return
+
+        indptr = np.zeros(2, dtype=self.indptr.dtype)
+        # return 1d (sparray) or 2drow (spmatrix)
+        shape = self.shape[1:] if isinstance(self, sparray) else (1, self.shape[1])
+        i0 = 0
+        for i1 in self.indptr[1:]:
+            indptr[1] = i1 - i0
+            indices = self.indices[i0:i1]
+            data = self.data[i0:i1]
+            yield self.__class__((data, indices, indptr), shape=shape, copy=True)
+            i0 = i1
+
+    def _getrow(self, i):
+        """Returns a copy of row i of the matrix, as a (1 x n)
+        CSR matrix (row vector).
+        """
+        if self.ndim == 1:
+            if i not in (0, -1):
+                raise IndexError(f'index ({i}) out of range')
+            return self.reshape((1, self.shape[0]), copy=True)
+
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError('index (%d) out of range' % i)
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data, i, i + 1, 0, N)
+        return self.__class__((data, indices, indptr), shape=(1, N),
+                              dtype=self.dtype, copy=False)
+
+    def _getcol(self, i):
+        """Returns a copy of column i. A (m x 1) sparse array (column vector).
+        """
+        if self.ndim == 1:
+            raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += N
+        if i < 0 or i >= N:
+            raise IndexError('index (%d) out of range' % i)
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data, 0, M, i, i + 1)
+        return self.__class__((data, indices, indptr), shape=(M, 1),
+                              dtype=self.dtype, copy=False)
+
+    def _get_int(self, idx):
+        spot = np.flatnonzero(self.indices == idx)
+        if spot.size:
+            return self.data[spot[0]]
+        return self.data.dtype.type(0)
+
+    def _get_slice(self, idx):
+        if idx == slice(None):
+            return self.copy()
+        if idx.step in (1, None):
+            ret = self._get_submatrix(0, idx, copy=True)
+            return ret.reshape(ret.shape[-1])
+        return self._minor_slice(idx)
+
+    def _get_array(self, idx):
+        idx_dtype = self._get_index_dtype(self.indices)
+        idx = np.asarray(idx, dtype=idx_dtype)
+        if idx.size == 0:
+            return self.__class__([], dtype=self.dtype)
+
+        M, N = 1, self.shape[0]
+        row = np.zeros_like(idx, dtype=idx_dtype)
+        col = np.asarray(idx, dtype=idx_dtype)
+        val = np.empty(row.size, dtype=self.dtype)
+        csr_sample_values(M, N, self.indptr, self.indices, self.data,
+                          row.size, row, col, val)
+
+        new_shape = col.shape if col.shape[0] > 1 else (col.shape[0],)
+        return self.__class__(val.reshape(new_shape))
+
+    def _get_intXarray(self, row, col):
+        return self._getrow(row)._minor_index_fancy(col)
+
+    def _get_intXslice(self, row, col):
+        if col.step in (1, None):
+            return self._get_submatrix(row, col, copy=True)
+        # TODO: uncomment this once it's faster:
+        # return self._getrow(row)._minor_slice(col)
+
+        M, N = self.shape
+        start, stop, stride = col.indices(N)
+
+        ii, jj = self.indptr[row:row+2]
+        row_indices = self.indices[ii:jj]
+        row_data = self.data[ii:jj]
+
+        if stride > 0:
+            ind = (row_indices >= start) & (row_indices < stop)
+        else:
+            ind = (row_indices <= start) & (row_indices > stop)
+
+        if abs(stride) > 1:
+            ind &= (row_indices - start) % stride == 0
+
+        row_indices = (row_indices[ind] - start) // stride
+        row_data = row_data[ind]
+        row_indptr = np.array([0, len(row_indices)])
+
+        if stride < 0:
+            row_data = row_data[::-1]
+            row_indices = abs(row_indices[::-1])
+
+        shape = (1, max(0, int(np.ceil(float(stop - start) / stride))))
+        return self.__class__((row_data, row_indices, row_indptr), shape=shape,
+                              dtype=self.dtype, copy=False)
+
+    def _get_sliceXint(self, row, col):
+        if row.step in (1, None):
+            return self._get_submatrix(row, col, copy=True)
+        return self._major_slice(row)._get_submatrix(minor=col)
+
+    def _get_sliceXarray(self, row, col):
+        return self._major_slice(row)._minor_index_fancy(col)
+
+    def _get_arrayXint(self, row, col):
+        res = self._major_index_fancy(row)._get_submatrix(minor=col)
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_arrayXslice(self, row, col):
+        if col.step not in (1, None):
+            col = np.arange(*col.indices(self.shape[1]))
+            return self._get_arrayXarray(row, col)
+        return self._major_index_fancy(row)._get_submatrix(minor=col)
+
+    def _set_int(self, idx, x):
+        self._set_many(0, idx, x)
+
+    def _set_array(self, idx, x):
+        x = np.broadcast_to(x, idx.shape)
+        self._set_many(np.zeros_like(idx), idx, x)
+
+
+def isspmatrix_csr(x):
+    """Is `x` of csr_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a csr matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a csr matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr
+    >>> isspmatrix_csr(csr_matrix([[5]]))
+    True
+    >>> isspmatrix_csr(csr_array([[5]]))
+    False
+    >>> isspmatrix_csr(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, csr_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class csr_array(_csr_base, sparray):
+    """
+    Compressed Sparse Row array.
+
+    This can be instantiated in several ways:
+        csr_array(D)
+            where D is a 2-D ndarray
+
+        csr_array(S)
+            with another sparse array or matrix S (equivalent to S.tocsr())
+
+        csr_array((M, N), [dtype])
+            to construct an empty array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csr_array((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csr_array((data, indices, indptr), [shape=(M, N)])
+            is the standard CSR representation where the column indices for
+            row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
+            corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
+            If the shape parameter is not supplied, the array dimensions
+            are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSR format data array of the array
+    indices
+        CSR format index array of the array
+    indptr
+        CSR format index pointer array of the array
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSR format
+      - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
+      - efficient row slicing
+      - fast matrix vector products
+
+    Disadvantages of the CSR format
+      - slow column slicing operations (consider CSC)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical Format
+        - Within each row, indices are sorted by column.
+        - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array
+    >>> csr_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_array((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    Duplicate entries are summed together:
+
+    >>> row = np.array([0, 1, 2, 0])
+    >>> col = np.array([0, 1, 1, 0])
+    >>> data = np.array([1, 2, 4, 8])
+    >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[9, 0, 0],
+           [0, 2, 0],
+           [0, 4, 0]])
+
+    As an example of how to construct a CSR array incrementally,
+    the following snippet builds a term-document array from texts:
+
+    >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
+    >>> indptr = [0]
+    >>> indices = []
+    >>> data = []
+    >>> vocabulary = {}
+    >>> for d in docs:
+    ...     for term in d:
+    ...         index = vocabulary.setdefault(term, len(vocabulary))
+    ...         indices.append(index)
+    ...         data.append(1)
+    ...     indptr.append(len(indices))
+    ...
+    >>> csr_array((data, indices, indptr), dtype=int).toarray()
+    array([[2, 1, 0, 0],
+           [0, 1, 1, 1]])
+
+    """
+
+
+class csr_matrix(spmatrix, _csr_base):
+    """
+    Compressed Sparse Row matrix.
+
+    This can be instantiated in several ways:
+        csr_matrix(D)
+            where D is a 2-D ndarray
+
+        csr_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tocsr())
+
+        csr_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csr_matrix((data, indices, indptr), [shape=(M, N)])
+            is the standard CSR representation where the column indices for
+            row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
+            corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
+            If the shape parameter is not supplied, the matrix dimensions
+            are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSR format data array of the matrix
+    indices
+        CSR format index array of the matrix
+    indptr
+        CSR format index pointer array of the matrix
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSR format
+      - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
+      - efficient row slicing
+      - fast matrix vector products
+
+    Disadvantages of the CSR format
+      - slow column slicing operations (consider CSC)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical Format
+        - Within each row, indices are sorted by column.
+        - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_matrix
+    >>> csr_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    Duplicate entries are summed together:
+
+    >>> row = np.array([0, 1, 2, 0])
+    >>> col = np.array([0, 1, 1, 0])
+    >>> data = np.array([1, 2, 4, 8])
+    >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[9, 0, 0],
+           [0, 2, 0],
+           [0, 4, 0]])
+
+    As an example of how to construct a CSR matrix incrementally,
+    the following snippet builds a term-document matrix from texts:
+
+    >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
+    >>> indptr = [0]
+    >>> indices = []
+    >>> data = []
+    >>> vocabulary = {}
+    >>> for d in docs:
+    ...     for term in d:
+    ...         index = vocabulary.setdefault(term, len(vocabulary))
+    ...         indices.append(index)
+    ...         data.append(1)
+    ...     indptr.append(len(indices))
+    ...
+    >>> csr_matrix((data, indices, indptr), dtype=int).toarray()
+    array([[2, 1, 0, 0],
+           [0, 1, 1, 1]])
+
+    """
+
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_data.py b/venv/lib/python3.10/site-packages/scipy/sparse/_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..585820b10a65271b52b81d140e82130eb4177979
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_data.py
@@ -0,0 +1,569 @@
+"""Base class for sparse matrice with a .data attribute
+
+    subclasses must provide a _with_data() method that
+    creates a new matrix with the same sparsity pattern
+    as self but with a different data array
+
+"""
+
+import math
+import numpy as np
+
+from ._base import _spbase, sparray, _ufuncs_with_fixed_point_at_zero
+from ._sputils import isscalarlike, validateaxis
+
+__all__ = []
+
+
+# TODO implement all relevant operations
+# use .data.__methods__() instead of /=, *=, etc.
+class _data_matrix(_spbase):
+    def __init__(self, arg1, *, maxprint=None):
+        _spbase.__init__(self, arg1, maxprint=maxprint)
+
+    @property
+    def dtype(self):
+        return self.data.dtype
+
+    @dtype.setter
+    def dtype(self, newtype):
+        self.data.dtype = newtype
+
+    def _deduped_data(self):
+        if hasattr(self, 'sum_duplicates'):
+            self.sum_duplicates()
+        return self.data
+
+    def __abs__(self):
+        return self._with_data(abs(self._deduped_data()))
+
+    def __round__(self, ndigits=0):
+        return self._with_data(np.around(self._deduped_data(), decimals=ndigits))
+
+    def _real(self):
+        return self._with_data(self.data.real)
+
+    def _imag(self):
+        return self._with_data(self.data.imag)
+
+    def __neg__(self):
+        if self.dtype.kind == 'b':
+            raise NotImplementedError('negating a boolean sparse array is not '
+                                      'supported')
+        return self._with_data(-self.data)
+
+    def __imul__(self, other):  # self *= other
+        if isscalarlike(other):
+            self.data *= other
+            return self
+        return NotImplemented
+
+    def __itruediv__(self, other):  # self /= other
+        if isscalarlike(other):
+            recip = 1.0 / other
+            self.data *= recip
+            return self
+        else:
+            return NotImplemented
+
+    def astype(self, dtype, casting='unsafe', copy=True):
+        dtype = np.dtype(dtype)
+        if self.dtype != dtype:
+            matrix = self._with_data(
+                self.data.astype(dtype, casting=casting, copy=True),
+                copy=True
+            )
+            return matrix._with_data(matrix._deduped_data(), copy=False)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    astype.__doc__ = _spbase.astype.__doc__
+
+    def conjugate(self, copy=True):
+        if np.issubdtype(self.dtype, np.complexfloating):
+            return self._with_data(self.data.conjugate(), copy=copy)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    conjugate.__doc__ = _spbase.conjugate.__doc__
+
+    def copy(self):
+        return self._with_data(self.data.copy(), copy=True)
+
+    copy.__doc__ = _spbase.copy.__doc__
+
+    def power(self, n, dtype=None):
+        """
+        This function performs element-wise power.
+
+        Parameters
+        ----------
+        n : scalar
+            n is a non-zero scalar (nonzero avoids dense ones creation)
+            If zero power is desired, special case it to use `np.ones`
+
+        dtype : If dtype is not specified, the current dtype will be preserved.
+
+        Raises
+        ------
+        NotImplementedError : if n is a zero scalar
+            If zero power is desired, special case it to use
+            ``np.ones(A.shape, dtype=A.dtype)``
+        """
+        if not isscalarlike(n):
+            raise NotImplementedError("input is not scalar")
+        if not n:
+            raise NotImplementedError(
+                "zero power is not supported as it would densify the matrix.\n"
+                "Use `np.ones(A.shape, dtype=A.dtype)` for this case."
+            )
+
+        data = self._deduped_data()
+        if dtype is not None:
+            data = data.astype(dtype)
+        return self._with_data(data ** n)
+
+    ###########################
+    # Multiplication handlers #
+    ###########################
+
+    def _mul_scalar(self, other):
+        return self._with_data(self.data * other)
+
+
+# Add the numpy unary ufuncs for which func(0) = 0 to _data_matrix.
+for npfunc in _ufuncs_with_fixed_point_at_zero:
+    name = npfunc.__name__
+
+    def _create_method(op):
+        def method(self):
+            result = op(self._deduped_data())
+            return self._with_data(result, copy=True)
+
+        method.__doc__ = (f"Element-wise {name}.\n\n"
+                          f"See `numpy.{name}` for more information.")
+        method.__name__ = name
+
+        return method
+
+    setattr(_data_matrix, name, _create_method(npfunc))
+
+
+def _find_missing_index(ind, n):
+    for k, a in enumerate(ind):
+        if k != a:
+            return k
+
+    k += 1
+    if k < n:
+        return k
+    else:
+        return -1
+
+
+class _minmax_mixin:
+    """Mixin for min and max methods.
+
+    These are not implemented for dia_matrix, hence the separate class.
+    """
+
+    def _min_or_max_axis(self, axis, min_or_max, explicit):
+        N = self.shape[axis]
+        if N == 0:
+            raise ValueError("zero-size array to reduction operation")
+        M = self.shape[1 - axis]
+        idx_dtype = self._get_index_dtype(maxval=M)
+
+        mat = self.tocsc() if axis == 0 else self.tocsr()
+        mat.sum_duplicates()
+
+        major_index, value = mat._minor_reduce(min_or_max)
+        if not explicit:
+            not_full = np.diff(mat.indptr)[major_index] < N
+            value[not_full] = min_or_max(value[not_full], 0)
+
+        mask = value != 0
+        major_index = np.compress(mask, major_index).astype(idx_dtype, copy=False)
+        value = np.compress(mask, value)
+
+        if isinstance(self, sparray):
+            coords = (major_index,)
+            shape = (M,)
+            return self._coo_container((value, coords), shape=shape, dtype=self.dtype)
+
+        if axis == 0:
+            return self._coo_container(
+                (value, (np.zeros(len(value), dtype=idx_dtype), major_index)),
+                dtype=self.dtype, shape=(1, M)
+            )
+        else:
+            return self._coo_container(
+                (value, (major_index, np.zeros(len(value), dtype=idx_dtype))),
+                dtype=self.dtype, shape=(M, 1)
+            )
+
+    def _min_or_max(self, axis, out, min_or_max, explicit):
+        if out is not None:
+            raise ValueError("Sparse arrays do not support an 'out' parameter.")
+
+        validateaxis(axis)
+        if self.ndim == 1:
+            if axis not in (None, 0, -1):
+                raise ValueError("axis out of range")
+            axis = None  # avoid calling special axis case. no impact on 1d
+
+        if axis is None:
+            if 0 in self.shape:
+                raise ValueError("zero-size array to reduction operation")
+
+            zero = self.dtype.type(0)
+            if self.nnz == 0:
+                return zero
+            m = min_or_max.reduce(self._deduped_data().ravel())
+            if self.nnz != math.prod(self.shape) and not explicit:
+                m = min_or_max(zero, m)
+            return m
+
+        if axis < 0:
+            axis += 2
+
+        if (axis == 0) or (axis == 1):
+            return self._min_or_max_axis(axis, min_or_max, explicit)
+        else:
+            raise ValueError("axis out of range")
+
+    def _arg_min_or_max_axis(self, axis, argmin_or_argmax, compare, explicit):
+        if self.shape[axis] == 0:
+            raise ValueError("Cannot apply the operation along a zero-sized dimension.")
+
+        if axis < 0:
+            axis += 2
+
+        zero = self.dtype.type(0)
+
+        mat = self.tocsc() if axis == 0 else self.tocsr()
+        mat.sum_duplicates()
+
+        ret_size, line_size = mat._swap(mat.shape)
+        ret = np.zeros(ret_size, dtype=int)
+
+        nz_lines, = np.nonzero(np.diff(mat.indptr))
+        for i in nz_lines:
+            p, q = mat.indptr[i:i + 2]
+            data = mat.data[p:q]
+            indices = mat.indices[p:q]
+            extreme_index = argmin_or_argmax(data)
+            extreme_value = data[extreme_index]
+            if explicit:
+                if q - p > 0:
+                    ret[i] = indices[extreme_index]
+            else:
+                if compare(extreme_value, zero) or q - p == line_size:
+                    ret[i] = indices[extreme_index]
+                else:
+                    zero_ind = _find_missing_index(indices, line_size)
+                    if extreme_value == zero:
+                        ret[i] = min(extreme_index, zero_ind)
+                    else:
+                        ret[i] = zero_ind
+
+        if isinstance(self, sparray):
+            return ret
+
+        if axis == 1:
+            ret = ret.reshape(-1, 1)
+
+        return self._ascontainer(ret)
+
+    def _arg_min_or_max(self, axis, out, argmin_or_argmax, compare, explicit):
+        if out is not None:
+            raise ValueError("Sparse types do not support an 'out' parameter.")
+
+        validateaxis(axis)
+
+        if self.ndim == 1:
+            if axis not in (None, 0, -1):
+                raise ValueError("axis out of range")
+            axis = None  # avoid calling special axis case. no impact on 1d
+
+        if axis is not None:
+            return self._arg_min_or_max_axis(axis, argmin_or_argmax, compare, explicit)
+
+        if 0 in self.shape:
+            raise ValueError("Cannot apply the operation to an empty matrix.")
+
+        if self.nnz == 0:
+            if explicit:
+                raise ValueError("Cannot apply the operation to zero matrix "
+                                 "when explicit=True.")
+            return 0
+
+        zero = self.dtype.type(0)
+        mat = self.tocoo()
+        # Convert to canonical form: no duplicates, sorted indices.
+        mat.sum_duplicates()
+        extreme_index = argmin_or_argmax(mat.data)
+        if explicit:
+            return extreme_index
+        extreme_value = mat.data[extreme_index]
+        num_col = mat.shape[-1]
+
+        # If the min value is less than zero, or max is greater than zero,
+        # then we do not need to worry about implicit zeros.
+        if compare(extreme_value, zero):
+            # cast to Python int to avoid overflow and RuntimeError
+            return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index])
+
+        # Cheap test for the rare case where we have no implicit zeros.
+        size = math.prod(self.shape)
+        if size == mat.nnz:
+            return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index])
+
+        # At this stage, any implicit zero could be the min or max value.
+        # After sum_duplicates(), the `row` and `col` arrays are guaranteed to
+        # be sorted in C-order, which means the linearized indices are sorted.
+        linear_indices = mat.row * num_col + mat.col
+        first_implicit_zero_index = _find_missing_index(linear_indices, size)
+        if extreme_value == zero:
+            return min(first_implicit_zero_index, extreme_index)
+        return first_implicit_zero_index
+
+    def max(self, axis=None, out=None, *, explicit=False):
+        """Return the maximum of the array/matrix or maximum along an axis.
+
+        By default, all elements are taken into account, not just the non-zero ones.
+        But with `explicit` set, only the stored elements are considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the sum is computed. The default is to
+            compute the maximum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except
+            for the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amax : coo_array or scalar
+            Maximum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        min : The minimum value of a sparse array/matrix along a given axis.
+        numpy.max : NumPy's implementation of 'max'
+
+        """
+        return self._min_or_max(axis, out, np.maximum, explicit)
+
+    def min(self, axis=None, out=None, *, explicit=False):
+        """Return the minimum of the array/matrix or maximum along an axis.
+
+        By default, all elements are taken into account, not just the non-zero ones.
+        But with `explicit` set, only the stored elements are considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the sum is computed. The default is to
+            compute the minimum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amin : coo_matrix or scalar
+            Minimum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        max : The maximum value of a sparse array/matrix along a given axis.
+        numpy.min : NumPy's implementation of 'min'
+
+        """
+        return self._min_or_max(axis, out, np.minimum, explicit)
+
+    def nanmax(self, axis=None, out=None, *, explicit=False):
+        """Return the maximum, ignoring any Nans, along an axis.
+
+        Return the maximum, ignoring any Nans, of the array/matrix along an axis.
+        By default this takes all elements into account, but with `explicit` set,
+        only stored elements are considered.
+
+        .. versionadded:: 1.11.0
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the maximum is computed. The default is to
+            compute the maximum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except
+            for the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amax : coo_array or scalar
+            Maximum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        nanmin : The minimum value of a sparse array/matrix along a given axis,
+                 ignoring NaNs.
+        max : The maximum value of a sparse array/matrix along a given axis,
+              propagating NaNs.
+        numpy.nanmax : NumPy's implementation of 'nanmax'.
+
+        """
+        return self._min_or_max(axis, out, np.fmax, explicit)
+
+    def nanmin(self, axis=None, out=None, *, explicit=False):
+        """Return the minimum, ignoring any Nans, along an axis.
+
+        Return the minimum, ignoring any Nans, of the array/matrix along an axis.
+        By default this takes all elements into account, but with `explicit` set,
+        only stored elements are considered.
+
+        .. versionadded:: 1.11.0
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the minimum is computed. The default is to
+            compute the minimum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amin : coo_array or scalar
+            Minimum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        nanmax : The maximum value of a sparse array/matrix along a given axis,
+                 ignoring NaNs.
+        min : The minimum value of a sparse array/matrix along a given axis,
+              propagating NaNs.
+        numpy.nanmin : NumPy's implementation of 'nanmin'.
+
+        """
+        return self._min_or_max(axis, out, np.fmin, explicit)
+
+    def argmax(self, axis=None, out=None, *, explicit=False):
+        """Return indices of maximum elements along an axis.
+
+        By default, implicit zero elements are taken into account. If there are
+        several minimum values, the index of the first occurrence is returned.
+        If `explicit` is set, only explicitly stored elements will be considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None}, optional
+            Axis along which the argmax is computed. If None (default), index
+            of the maximum element in the flatten data is returned.
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only explicitly stored elements will be considered.
+            If axis is not None and a row/column has no stored elements, argmax
+            is undefined, so the index ``0`` is returned for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        ind : numpy.matrix or int
+            Indices of maximum elements. If matrix, its size along `axis` is 1.
+        """
+        return self._arg_min_or_max(axis, out, np.argmax, np.greater, explicit)
+
+    def argmin(self, axis=None, out=None, *, explicit=False):
+        """Return indices of minimum elements along an axis.
+
+        By default, implicit zero elements are taken into account. If there are
+        several minimum values, the index of the first occurrence is returned.
+        If `explicit` is set, only explicitly stored elements will be considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None}, optional
+            Axis along which the argmin is computed. If None (default), index
+            of the minimum element in the flatten data is returned.
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only explicitly stored elements will be considered.
+            If axis is not None and a row/column has no stored elements, argmin
+            is undefined, so the index ``0`` is returned for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+         ind : numpy.matrix or int
+            Indices of minimum elements. If matrix, its size along `axis` is 1.
+        """
+        return self._arg_min_or_max(axis, out, np.argmin, np.less, explicit)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_dok.py b/venv/lib/python3.10/site-packages/scipy/sparse/_dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9814a9e8d0b2d5a67185faae9311f4216cc7d13
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_dok.py
@@ -0,0 +1,692 @@
+"""Dictionary Of Keys based matrix"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['dok_array', 'dok_matrix', 'isspmatrix_dok']
+
+import itertools
+from warnings import warn
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray, issparse
+from ._index import IndexMixin
+from ._sputils import (isdense, getdtype, isshape, isintlike, isscalarlike,
+                       upcast, upcast_scalar, check_shape)
+
+
+class _dok_base(_spbase, IndexMixin, dict):
+    _format = 'dok'
+    _allow_nd = (1, 2)
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _spbase.__init__(self, arg1, maxprint=maxprint)
+
+        if isinstance(arg1, tuple) and isshape(arg1, allow_nd=self._allow_nd):
+            self._shape = check_shape(arg1, allow_nd=self._allow_nd)
+            self._dict = {}
+            self.dtype = getdtype(dtype, default=float)
+        elif issparse(arg1):  # Sparse ctor
+            if arg1.format == self.format:
+                arg1 = arg1.copy() if copy else arg1
+            else:
+                arg1 = arg1.todok()
+
+            if dtype is not None:
+                arg1 = arg1.astype(dtype, copy=False)
+
+            self._dict = arg1._dict
+            self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd)
+            self.dtype = getdtype(arg1.dtype)
+        else:  # Dense ctor
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise TypeError('Invalid input format.') from e
+
+            if arg1.ndim > 2:
+                raise ValueError(f"DOK arrays don't yet support {arg1.ndim}D input.")
+
+            if arg1.ndim == 1:
+                if dtype is not None:
+                    arg1 = arg1.astype(dtype)
+                self._dict = {i: v for i, v in enumerate(arg1) if v != 0}
+                self.dtype = getdtype(arg1.dtype)
+            else:
+                d = self._coo_container(arg1, shape=shape, dtype=dtype).todok()
+                self._dict = d._dict
+                self.dtype = getdtype(d.dtype)
+            self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd)
+
+    def update(self, val):
+        # Prevent direct usage of update
+        raise NotImplementedError("Direct update to DOK sparse format is not allowed.")
+
+    def _getnnz(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "_getnnz over an axis is not implemented for DOK format."
+            )
+        return len(self._dict)
+
+    def count_nonzero(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "count_nonzero over an axis is not implemented for DOK format."
+            )
+        return sum(x != 0 for x in self.values())
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def __len__(self):
+        return len(self._dict)
+
+    def __contains__(self, key):
+        return key in self._dict
+
+    def setdefault(self, key, default=None, /):
+        return self._dict.setdefault(key, default)
+
+    def __delitem__(self, key, /):
+        del self._dict[key]
+
+    def clear(self):
+        return self._dict.clear()
+
+    def pop(self, /, *args):
+        return self._dict.pop(*args)
+
+    def __reversed__(self):
+        raise TypeError("reversed is not defined for dok_array type")
+
+    def __or__(self, other):
+        type_names = f"{type(self).__name__} and {type(other).__name__}"
+        raise TypeError(f"unsupported operand type for |: {type_names}")
+
+    def __ror__(self, other):
+        type_names = f"{type(self).__name__} and {type(other).__name__}"
+        raise TypeError(f"unsupported operand type for |: {type_names}")
+
+    def __ior__(self, other):
+        type_names = f"{type(self).__name__} and {type(other).__name__}"
+        raise TypeError(f"unsupported operand type for |: {type_names}")
+
+    def popitem(self):
+        return self._dict.popitem()
+
+    def items(self):
+        return self._dict.items()
+
+    def keys(self):
+        return self._dict.keys()
+
+    def values(self):
+        return self._dict.values()
+
+    def get(self, key, default=0.0):
+        """This provides dict.get method functionality with type checking"""
+        if key in self._dict:
+            return self._dict[key]
+        if isintlike(key) and self.ndim == 1:
+            key = (key,)
+        if self.ndim != len(key):
+            raise IndexError(f'Index {key} length needs to match self.shape')
+        try:
+            for i in key:
+                assert isintlike(i)
+        except (AssertionError, TypeError, ValueError) as e:
+            raise IndexError('Index must be or consist of integers.') from e
+        key = tuple(i + M if i < 0 else i for i, M in zip(key, self.shape))
+        if any(i < 0 or i >= M for i, M in zip(key, self.shape)):
+            raise IndexError('Index out of bounds.')
+        if self.ndim == 1:
+            key = key[0]
+        return self._dict.get(key, default)
+
+    # 1D get methods
+    def _get_int(self, idx):
+        return self._dict.get(idx, self.dtype.type(0))
+
+    def _get_slice(self, idx):
+        i_range = range(*idx.indices(self.shape[0]))
+        return self._get_array(list(i_range))
+
+    def _get_array(self, idx):
+        idx = np.asarray(idx)
+        if idx.ndim == 0:
+            val = self._dict.get(int(idx), self.dtype.type(0))
+            return np.array(val, stype=self.dtype)
+        new_dok = self._dok_container(idx.shape, dtype=self.dtype)
+        dok_vals = [self._dict.get(i, 0) for i in idx.ravel()]
+        if dok_vals:
+            if len(idx.shape) == 1:
+                for i, v in enumerate(dok_vals):
+                    if v:
+                        new_dok._dict[i] = v
+            else:
+                new_idx = np.unravel_index(np.arange(len(dok_vals)), idx.shape)
+                new_idx = new_idx[0] if len(new_idx) == 1 else zip(*new_idx)
+                for i, v in zip(new_idx, dok_vals, strict=True):
+                    if v:
+                        new_dok._dict[i] = v
+        return new_dok
+
+    # 2D get methods
+    def _get_intXint(self, row, col):
+        return self._dict.get((row, col), self.dtype.type(0))
+
+    def _get_intXslice(self, row, col):
+        return self._get_sliceXslice(slice(row, row + 1), col)
+
+    def _get_sliceXint(self, row, col):
+        return self._get_sliceXslice(row, slice(col, col + 1))
+
+    def _get_sliceXslice(self, row, col):
+        row_start, row_stop, row_step = row.indices(self.shape[0])
+        col_start, col_stop, col_step = col.indices(self.shape[1])
+        row_range = range(row_start, row_stop, row_step)
+        col_range = range(col_start, col_stop, col_step)
+        shape = (len(row_range), len(col_range))
+        # Switch paths only when advantageous
+        # (count the iterations in the loops, adjust for complexity)
+        if len(self) >= 2 * shape[0] * shape[1]:
+            # O(nr*nc) path: loop over 
+            return self._get_columnXarray(row_range, col_range)
+        # O(nnz) path: loop over entries of self
+        newdok = self._dok_container(shape, dtype=self.dtype)
+        for key in self.keys():
+            i, ri = divmod(int(key[0]) - row_start, row_step)
+            if ri != 0 or i < 0 or i >= shape[0]:
+                continue
+            j, rj = divmod(int(key[1]) - col_start, col_step)
+            if rj != 0 or j < 0 or j >= shape[1]:
+                continue
+            newdok._dict[i, j] = self._dict[key]
+        return newdok
+
+    def _get_intXarray(self, row, col):
+        return self._get_columnXarray([row], col.ravel())
+
+    def _get_arrayXint(self, row, col):
+        res = self._get_columnXarray(row.ravel(), [col])
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_sliceXarray(self, row, col):
+        row = list(range(*row.indices(self.shape[0])))
+        return self._get_columnXarray(row, col)
+
+    def _get_arrayXslice(self, row, col):
+        col = list(range(*col.indices(self.shape[1])))
+        return self._get_columnXarray(row, col)
+
+    def _get_columnXarray(self, row, col):
+        # outer indexing
+        newdok = self._dok_container((len(row), len(col)), dtype=self.dtype)
+
+        for i, r in enumerate(row):
+            for j, c in enumerate(col):
+                v = self._dict.get((r, c), 0)
+                if v:
+                    newdok._dict[i, j] = v
+        return newdok
+
+    def _get_arrayXarray(self, row, col):
+        # inner indexing
+        i, j = map(np.atleast_2d, np.broadcast_arrays(row, col))
+        newdok = self._dok_container(i.shape, dtype=self.dtype)
+
+        for key in itertools.product(range(i.shape[0]), range(i.shape[1])):
+            v = self._dict.get((i[key], j[key]), 0)
+            if v:
+                newdok._dict[key] = v
+        return newdok
+
+    # 1D set methods
+    def _set_int(self, idx, x):
+        if x:
+            self._dict[idx] = x
+        elif idx in self._dict:
+            del self._dict[idx]
+
+    def _set_array(self, idx, x):
+        idx_set = idx.ravel()
+        x_set = x.ravel()
+        if len(idx_set) != len(x_set):
+            if len(x_set) == 1:
+                x_set = np.full(len(idx_set), x_set[0], dtype=self.dtype)
+            else:
+              raise ValueError("Need len(index)==len(data) or len(data)==1")
+        for i, v in zip(idx_set, x_set):
+            if v:
+                self._dict[i] = v
+            elif i in self._dict:
+                del self._dict[i]
+
+    # 2D set methods
+    def _set_intXint(self, row, col, x):
+        key = (row, col)
+        if x:
+            self._dict[key] = x
+        elif key in self._dict:
+            del self._dict[key]
+
+    def _set_arrayXarray(self, row, col, x):
+        row = list(map(int, row.ravel()))
+        col = list(map(int, col.ravel()))
+        x = x.ravel()
+        self._dict.update(zip(zip(row, col), x))
+
+        for i in np.nonzero(x == 0)[0]:
+            key = (row[i], col[i])
+            if self._dict[key] == 0:
+                # may have been superseded by later update
+                del self._dict[key]
+
+    def __add__(self, other):
+        if isscalarlike(other):
+            res_dtype = upcast_scalar(self.dtype, other)
+            new = self._dok_container(self.shape, dtype=res_dtype)
+            # Add this scalar to each element.
+            for key in itertools.product(*[range(d) for d in self.shape]):
+                aij = self._dict.get(key, 0) + other
+                if aij:
+                    new[key] = aij
+        elif issparse(other):
+            if other.shape != self.shape:
+                raise ValueError("Matrix dimensions are not equal.")
+            res_dtype = upcast(self.dtype, other.dtype)
+            new = self._dok_container(self.shape, dtype=res_dtype)
+            new._dict = self._dict.copy()
+            if other.format == "dok":
+                o_items = other.items()
+            else:
+                other = other.tocoo()
+                if self.ndim == 1:
+                    o_items = zip(other.coords[0], other.data)
+                else:
+                    o_items = zip(zip(*other.coords), other.data)
+            with np.errstate(over='ignore'):
+                new._dict.update((k, new[k] + v) for k, v in o_items)
+        elif isdense(other):
+            new = self.todense() + other
+        else:
+            return NotImplemented
+        return new
+
+    def __radd__(self, other):
+        return self + other  # addition is commutative
+
+    def __neg__(self):
+        if self.dtype.kind == 'b':
+            raise NotImplementedError(
+                'Negating a sparse boolean matrix is not supported.'
+            )
+        new = self._dok_container(self.shape, dtype=self.dtype)
+        new._dict.update((k, -v) for k, v in self.items())
+        return new
+
+    def _mul_scalar(self, other):
+        res_dtype = upcast_scalar(self.dtype, other)
+        # Multiply this scalar by every element.
+        new = self._dok_container(self.shape, dtype=res_dtype)
+        new._dict.update(((k, v * other) for k, v in self.items()))
+        return new
+
+    def _matmul_vector(self, other):
+        res_dtype = upcast(self.dtype, other.dtype)
+
+        # vector @ vector
+        if self.ndim == 1:
+            if issparse(other):
+                if other.format == "dok":
+                    keys = self.keys() & other.keys()
+                else:
+                    keys = self.keys() & other.tocoo().coords[0]
+                return res_dtype(sum(self._dict[k] * other._dict[k] for k in keys))
+            elif isdense(other):
+                return res_dtype(sum(other[k] * v for k, v in self.items()))
+            else:
+                return NotImplemented
+
+        # matrix @ vector
+        result = np.zeros(self.shape[0], dtype=res_dtype)
+        for (i, j), v in self.items():
+            result[i] += v * other[j]
+        return result
+
+    def _matmul_multivector(self, other):
+        result_dtype = upcast(self.dtype, other.dtype)
+        # vector @ multivector
+        if self.ndim == 1:
+            # works for other 1d or 2d
+            return sum(v * other[j] for j, v in self._dict.items())
+
+        # matrix @ multivector
+        M = self.shape[0]
+        new_shape = (M,) if other.ndim == 1 else (M, other.shape[1])
+        result = np.zeros(new_shape, dtype=result_dtype)
+        for (i, j), v in self.items():
+            result[i] += v * other[j]
+        return result
+
+    def __imul__(self, other):
+        if isscalarlike(other):
+            self._dict.update((k, v * other) for k, v in self.items())
+            return self
+        return NotImplemented
+
+    def __truediv__(self, other):
+        if isscalarlike(other):
+            res_dtype = upcast_scalar(self.dtype, other)
+            new = self._dok_container(self.shape, dtype=res_dtype)
+            new._dict.update(((k, v / other) for k, v in self.items()))
+            return new
+        return self.tocsr() / other
+
+    def __itruediv__(self, other):
+        if isscalarlike(other):
+            self._dict.update((k, v / other) for k, v in self.items())
+            return self
+        return NotImplemented
+
+    def __reduce__(self):
+        # this approach is necessary because __setstate__ is called after
+        # __setitem__ upon unpickling and since __init__ is not called there
+        # is no shape attribute hence it is not possible to unpickle it.
+        return dict.__reduce__(self)
+
+    def diagonal(self, k=0):
+        if self.ndim == 2:
+            return super().diagonal(k)
+        raise ValueError("diagonal requires two dimensions")
+
+    def transpose(self, axes=None, copy=False):
+        if self.ndim == 1:
+            return self.copy()
+
+        if axes is not None and axes != (1, 0):
+            raise ValueError(
+                "Sparse arrays/matrices do not support "
+                "an 'axes' parameter because swapping "
+                "dimensions is the only logical permutation."
+            )
+
+        M, N = self.shape
+        new = self._dok_container((N, M), dtype=self.dtype, copy=copy)
+        new._dict.update((((right, left), val) for (left, right), val in self.items()))
+        return new
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def conjtransp(self):
+        """DEPRECATED: Return the conjugate transpose.
+
+        .. deprecated:: 1.14.0
+
+            `conjtransp` is deprecated and will be removed in v1.16.0.
+            Use ``.T.conj()`` instead.
+        """
+        msg = ("`conjtransp` is deprecated and will be removed in v1.16.0. "
+                   "Use `.T.conj()` instead.")
+        warn(msg, DeprecationWarning, stacklevel=2)
+
+        if self.ndim == 1:
+            new = self.tocoo()
+            new.data = new.data.conjugate()
+            return new
+
+        M, N = self.shape
+        new = self._dok_container((N, M), dtype=self.dtype)
+        new._dict = {(right, left): np.conj(val) for (left, right), val in self.items()}
+        return new
+
+    def copy(self):
+        new = self._dok_container(self.shape, dtype=self.dtype)
+        new._dict.update(self._dict)
+        return new
+
+    copy.__doc__ = _spbase.copy.__doc__
+
+    @classmethod
+    def fromkeys(cls, iterable, value=1, /):
+        tmp = dict.fromkeys(iterable, value)
+        if isinstance(next(iter(tmp)), tuple):
+            shape = tuple(max(idx) + 1 for idx in zip(*tmp))
+        else:
+            shape = (max(tmp) + 1,)
+        result = cls(shape, dtype=type(value))
+        result._dict = tmp
+        return result
+
+    def tocoo(self, copy=False):
+        nnz = self.nnz
+        if nnz == 0:
+            return self._coo_container(self.shape, dtype=self.dtype)
+
+        idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+        data = np.fromiter(self.values(), dtype=self.dtype, count=nnz)
+        # handle 1d keys specially b/c not a tuple
+        inds = zip(*self.keys()) if self.ndim > 1 else (self.keys(),)
+        coords = tuple(np.fromiter(ix, dtype=idx_dtype, count=nnz) for ix in inds)
+        A = self._coo_container((data, coords), shape=self.shape, dtype=self.dtype)
+        A.has_canonical_format = True
+        return A
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    def todok(self, copy=False):
+        if copy:
+            return self.copy()
+        return self
+
+    todok.__doc__ = _spbase.todok.__doc__
+
+    def tocsc(self, copy=False):
+        if self.ndim == 1:
+            raise NotImplementedError("tocsr() not valid for 1d sparse array")
+        return self.tocoo(copy=False).tocsc(copy=copy)
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def resize(self, *shape):
+        shape = check_shape(shape, allow_nd=self._allow_nd)
+        if len(shape) != len(self.shape):
+            # TODO implement resize across dimensions
+            raise NotImplementedError
+
+        if self.ndim == 1:
+            newN = shape[-1]
+            for i in list(self._dict):
+                if i >= newN:
+                    del self._dict[i]
+            self._shape = shape
+            return
+
+        newM, newN = shape
+        M, N = self.shape
+        if newM < M or newN < N:
+            # Remove all elements outside new dimensions
+            for i, j in list(self.keys()):
+                if i >= newM or j >= newN:
+                    del self._dict[i, j]
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    # Added for 1d to avoid `tocsr` from _base.py
+    def astype(self, dtype, casting='unsafe', copy=True):
+        dtype = np.dtype(dtype)
+        if self.dtype != dtype:
+            result = self._dok_container(self.shape, dtype=dtype)
+            data = np.array(list(self._dict.values()), dtype=dtype)
+            result._dict = dict(zip(self._dict, data))
+            return result
+        elif copy:
+            return self.copy()
+        return self
+
+
+def isspmatrix_dok(x):
+    """Is `x` of dok_array type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a dok matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a dok matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import dok_array, dok_matrix, coo_matrix, isspmatrix_dok
+    >>> isspmatrix_dok(dok_matrix([[5]]))
+    True
+    >>> isspmatrix_dok(dok_array([[5]]))
+    False
+    >>> isspmatrix_dok(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, dok_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class dok_array(_dok_base, sparray):
+    """
+    Dictionary Of Keys based sparse array.
+
+    This is an efficient structure for constructing sparse
+    arrays incrementally.
+
+    This can be instantiated in several ways:
+        dok_array(D)
+            where D is a 2-D ndarray
+
+        dok_array(S)
+            with another sparse array or matrix S (equivalent to S.todok())
+
+        dok_array((M,N), [dtype])
+            create the array with initial shape (M,N)
+            dtype is optional, defaulting to dtype='d'
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+        Number of nonzero elements
+    size
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    - Allows for efficient O(1) access of individual elements.
+    - Duplicates are not allowed.
+    - Can be efficiently converted to a coo_array once constructed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import dok_array
+    >>> S = dok_array((5, 5), dtype=np.float32)
+    >>> for i in range(5):
+    ...     for j in range(5):
+    ...         S[i, j] = i + j    # Update element
+
+    """
+
+
+class dok_matrix(spmatrix, _dok_base):
+    """
+    Dictionary Of Keys based sparse matrix.
+
+    This is an efficient structure for constructing sparse
+    matrices incrementally.
+
+    This can be instantiated in several ways:
+        dok_matrix(D)
+            where D is a 2-D ndarray
+
+        dok_matrix(S)
+            with another sparse array or matrix S (equivalent to S.todok())
+
+        dok_matrix((M,N), [dtype])
+            create the matrix with initial shape (M,N)
+            dtype is optional, defaulting to dtype='d'
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+        Number of nonzero elements
+    size
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    - Allows for efficient O(1) access of individual elements.
+    - Duplicates are not allowed.
+    - Can be efficiently converted to a coo_matrix once constructed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import dok_matrix
+    >>> S = dok_matrix((5, 5), dtype=np.float32)
+    >>> for i in range(5):
+    ...     for j in range(5):
+    ...         S[i, j] = i + j    # Update element
+
+    """
+
+    def set_shape(self, shape):
+        new_matrix = self.reshape(shape, copy=False).asformat(self.format)
+        self.__dict__ = new_matrix.__dict__
+
+    def get_shape(self):
+        """Get shape of a sparse matrix."""
+        return self._shape
+
+    shape = property(fget=get_shape, fset=set_shape)
+
+    def __reversed__(self):
+        return self._dict.__reversed__()
+
+    def __or__(self, other):
+        if isinstance(other, _dok_base):
+            return self._dict | other._dict
+        return self._dict | other
+
+    def __ror__(self, other):
+        if isinstance(other, _dok_base):
+            return self._dict | other._dict
+        return self._dict | other
+
+    def __ior__(self, other):
+        if isinstance(other, _dok_base):
+            self._dict |= other._dict
+        else:
+            self._dict |= other
+        return self
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_lil.py b/venv/lib/python3.10/site-packages/scipy/sparse/_lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..479472445cd8bdc36374b3d8bc18e6f9df123306
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_lil.py
@@ -0,0 +1,632 @@
+"""List of Lists sparse matrix class
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['lil_array', 'lil_matrix', 'isspmatrix_lil']
+
+from bisect import bisect_left
+
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray, issparse
+from ._index import IndexMixin, INT_TYPES, _broadcast_arrays
+from ._sputils import (getdtype, isshape, isscalarlike, upcast_scalar,
+                       check_shape, check_reshape_kwargs)
+from . import _csparsetools
+
+
+class _lil_base(_spbase, IndexMixin):
+    _format = 'lil'
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _spbase.__init__(self, arg1, maxprint=maxprint)
+        self.dtype = getdtype(dtype, arg1, default=float)
+
+        # First get the shape
+        if issparse(arg1):
+            if arg1.format == "lil" and copy:
+                A = arg1.copy()
+            else:
+                A = arg1.tolil()
+
+            if dtype is not None:
+                newdtype = getdtype(dtype)
+                A = A.astype(newdtype, copy=False)
+
+            self._shape = check_shape(A.shape)
+            self.dtype = A.dtype
+            self.rows = A.rows
+            self.data = A.data
+        elif isinstance(arg1,tuple):
+            if isshape(arg1):
+                if shape is not None:
+                    raise ValueError('invalid use of shape parameter')
+                M, N = arg1
+                self._shape = check_shape((M, N))
+                self.rows = np.empty((M,), dtype=object)
+                self.data = np.empty((M,), dtype=object)
+                for i in range(M):
+                    self.rows[i] = []
+                    self.data[i] = []
+            else:
+                raise TypeError('unrecognized lil_array constructor usage')
+        else:
+            # assume A is dense
+            try:
+                A = self._ascontainer(arg1)
+            except TypeError as e:
+                raise TypeError('unsupported matrix type') from e
+            if isinstance(self, sparray) and A.ndim != 2:
+                raise ValueError(f"LIL arrays don't support {A.ndim}D input. Use 2D")
+            A = self._csr_container(A, dtype=dtype).tolil()
+
+            self._shape = check_shape(A.shape)
+            self.dtype = getdtype(A.dtype)
+            self.rows = A.rows
+            self.data = A.data
+
+    def __iadd__(self,other):
+        self[:,:] = self + other
+        return self
+
+    def __isub__(self,other):
+        self[:,:] = self - other
+        return self
+
+    def __imul__(self,other):
+        if isscalarlike(other):
+            self[:,:] = self * other
+            return self
+        else:
+            return NotImplemented
+
+    def __itruediv__(self,other):
+        if isscalarlike(other):
+            self[:,:] = self / other
+            return self
+        else:
+            return NotImplemented
+
+    # Whenever the dimensions change, empty lists should be created for each
+    # row
+
+    def _getnnz(self, axis=None):
+        if axis is None:
+            return sum([len(rowvals) for rowvals in self.data])
+        if axis < 0:
+            axis += 2
+        if axis == 0:
+            out = np.zeros(self.shape[1], dtype=np.intp)
+            for row in self.rows:
+                out[row] += 1
+            return out
+        elif axis == 1:
+            return np.array([len(rowvals) for rowvals in self.data], dtype=np.intp)
+        else:
+            raise ValueError('axis out of bounds')
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        if axis is None:
+            return sum(np.count_nonzero(rowvals) for rowvals in self.data)
+
+        if axis < 0:
+            axis += 2
+        if axis == 0:
+            out = np.zeros(self.shape[1], dtype=np.intp)
+            for row, data in zip(self.rows, self.data):
+                mask = [c for c, d in zip(row, data) if d != 0]
+                out[mask] += 1
+            return out
+        elif axis == 1:
+            return np.array(
+                [np.count_nonzero(rowvals) for rowvals in self.data], dtype=np.intp,
+            )
+        else:
+            raise ValueError('axis out of bounds')
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def getrowview(self, i):
+        """Returns a view of the 'i'th row (without copying).
+        """
+        new = self._lil_container((1, self.shape[1]), dtype=self.dtype)
+        new.rows[0] = self.rows[i]
+        new.data[0] = self.data[i]
+        return new
+
+    def getrow(self, i):
+        """Returns a copy of the 'i'th row.
+        """
+        M, N = self.shape
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError('row index out of bounds')
+        new = self._lil_container((1, N), dtype=self.dtype)
+        new.rows[0] = self.rows[i][:]
+        new.data[0] = self.data[i][:]
+        return new
+
+    def __getitem__(self, key):
+        # Fast path for simple (int, int) indexing.
+        if (isinstance(key, tuple) and len(key) == 2 and
+                isinstance(key[0], INT_TYPES) and
+                isinstance(key[1], INT_TYPES)):
+            # lil_get1 handles validation for us.
+            return self._get_intXint(*key)
+        # Everything else takes the normal path.
+        return IndexMixin.__getitem__(self, key)
+
+    def _asindices(self, idx, N):
+        # LIL routines handle bounds-checking for us, so don't do it here.
+        try:
+            x = np.asarray(idx)
+        except (ValueError, TypeError, MemoryError) as e:
+            raise IndexError('invalid index') from e
+        if x.ndim not in (1, 2):
+            raise IndexError('Index dimension must be <= 2')
+        return x
+
+    def _get_intXint(self, row, col):
+        v = _csparsetools.lil_get1(self.shape[0], self.shape[1], self.rows,
+                                   self.data, row, col)
+        return self.dtype.type(v)
+
+    def _get_sliceXint(self, row, col):
+        row = range(*row.indices(self.shape[0]))
+        return self._get_row_ranges(row, slice(col, col+1))
+
+    def _get_arrayXint(self, row, col):
+        res = self._get_row_ranges(row.ravel(), slice(col, col+1))
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_intXslice(self, row, col):
+        return self._get_row_ranges((row,), col)
+
+    def _get_sliceXslice(self, row, col):
+        row = range(*row.indices(self.shape[0]))
+        return self._get_row_ranges(row, col)
+
+    def _get_arrayXslice(self, row, col):
+        return self._get_row_ranges(row, col)
+
+    def _get_intXarray(self, row, col):
+        row = np.array(row, dtype=col.dtype, ndmin=1)
+        return self._get_columnXarray(row, col)
+
+    def _get_sliceXarray(self, row, col):
+        row = np.arange(*row.indices(self.shape[0]))
+        return self._get_columnXarray(row, col)
+
+    def _get_columnXarray(self, row, col):
+        # outer indexing
+        row, col = _broadcast_arrays(row[:,None], col)
+        return self._get_arrayXarray(row, col)
+
+    def _get_arrayXarray(self, row, col):
+        # inner indexing
+        i, j = map(np.atleast_2d, _prepare_index_for_memoryview(row, col))
+        new = self._lil_container(i.shape, dtype=self.dtype)
+        _csparsetools.lil_fancy_get(self.shape[0], self.shape[1],
+                                    self.rows, self.data,
+                                    new.rows, new.data,
+                                    i, j)
+        return new
+
+    def _get_row_ranges(self, rows, col_slice):
+        """
+        Fast path for indexing in the case where column index is slice.
+
+        This gains performance improvement over brute force by more
+        efficient skipping of zeros, by accessing the elements
+        column-wise in order.
+
+        Parameters
+        ----------
+        rows : sequence or range
+            Rows indexed. If range, must be within valid bounds.
+        col_slice : slice
+            Columns indexed
+
+        """
+        j_start, j_stop, j_stride = col_slice.indices(self.shape[1])
+        col_range = range(j_start, j_stop, j_stride)
+        nj = len(col_range)
+        new = self._lil_container((len(rows), nj), dtype=self.dtype)
+
+        _csparsetools.lil_get_row_ranges(self.shape[0], self.shape[1],
+                                         self.rows, self.data,
+                                         new.rows, new.data,
+                                         rows,
+                                         j_start, j_stop, j_stride, nj)
+
+        return new
+
+    def _set_intXint(self, row, col, x):
+        _csparsetools.lil_insert(self.shape[0], self.shape[1], self.rows,
+                                 self.data, row, col, x)
+
+    def _set_arrayXarray(self, row, col, x):
+        i, j, x = map(np.atleast_2d, _prepare_index_for_memoryview(row, col, x))
+        _csparsetools.lil_fancy_set(self.shape[0], self.shape[1],
+                                    self.rows, self.data,
+                                    i, j, x)
+
+    def _set_arrayXarray_sparse(self, row, col, x):
+        # Fall back to densifying x
+        x = np.asarray(x.toarray(), dtype=self.dtype)
+        x, _ = _broadcast_arrays(x, row)
+        self._set_arrayXarray(row, col, x)
+
+    def __setitem__(self, key, x):
+        if isinstance(key, tuple) and len(key) == 2:
+            row, col = key
+            # Fast path for simple (int, int) indexing.
+            if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES):
+                x = self.dtype.type(x)
+                if x.size > 1:
+                    raise ValueError("Trying to assign a sequence to an item")
+                return self._set_intXint(row, col, x)
+            # Fast path for full-matrix sparse assignment.
+            if (isinstance(row, slice) and isinstance(col, slice) and
+                    row == slice(None) and col == slice(None) and
+                    issparse(x) and x.shape == self.shape):
+                x = self._lil_container(x, dtype=self.dtype)
+                self.rows = x.rows
+                self.data = x.data
+                return
+        # Everything else takes the normal path.
+        IndexMixin.__setitem__(self, key, x)
+
+    def _mul_scalar(self, other):
+        if other == 0:
+            # Multiply by zero: return the zero matrix
+            new = self._lil_container(self.shape, dtype=self.dtype)
+        else:
+            res_dtype = upcast_scalar(self.dtype, other)
+
+            new = self.copy()
+            new = new.astype(res_dtype)
+            # Multiply this scalar by every element.
+            for j, rowvals in enumerate(new.data):
+                new.data[j] = [val*other for val in rowvals]
+        return new
+
+    def __truediv__(self, other):           # self / other
+        if isscalarlike(other):
+            new = self.copy()
+            new.dtype = np.result_type(self, other)
+            # Divide every element by this scalar
+            for j, rowvals in enumerate(new.data):
+                new.data[j] = [val/other for val in rowvals]
+            return new
+        else:
+            return self.tocsr() / other
+
+    def copy(self):
+        M, N = self.shape
+        new = self._lil_container(self.shape, dtype=self.dtype)
+        # This is ~14x faster than calling deepcopy() on rows and data.
+        _csparsetools.lil_get_row_ranges(M, N, self.rows, self.data,
+                                         new.rows, new.data, range(M),
+                                         0, N, 1, N)
+        return new
+
+    copy.__doc__ = _spbase.copy.__doc__
+
+    def reshape(self, *args, **kwargs):
+        shape = check_shape(args, self.shape)
+        order, copy = check_reshape_kwargs(kwargs)
+
+        # Return early if reshape is not required
+        if shape == self.shape:
+            if copy:
+                return self.copy()
+            else:
+                return self
+
+        new = self._lil_container(shape, dtype=self.dtype)
+
+        if order == 'C':
+            ncols = self.shape[1]
+            for i, row in enumerate(self.rows):
+                for col, j in enumerate(row):
+                    new_r, new_c = np.unravel_index(i * ncols + j, shape)
+                    new[new_r, new_c] = self[i, j]
+        elif order == 'F':
+            nrows = self.shape[0]
+            for i, row in enumerate(self.rows):
+                for col, j in enumerate(row):
+                    new_r, new_c = np.unravel_index(i + j * nrows, shape, order)
+                    new[new_r, new_c] = self[i, j]
+        else:
+            raise ValueError("'order' must be 'C' or 'F'")
+
+        return new
+
+    reshape.__doc__ = _spbase.reshape.__doc__
+
+    def resize(self, *shape):
+        shape = check_shape(shape)
+        new_M, new_N = shape
+        M, N = self.shape
+
+        if new_M < M:
+            self.rows = self.rows[:new_M]
+            self.data = self.data[:new_M]
+        elif new_M > M:
+            self.rows = np.resize(self.rows, new_M)
+            self.data = np.resize(self.data, new_M)
+            for i in range(M, new_M):
+                self.rows[i] = []
+                self.data[i] = []
+
+        if new_N < N:
+            for row, data in zip(self.rows, self.data):
+                trunc = bisect_left(row, new_N)
+                del row[trunc:]
+                del data[trunc:]
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    def toarray(self, order=None, out=None):
+        d = self._process_toarray_args(order, out)
+        for i, row in enumerate(self.rows):
+            for pos, j in enumerate(row):
+                d[i, j] = self.data[i][pos]
+        return d
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    def transpose(self, axes=None, copy=False):
+        return self.tocsr(copy=copy).transpose(axes=axes, copy=False).tolil(copy=False)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def tolil(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tolil.__doc__ = _spbase.tolil.__doc__
+
+    def tocsr(self, copy=False):
+        M, N = self.shape
+        if M == 0 or N == 0:
+            return self._csr_container((M, N), dtype=self.dtype)
+
+        # construct indptr array
+        if M*N <= np.iinfo(np.int32).max:
+            # fast path: it is known that 64-bit indexing will not be needed.
+            idx_dtype = np.int32
+            indptr = np.empty(M + 1, dtype=idx_dtype)
+            indptr[0] = 0
+            _csparsetools.lil_get_lengths(self.rows, indptr[1:])
+            np.cumsum(indptr, out=indptr)
+            nnz = indptr[-1]
+        else:
+            idx_dtype = self._get_index_dtype(maxval=N)
+            lengths = np.empty(M, dtype=idx_dtype)
+            _csparsetools.lil_get_lengths(self.rows, lengths)
+            nnz = lengths.sum(dtype=np.int64)
+            idx_dtype = self._get_index_dtype(maxval=max(N, nnz))
+            indptr = np.empty(M + 1, dtype=idx_dtype)
+            indptr[0] = 0
+            np.cumsum(lengths, dtype=idx_dtype, out=indptr[1:])
+
+        indices = np.empty(nnz, dtype=idx_dtype)
+        data = np.empty(nnz, dtype=self.dtype)
+        _csparsetools.lil_flatten_to_array(self.rows, indices)
+        _csparsetools.lil_flatten_to_array(self.data, data)
+
+        # init csr matrix
+        return self._csr_container((data, indices, indptr), shape=self.shape)
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+
+def _prepare_index_for_memoryview(i, j, x=None):
+    """
+    Convert index and data arrays to form suitable for passing to the
+    Cython fancy getset routines.
+
+    The conversions are necessary since to (i) ensure the integer
+    index arrays are in one of the accepted types, and (ii) to ensure
+    the arrays are writable so that Cython memoryview support doesn't
+    choke on them.
+
+    Parameters
+    ----------
+    i, j
+        Index arrays
+    x : optional
+        Data arrays
+
+    Returns
+    -------
+    i, j, x
+        Re-formatted arrays (x is omitted, if input was None)
+
+    """
+    if i.dtype > j.dtype:
+        j = j.astype(i.dtype)
+    elif i.dtype < j.dtype:
+        i = i.astype(j.dtype)
+
+    if not i.flags.writeable or i.dtype not in (np.int32, np.int64):
+        i = i.astype(np.intp)
+    if not j.flags.writeable or j.dtype not in (np.int32, np.int64):
+        j = j.astype(np.intp)
+
+    if x is not None:
+        if not x.flags.writeable:
+            x = x.copy()
+        return i, j, x
+    else:
+        return i, j
+
+
+def isspmatrix_lil(x):
+    """Is `x` of lil_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a lil matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a lil matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import lil_array, lil_matrix, coo_matrix, isspmatrix_lil
+    >>> isspmatrix_lil(lil_matrix([[5]]))
+    True
+    >>> isspmatrix_lil(lil_array([[5]]))
+    False
+    >>> isspmatrix_lil(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, lil_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class lil_array(_lil_base, sparray):
+    """
+    Row-based LIst of Lists sparse array.
+
+    This is a structure for constructing sparse arrays incrementally.
+    Note that inserting a single item can take linear time in the worst case;
+    to construct the array efficiently, make sure the items are pre-sorted by
+    index, per row.
+
+    This can be instantiated in several ways:
+        lil_array(D)
+            where D is a 2-D ndarray
+
+        lil_array(S)
+            with another sparse array or matrix S (equivalent to S.tolil())
+
+        lil_array((M, N), [dtype])
+            to construct an empty array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        LIL format data array of the array
+    rows
+        LIL format row index array of the array
+    T
+
+    Notes
+    -----
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the LIL format
+        - supports flexible slicing
+        - changes to the array sparsity structure are efficient
+
+    Disadvantages of the LIL format
+        - arithmetic operations LIL + LIL are slow (consider CSR or CSC)
+        - slow column slicing (consider CSC)
+        - slow matrix vector products (consider CSR or CSC)
+
+    Intended Usage
+        - LIL is a convenient format for constructing sparse arrays
+        - once an array has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - consider using the COO format when constructing large arrays
+
+    Data Structure
+        - An array (``self.rows``) of rows, each of which is a sorted
+          list of column indices of non-zero elements.
+        - The corresponding nonzero values are stored in similar
+          fashion in ``self.data``.
+
+    """
+
+
+class lil_matrix(spmatrix, _lil_base):
+    """
+    Row-based LIst of Lists sparse matrix.
+
+    This is a structure for constructing sparse matrices incrementally.
+    Note that inserting a single item can take linear time in the worst case;
+    to construct the matrix efficiently, make sure the items are pre-sorted by
+    index, per row.
+
+    This can be instantiated in several ways:
+        lil_matrix(D)
+            where D is a 2-D ndarray
+
+        lil_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tolil())
+
+        lil_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        LIL format data array of the matrix
+    rows
+        LIL format row index array of the matrix
+    T
+
+    Notes
+    -----
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the LIL format
+        - supports flexible slicing
+        - changes to the matrix sparsity structure are efficient
+
+    Disadvantages of the LIL format
+        - arithmetic operations LIL + LIL are slow (consider CSR or CSC)
+        - slow column slicing (consider CSC)
+        - slow matrix vector products (consider CSR or CSC)
+
+    Intended Usage
+        - LIL is a convenient format for constructing sparse matrices
+        - once a matrix has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - consider using the COO format when constructing large matrices
+
+    Data Structure
+        - An array (``self.rows``) of rows, each of which is a sorted
+          list of column indices of non-zero elements.
+        - The corresponding nonzero values are stored in similar
+          fashion in ``self.data``.
+
+    """
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py b/venv/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b7f533926fd415a379cb08420b4a65a14baeb43
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py
@@ -0,0 +1,167 @@
+import numpy as np
+import scipy as sp
+
+__all__ = ['save_npz', 'load_npz']
+
+
+# Make loading safe vs. malicious input
+PICKLE_KWARGS = dict(allow_pickle=False)
+
+
+def save_npz(file, matrix, compressed=True):
+    """ Save a sparse matrix or array to a file using ``.npz`` format.
+
+    Parameters
+    ----------
+    file : str or file-like object
+        Either the file name (string) or an open file (file-like object)
+        where the data will be saved. If file is a string, the ``.npz``
+        extension will be appended to the file name if it is not already
+        there.
+    matrix: spmatrix or sparray
+        The sparse matrix or array to save.
+        Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``.
+    compressed : bool, optional
+        Allow compressing the file. Default: True
+
+    See Also
+    --------
+    scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format.
+    numpy.savez: Save several arrays into a ``.npz`` archive.
+    numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive.
+
+    Examples
+    --------
+    Store sparse matrix to disk, and load it again:
+
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
+    >>> sparse_matrix
+    
+    >>> sparse_matrix.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+
+    >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
+    >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
+
+    >>> sparse_matrix
+    
+    >>> sparse_matrix.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+    """
+    arrays_dict = {}
+    if matrix.format in ('csc', 'csr', 'bsr'):
+        arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
+    elif matrix.format == 'dia':
+        arrays_dict.update(offsets=matrix.offsets)
+    elif matrix.format == 'coo':
+        arrays_dict.update(row=matrix.row, col=matrix.col)
+    else:
+        msg = f'Save is not implemented for sparse matrix of format {matrix.format}.'
+        raise NotImplementedError(msg)
+    arrays_dict.update(
+        format=matrix.format.encode('ascii'),
+        shape=matrix.shape,
+        data=matrix.data
+    )
+    if isinstance(matrix, sp.sparse.sparray):
+        arrays_dict.update(_is_array=True)
+    if compressed:
+        np.savez_compressed(file, **arrays_dict)
+    else:
+        np.savez(file, **arrays_dict)
+
+
+def load_npz(file):
+    """ Load a sparse array/matrix from a file using ``.npz`` format.
+
+    Parameters
+    ----------
+    file : str or file-like object
+        Either the file name (string) or an open file (file-like object)
+        where the data will be loaded.
+
+    Returns
+    -------
+    result : csc_array, csr_array, bsr_array, dia_array or coo_array
+        A sparse array/matrix containing the loaded data.
+
+    Raises
+    ------
+    OSError
+        If the input file does not exist or cannot be read.
+
+    See Also
+    --------
+    scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format.
+    numpy.load: Load several arrays from a ``.npz`` archive.
+
+    Examples
+    --------
+    Store sparse array/matrix to disk, and load it again:
+
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]])
+    >>> sparse_array
+    
+    >>> sparse_array.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+
+    >>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array)
+    >>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz')
+
+    >>> sparse_array
+    
+    >>> sparse_array.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+
+    In this example we force the result to be csr_array from csr_matrix
+    >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
+    >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
+    >>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
+    >>> sparse_array = sp.sparse.csr_array(tmp)
+    """
+    with np.load(file, **PICKLE_KWARGS) as loaded:
+        sparse_format = loaded.get('format')
+        if sparse_format is None:
+            raise ValueError(f'The file {file} does not contain '
+                             f'a sparse array or matrix.')
+        sparse_format = sparse_format.item()
+
+        if not isinstance(sparse_format, str):
+            # Play safe with Python 2 vs 3 backward compatibility;
+            # files saved with SciPy < 1.0.0 may contain unicode or bytes.
+            sparse_format = sparse_format.decode('ascii')
+
+        if loaded.get('_is_array'):
+            sparse_type = sparse_format + '_array'
+        else:
+            sparse_type = sparse_format + '_matrix'
+
+        try:
+            cls = getattr(sp.sparse, f'{sparse_type}')
+        except AttributeError as e:
+            raise ValueError(f'Unknown format "{sparse_type}"') from e
+
+        if sparse_format in ('csc', 'csr', 'bsr'):
+            return cls((loaded['data'], loaded['indices'], loaded['indptr']),
+                       shape=loaded['shape'])
+        elif sparse_format == 'dia':
+            return cls((loaded['data'], loaded['offsets']),
+                       shape=loaded['shape'])
+        elif sparse_format == 'coo':
+            return cls((loaded['data'], (loaded['row'], loaded['col'])),
+                       shape=loaded['shape'])
+        else:
+            raise NotImplementedError(f'Load is not implemented for '
+                                      f'sparse matrix of format {sparse_format}.')
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py b/venv/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e9b0abcede6387e74538baf839a303c6cc1b6be
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py
@@ -0,0 +1,76 @@
+""" Functions that operate on sparse matrices
+"""
+
+__all__ = ['count_blocks','estimate_blocksize']
+
+from ._base import issparse
+from ._csr import csr_array
+from ._sparsetools import csr_count_blocks
+
+
+def estimate_blocksize(A,efficiency=0.7):
+    """Attempt to determine the blocksize of a sparse matrix
+
+    Returns a blocksize=(r,c) such that
+        - A.nnz / A.tobsr( (r,c) ).nnz > efficiency
+    """
+    if not (issparse(A) and A.format in ("csc", "csr")):
+        A = csr_array(A)
+
+    if A.nnz == 0:
+        return (1,1)
+
+    if not 0 < efficiency < 1.0:
+        raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0')
+
+    high_efficiency = (1.0 + efficiency) / 2.0
+    nnz = float(A.nnz)
+    M,N = A.shape
+
+    if M % 2 == 0 and N % 2 == 0:
+        e22 = nnz / (4 * count_blocks(A,(2,2)))
+    else:
+        e22 = 0.0
+
+    if M % 3 == 0 and N % 3 == 0:
+        e33 = nnz / (9 * count_blocks(A,(3,3)))
+    else:
+        e33 = 0.0
+
+    if e22 > high_efficiency and e33 > high_efficiency:
+        e66 = nnz / (36 * count_blocks(A,(6,6)))
+        if e66 > efficiency:
+            return (6,6)
+        else:
+            return (3,3)
+    else:
+        if M % 4 == 0 and N % 4 == 0:
+            e44 = nnz / (16 * count_blocks(A,(4,4)))
+        else:
+            e44 = 0.0
+
+        if e44 > efficiency:
+            return (4,4)
+        elif e33 > efficiency:
+            return (3,3)
+        elif e22 > efficiency:
+            return (2,2)
+        else:
+            return (1,1)
+
+
+def count_blocks(A,blocksize):
+    """For a given blocksize=(r,c) count the number of occupied
+    blocks in a sparse matrix A
+    """
+    r,c = blocksize
+    if r < 1 or c < 1:
+        raise ValueError('r and c must be positive')
+
+    if issparse(A):
+        if A.format == "csr":
+            M,N = A.shape
+            return csr_count_blocks(M,N,r,c,A.indptr,A.indices)
+        elif A.format == "csc":
+            return count_blocks(A.T,(c,r))
+    return count_blocks(csr_array(A),blocksize)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/_sputils.py b/venv/lib/python3.10/site-packages/scipy/sparse/_sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fb5b5fc6c2e37d0c61dd3a3aa0aa382c7486a03
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/_sputils.py
@@ -0,0 +1,617 @@
+""" Utility functions for sparse matrix module
+"""
+
+import sys
+from typing import Any, Literal, Union
+import operator
+import numpy as np
+from math import prod
+import scipy.sparse as sp
+from scipy._lib._util import np_long, np_ulong
+
+
+__all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike',
+           'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype',
+           'broadcast_shapes']
+
+supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc,
+                    np.uintc, np_long, np_ulong, np.longlong, np.ulonglong,
+                    np.float32, np.float64, np.longdouble,
+                    np.complex64, np.complex128, np.clongdouble]
+
+_upcast_memo = {}
+
+
+def upcast(*args):
+    """Returns the nearest supported sparse dtype for the
+    combination of one or more types.
+
+    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype
+
+    Examples
+    --------
+    >>> from scipy.sparse._sputils import upcast
+    >>> upcast('int32')
+    
+    >>> upcast('bool')
+    
+    >>> upcast('int32','float32')
+    
+    >>> upcast('bool',complex,float)
+    
+
+    """
+
+    t = _upcast_memo.get(hash(args))
+    if t is not None:
+        return t
+
+    upcast = np.result_type(*args)
+
+    for t in supported_dtypes:
+        if np.can_cast(upcast, t):
+            _upcast_memo[hash(args)] = t
+            return t
+
+    raise TypeError(f'no supported conversion for types: {args!r}')
+
+
+def upcast_char(*args):
+    """Same as `upcast` but taking dtype.char as input (faster)."""
+    t = _upcast_memo.get(args)
+    if t is not None:
+        return t
+    t = upcast(*map(np.dtype, args))
+    _upcast_memo[args] = t
+    return t
+
+
+def upcast_scalar(dtype, scalar):
+    """Determine data type for binary operation between an array of
+    type `dtype` and a scalar.
+    """
+    return (np.array([0], dtype=dtype) * scalar).dtype
+
+
+def downcast_intp_index(arr):
+    """
+    Down-cast index array to np.intp dtype if it is of a larger dtype.
+
+    Raise an error if the array contains a value that is too large for
+    intp.
+    """
+    if arr.dtype.itemsize > np.dtype(np.intp).itemsize:
+        if arr.size == 0:
+            return arr.astype(np.intp)
+        maxval = arr.max()
+        minval = arr.min()
+        if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min:
+            raise ValueError("Cannot deal with arrays with indices larger "
+                             "than the machine maximum address size "
+                             "(e.g. 64-bit indices on 32-bit machine).")
+        return arr.astype(np.intp)
+    return arr
+
+
+def to_native(A):
+    """
+    Ensure that the data type of the NumPy array `A` has native byte order.
+
+    `A` must be a NumPy array.  If the data type of `A` does not have native
+    byte order, a copy of `A` with a native byte order is returned. Otherwise
+    `A` is returned.
+    """
+    dt = A.dtype
+    if dt.isnative:
+        # Don't call `asarray()` if A is already native, to avoid unnecessarily
+        # creating a view of the input array.
+        return A
+    return np.asarray(A, dtype=dt.newbyteorder('native'))
+
+
+def getdtype(dtype, a=None, default=None):
+    """Form a supported numpy dtype based on input arguments.
+
+    Returns a valid ``numpy.dtype`` from `dtype` if not None,
+    or else ``a.dtype`` if possible, or else the given `default`
+    if not None, or else raise a ``TypeError``.
+
+    The resulting ``dtype`` must be in ``supported_dtypes``:
+        bool_, int8, uint8, int16, uint16, int32, uint32,
+        int64, uint64, longlong, ulonglong, float32, float64,
+        longdouble, complex64, complex128, clongdouble
+    """
+    if dtype is None:
+        try:
+            newdtype = a.dtype
+        except AttributeError as e:
+            if default is not None:
+                newdtype = np.dtype(default)
+            else:
+                raise TypeError("could not interpret data type") from e
+    else:
+        newdtype = np.dtype(dtype)
+
+    if newdtype not in supported_dtypes:
+        supported_dtypes_fmt = ", ".join(t.__name__ for t in supported_dtypes)
+        raise ValueError(f"scipy.sparse does not support dtype {newdtype.name}. "
+                         f"The only supported types are: {supported_dtypes_fmt}.")
+    return newdtype
+
+
+def getdata(obj, dtype=None, copy=False) -> np.ndarray:
+    """
+    This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)`
+    that will generate a warning if the result is an object array.
+    """
+    data = np.array(obj, dtype=dtype, copy=copy)
+    # Defer to getdtype for checking that the dtype is OK.
+    # This is called for the validation only; we don't need the return value.
+    getdtype(data.dtype)
+    return data
+
+
+def safely_cast_index_arrays(A, idx_dtype=np.int32, msg=""):
+    """Safely cast sparse array indices to `idx_dtype`.
+
+    Check the shape of `A` to determine if it is safe to cast its index
+    arrays to dtype `idx_dtype`. If any dimension in shape is larger than
+    fits in the dtype, casting is unsafe so raise ``ValueError``.
+    If safe, cast the index arrays to `idx_dtype` and return the result
+    without changing the input `A`. The caller can assign results to `A`
+    attributes if desired or use the recast index arrays directly.
+
+    Unless downcasting is needed, the original index arrays are returned.
+    You can test e.g. ``A.indptr is new_indptr`` to see if downcasting occurred.
+
+    .. versionadded:: 1.15.0
+
+    Parameters
+    ----------
+    A : sparse array or matrix
+        The array for which index arrays should be downcast.
+    idx_dtype : dtype
+        Desired dtype. Should be an integer dtype (default: ``np.int32``).
+        Most of scipy.sparse uses either int64 or int32.
+    msg : string, optional
+        A string to be added to the end of the ValueError message
+        if the array shape is too big to fit in `idx_dtype`.
+        The error message is ``f" values too large for {msg}"``
+        It should indicate why the downcasting is needed, e.g. "SuperLU",
+        and defaults to f"dtype {idx_dtype}".
+
+    Returns
+    -------
+    idx_arrays : ndarray or tuple of ndarrays
+        Based on ``A.format``, index arrays are returned after casting to `idx_dtype`.
+        For CSC/CSR, returns ``(indices, indptr)``.
+        For COO, returns ``coords``.
+        For DIA, returns ``offsets``.
+        For BSR, returns ``(indices, indptr)``.
+
+    Raises
+    ------
+    ValueError
+        If the array has shape that would not fit in the new dtype, or if
+        the sparse format does not use index arrays.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import sparse
+    >>> data = [3]
+    >>> coords = (np.array([3]), np.array([1]))  # Note: int64 arrays
+    >>> A = sparse.coo_array((data, coords))
+    >>> A.coords[0].dtype
+    dtype('int64')
+
+    >>> # rescast after construction, raising exception if shape too big
+    >>> coords = sparse.safely_cast_index_arrays(A, np.int32)
+    >>> A.coords[0] is coords[0]  # False if casting is needed
+    False
+    >>> A.coords = coords  # set the index dtype of A
+    >>> A.coords[0].dtype
+    dtype('int32')
+    """
+    if not msg:
+        msg = f"dtype {idx_dtype}"
+    # check for safe downcasting
+    max_value = np.iinfo(idx_dtype).max
+
+    if A.format in ("csc", "csr"):
+        # indptr[-1] is max b/c indptr always sorted
+        if A.indptr[-1] > max_value:
+            raise ValueError(f"indptr values too large for {msg}")
+
+        # check shape vs dtype
+        if max(*A.shape) > max_value:
+            if (A.indices > max_value).any():
+                raise ValueError(f"indices values too large for {msg}")
+
+        indices = A.indices.astype(idx_dtype, copy=False)
+        indptr = A.indptr.astype(idx_dtype, copy=False)
+        return indices, indptr
+
+    elif A.format == "coo":
+        if max(*A.shape) > max_value:
+            if any((co > max_value).any() for co in A.coords):
+                raise ValueError(f"coords values too large for {msg}")
+        return tuple(co.astype(idx_dtype, copy=False) for co in A.coords)
+
+    elif A.format == "dia":
+        if max(*A.shape) > max_value:
+            if (A.offsets > max_value).any():
+                raise ValueError(f"offsets values too large for {msg}")
+        offsets = A.offsets.astype(idx_dtype, copy=False)
+        return offsets
+
+    elif A.format == 'bsr':
+        R, C = A.blocksize
+        if A.indptr[-1] * R > max_value:
+            raise ValueError("indptr values too large for {msg}")
+        if max(*A.shape) > max_value:
+            if (A.indices * C > max_value).any():
+                raise ValueError(f"indices values too large for {msg}")
+        indices = A.indices.astype(idx_dtype, copy=False)
+        indptr = A.indptr.astype(idx_dtype, copy=False)
+        return indices, indptr
+
+    else:
+        raise TypeError(f'Format {A.format} is not associated with index arrays. '
+                        'DOK and LIL have dict and list, not array.')
+
+
+def get_index_dtype(arrays=(), maxval=None, check_contents=False):
+    """
+    Based on input (integer) arrays `a`, determine a suitable index data
+    type that can hold the data in the arrays.
+
+    Parameters
+    ----------
+    arrays : tuple of array_like
+        Input arrays whose types/contents to check
+    maxval : float, optional
+        Maximum value needed
+    check_contents : bool, optional
+        Whether to check the values in the arrays and not just their types.
+        Default: False (check only the types)
+
+    Returns
+    -------
+    dtype : dtype
+        Suitable index data type (int32 or int64)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import sparse
+    >>> # select index dtype based on shape
+    >>> shape = (3, 3)
+    >>> idx_dtype = sparse.get_index_dtype(maxval=max(shape))
+    >>> data = [1.1, 3.0, 1.5]
+    >>> indices = np.array([0, 1, 0], dtype=idx_dtype)
+    >>> indptr = np.array([0, 2, 3, 3], dtype=idx_dtype)
+    >>> A = sparse.csr_array((data, indices, indptr), shape=shape)
+    >>> A.indptr.dtype
+    dtype('int32')
+
+    >>> # select based on larger of existing arrays and shape
+    >>> shape = (3, 3)
+    >>> idx_dtype = sparse.get_index_dtype(A.indptr, maxval=max(shape))
+    >>> idx_dtype
+    
+    """
+    # not using intc directly due to misinteractions with pythran
+    if np.intc().itemsize != 4:
+        return np.int64
+
+    int32min = np.int32(np.iinfo(np.int32).min)
+    int32max = np.int32(np.iinfo(np.int32).max)
+
+    if maxval is not None:
+        maxval = np.int64(maxval)
+        if maxval > int32max:
+            return np.int64
+
+    if isinstance(arrays, np.ndarray):
+        arrays = (arrays,)
+
+    for arr in arrays:
+        arr = np.asarray(arr)
+        if not np.can_cast(arr.dtype, np.int32):
+            if check_contents:
+                if arr.size == 0:
+                    # a bigger type not needed
+                    continue
+                elif np.issubdtype(arr.dtype, np.integer):
+                    maxval = arr.max()
+                    minval = arr.min()
+                    if minval >= int32min and maxval <= int32max:
+                        # a bigger type not needed
+                        continue
+            return np.int64
+    return np.int32
+
+
+def get_sum_dtype(dtype: np.dtype) -> np.dtype:
+    """Mimic numpy's casting for np.sum"""
+    if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
+        return np.uint
+    if np.can_cast(dtype, np.int_):
+        return np.int_
+    return dtype
+
+
+def isscalarlike(x) -> bool:
+    """Is x either a scalar, an array scalar, or a 0-dim array?"""
+    return np.isscalar(x) or (isdense(x) and x.ndim == 0)
+
+
+def isintlike(x) -> bool:
+    """Is x appropriate as an index into a sparse matrix? Returns True
+    if it can be cast safely to a machine int.
+    """
+    # Fast-path check to eliminate non-scalar values. operator.index would
+    # catch this case too, but the exception catching is slow.
+    if np.ndim(x) != 0:
+        return False
+    try:
+        operator.index(x)
+    except (TypeError, ValueError):
+        try:
+            loose_int = bool(int(x) == x)
+        except (TypeError, ValueError):
+            return False
+        if loose_int:
+            msg = "Inexact indices into sparse matrices are not allowed"
+            raise ValueError(msg)
+        return loose_int
+    return True
+
+
+def isshape(x, nonneg=False, *, allow_nd=(2,)) -> bool:
+    """Is x a valid tuple of dimensions?
+
+    If nonneg, also checks that the dimensions are non-negative.
+    Shapes of length in the tuple allow_nd are allowed.
+    """
+    ndim = len(x)
+    if ndim not in allow_nd:
+        return False
+
+    for d in x:
+        if not isintlike(d):
+            return False
+        if nonneg and d < 0:
+            return False
+    return True
+
+
+def issequence(t) -> bool:
+    return ((isinstance(t, list | tuple) and
+            (len(t) == 0 or np.isscalar(t[0]))) or
+            (isinstance(t, np.ndarray) and (t.ndim == 1)))
+
+
+def ismatrix(t) -> bool:
+    return ((isinstance(t, list | tuple) and
+             len(t) > 0 and issequence(t[0])) or
+            (isinstance(t, np.ndarray) and t.ndim == 2))
+
+
+def isdense(x) -> bool:
+    return isinstance(x, np.ndarray)
+
+
+def validateaxis(axis) -> None:
+    if axis is None:
+        return
+    axis_type = type(axis)
+
+    # In NumPy, you can pass in tuples for 'axis', but they are
+    # not very useful for sparse matrices given their limited
+    # dimensions, so let's make it explicit that they are not
+    # allowed to be passed in
+    if isinstance(axis, tuple):
+        raise TypeError("Tuples are not accepted for the 'axis' parameter. "
+                        "Please pass in one of the following: "
+                        "{-2, -1, 0, 1, None}.")
+
+    # If not a tuple, check that the provided axis is actually
+    # an integer and raise a TypeError similar to NumPy's
+    if not np.issubdtype(np.dtype(axis_type), np.integer):
+        raise TypeError(f"axis must be an integer, not {axis_type.__name__}")
+
+    if not (-2 <= axis <= 1):
+        raise ValueError("axis out of range")
+
+
+def check_shape(args, current_shape=None, *, allow_nd=(2,)) -> tuple[int, ...]:
+    """Imitate numpy.matrix handling of shape arguments
+
+    Parameters
+    ----------
+    args : array_like
+        Data structures providing information about the shape of the sparse array.
+    current_shape : tuple, optional
+        The current shape of the sparse array or matrix.
+        If None (default), the current shape will be inferred from args.
+    allow_nd : tuple of ints, optional default: (2,)
+        If shape does not have a length in the tuple allow_nd an error is raised.
+
+    Returns
+    -------
+    new_shape: tuple
+        The new shape after validation.
+    """
+    if len(args) == 0:
+        raise TypeError("function missing 1 required positional argument: 'shape'")
+    if len(args) == 1:
+        try:
+            shape_iter = iter(args[0])
+        except TypeError:
+            new_shape = (operator.index(args[0]), )
+        else:
+            new_shape = tuple(operator.index(arg) for arg in shape_iter)
+    else:
+        new_shape = tuple(operator.index(arg) for arg in args)
+
+    if current_shape is None:
+        if len(new_shape) not in allow_nd:
+            raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}')
+        if any(d < 0 for d in new_shape):
+            raise ValueError("'shape' elements cannot be negative")
+    else:
+        # Check the current size only if needed
+        current_size = prod(current_shape)
+
+        # Check for negatives
+        negative_indexes = [i for i, x in enumerate(new_shape) if x < 0]
+        if not negative_indexes:
+            new_size = prod(new_shape)
+            if new_size != current_size:
+                raise ValueError(f'cannot reshape array of size {current_size}'
+                                 f' into shape {new_shape}')
+        elif len(negative_indexes) == 1:
+            skip = negative_indexes[0]
+            specified = prod(new_shape[:skip] + new_shape[skip+1:])
+            unspecified, remainder = divmod(current_size, specified)
+            if remainder != 0:
+                err_shape = tuple('newshape' if x < 0 else x for x in new_shape)
+                raise ValueError(f'cannot reshape array of size {current_size}'
+                                 f' into shape {err_shape}')
+            new_shape = new_shape[:skip] + (unspecified,) + new_shape[skip+1:]
+        else:
+            raise ValueError('can only specify one unknown dimension')
+
+    if len(new_shape) not in allow_nd:
+        raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}')
+
+    return new_shape
+
+
+def broadcast_shapes(*shapes):
+    """Check if shapes can be broadcast and return resulting shape
+
+    This is similar to the NumPy ``broadcast_shapes`` function but
+    does not check memory consequences of the resulting dense matrix.
+
+    Parameters
+    ----------
+    *shapes : tuple of shape tuples
+        The tuple of shapes to be considered for broadcasting.
+        Shapes should be tuples of non-negative integers.
+
+    Returns
+    -------
+    new_shape : tuple of integers
+        The shape that results from broadcasting th input shapes.
+    """
+    if not shapes:
+        return ()
+    shapes = [shp if isinstance(shp, (tuple, list)) else (shp,) for shp in shapes]
+    big_shp = max(shapes, key=len)
+    out = list(big_shp)
+    for shp in shapes:
+        if shp is big_shp:
+            continue
+        for i, x in enumerate(shp, start=-len(shp)):
+            if x != 1 and x != out[i]:
+                if out[i] != 1:
+                    raise ValueError("shapes cannot be broadcast to a single shape.")
+                out[i] = x
+    return (*out,)
+
+
+def check_reshape_kwargs(kwargs):
+    """Unpack keyword arguments for reshape function.
+
+    This is useful because keyword arguments after star arguments are not
+    allowed in Python 2, but star keyword arguments are. This function unpacks
+    'order' and 'copy' from the star keyword arguments (with defaults) and
+    throws an error for any remaining.
+    """
+
+    order = kwargs.pop('order', 'C')
+    copy = kwargs.pop('copy', False)
+    if kwargs:  # Some unused kwargs remain
+        raise TypeError("reshape() got unexpected keywords arguments: "
+                        f"{', '.join(kwargs.keys())}")
+    return order, copy
+
+
+def is_pydata_spmatrix(m) -> bool:
+    """
+    Check whether object is pydata/sparse matrix, avoiding importing the module.
+    """
+    base_cls = getattr(sys.modules.get('sparse'), 'SparseArray', None)
+    return base_cls is not None and isinstance(m, base_cls)
+
+
+def convert_pydata_sparse_to_scipy(
+    arg: Any,
+    target_format: None | Literal["csc", "csr"] = None,
+    accept_fv: Any = None,
+) -> Union[Any, "sp.spmatrix"]:
+    """
+    Convert a pydata/sparse array to scipy sparse matrix,
+    pass through anything else.
+    """
+    if is_pydata_spmatrix(arg):
+        # The `accept_fv` keyword is new in PyData Sparse 0.15.4 (May 2024),
+        # remove the `except` once the minimum supported version is >=0.15.4
+        try:
+            arg = arg.to_scipy_sparse(accept_fv=accept_fv)
+        except TypeError:
+            arg = arg.to_scipy_sparse()
+        if target_format is not None:
+            arg = arg.asformat(target_format)
+        elif arg.format not in ("csc", "csr"):
+            arg = arg.tocsc()
+    return arg
+
+
+###############################################################################
+# Wrappers for NumPy types that are deprecated
+
+# Numpy versions of these functions raise deprecation warnings, the
+# ones below do not.
+
+def matrix(*args, **kwargs):
+    return np.array(*args, **kwargs).view(np.matrix)
+
+
+def asmatrix(data, dtype=None):
+    if isinstance(data, np.matrix) and (dtype is None or data.dtype == dtype):
+        return data
+    return np.asarray(data, dtype=dtype).view(np.matrix)
+
+###############################################################################
+
+
+def _todata(s) -> np.ndarray:
+    """Access nonzero values, possibly after summing duplicates.
+
+    Parameters
+    ----------
+    s : sparse array
+        Input sparse array.
+
+    Returns
+    -------
+    data: ndarray
+      Nonzero values of the array, with shape (s.nnz,)
+
+    """
+    if isinstance(s, sp._data._data_matrix):
+        return s._deduped_data()
+
+    if isinstance(s, sp.dok_array):
+        return np.fromiter(s.values(), dtype=s.dtype, count=s.nnz)
+
+    if isinstance(s, sp.lil_array):
+        data = np.empty(s.nnz, dtype=s.dtype)
+        sp._csparsetools.lil_flatten_to_array(s.data, data)
+        return data
+
+    return s.tocoo()._deduped_data()
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/bsr.py b/venv/lib/python3.10/site-packages/scipy/sparse/bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..c686301a78fc3e2221600eb06035a5cb12898cdb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/bsr.py
@@ -0,0 +1,36 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'bsr_matmat',
+    'bsr_matrix',
+    'bsr_matvec',
+    'bsr_matvecs',
+    'bsr_sort_indices',
+    'bsr_tocsr',
+    'bsr_transpose',
+    'check_shape',
+    'csr_matmat_maxnnz',
+    'getdata',
+    'getdtype',
+    'isshape',
+    'isspmatrix_bsr',
+    'spmatrix',
+    'to_native',
+    'upcast',
+    'warn',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="bsr",
+                                   private_modules=["_bsr"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/coo.py b/venv/lib/python3.10/site-packages/scipy/sparse/coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..bda2da3d09a676ab79739331a21ba26102bb90ae
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/coo.py
@@ -0,0 +1,37 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'SparseEfficiencyWarning',
+    'check_reshape_kwargs',
+    'check_shape',
+    'coo_matrix',
+    'coo_matvec',
+    'coo_tocsr',
+    'coo_todense',
+    'downcast_intp_index',
+    'getdata',
+    'getdtype',
+    'isshape',
+    'isspmatrix_coo',
+    'operator',
+    'spmatrix',
+    'to_native',
+    'upcast',
+    'upcast_char',
+    'warn',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="coo",
+                                   private_modules=["_coo"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..111fde875b01dced2aa949eb33cedc617b37482a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..325d0d169388e68ad66bfeac0a2521971c4dd807
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py
@@ -0,0 +1,119 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_array_almost_equal
+from scipy.sparse import csgraph, csr_array
+
+
+def test_weak_connections():
+    Xde = np.array([[0, 1, 0],
+                    [0, 0, 0],
+                    [0, 0, 0]])
+
+    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)
+
+    for X in Xsp, Xde:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='weak')
+
+        assert_equal(n_components, 2)
+        assert_array_almost_equal(labels, [0, 0, 1])
+
+
+def test_strong_connections():
+    X1de = np.array([[0, 1, 0],
+                     [0, 0, 0],
+                     [0, 0, 0]])
+    X2de = X1de + X1de.T
+
+    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
+    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)
+
+    for X in X1sp, X1de:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='strong')
+
+        assert_equal(n_components, 3)
+        labels.sort()
+        assert_array_almost_equal(labels, [0, 1, 2])
+
+    for X in X2sp, X2de:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='strong')
+
+        assert_equal(n_components, 2)
+        labels.sort()
+        assert_array_almost_equal(labels, [0, 0, 1])
+
+
+def test_strong_connections2():
+    X = np.array([[0, 0, 0, 0, 0, 0],
+                  [1, 0, 1, 0, 0, 0],
+                  [0, 0, 0, 1, 0, 0],
+                  [0, 0, 1, 0, 1, 0],
+                  [0, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 0, 1, 0]])
+    n_components, labels =\
+        csgraph.connected_components(X, directed=True,
+                                     connection='strong')
+    assert_equal(n_components, 5)
+    labels.sort()
+    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4])
+
+
+def test_weak_connections2():
+    X = np.array([[0, 0, 0, 0, 0, 0],
+                  [1, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 1, 0, 0],
+                  [0, 0, 1, 0, 1, 0],
+                  [0, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 0, 1, 0]])
+    n_components, labels =\
+        csgraph.connected_components(X, directed=True,
+                                     connection='weak')
+    assert_equal(n_components, 2)
+    labels.sort()
+    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1])
+
+
+def test_ticket1876():
+    # Regression test: this failed in the original implementation
+    # There should be two strongly-connected components; previously gave one
+    g = np.array([[0, 1, 1, 0],
+                  [1, 0, 0, 1],
+                  [0, 0, 0, 1],
+                  [0, 0, 1, 0]])
+    n_components, labels = csgraph.connected_components(g, connection='strong')
+
+    assert_equal(n_components, 2)
+    assert_equal(labels[0], labels[1])
+    assert_equal(labels[2], labels[3])
+
+
+def test_fully_connected_graph():
+    # Fully connected dense matrices raised an exception.
+    # https://github.com/scipy/scipy/issues/3818
+    g = np.ones((4, 4))
+    n_components, labels = csgraph.connected_components(g)
+    assert_equal(n_components, 1)
+
+
+def test_int64_indices_undirected():
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    n, labels = csgraph.connected_components(g, directed=False)
+    assert n == 1
+    assert_array_almost_equal(labels, [0, 0])
+
+
+def test_int64_indices_directed():
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    n, labels = csgraph.connected_components(g, directed=True,
+                                             connection='strong')
+    assert n == 2
+    assert_array_almost_equal(labels, [1, 0])
+
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py
new file mode 100644
index 0000000000000000000000000000000000000000..65f141e5b371367018a6e9985f8325850d8972da
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py
@@ -0,0 +1,61 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+from scipy.sparse import csr_array
+from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense
+
+
+def test_csgraph_from_dense():
+    np.random.seed(1234)
+    G = np.random.random((10, 10))
+    some_nulls = (G < 0.4)
+    all_nulls = (G < 0.8)
+
+    for null_value in [0, np.nan, np.inf]:
+        G[all_nulls] = null_value
+        with np.errstate(invalid="ignore"):
+            G_csr = csgraph_from_dense(G, null_value=0)
+
+        G[all_nulls] = 0
+        assert_array_almost_equal(G, G_csr.toarray())
+
+    for null_value in [np.nan, np.inf]:
+        G[all_nulls] = 0
+        G[some_nulls] = null_value
+        with np.errstate(invalid="ignore"):
+            G_csr = csgraph_from_dense(G, null_value=0)
+
+        G[all_nulls] = 0
+        assert_array_almost_equal(G, G_csr.toarray())
+
+
+def test_csgraph_to_dense():
+    np.random.seed(1234)
+    G = np.random.random((10, 10))
+    nulls = (G < 0.8)
+    G[nulls] = np.inf
+
+    G_csr = csgraph_from_dense(G)
+
+    for null_value in [0, 10, -np.inf, np.inf]:
+        G[nulls] = null_value
+        assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value))
+
+
+def test_multiple_edges():
+    # create a random square matrix with an even number of elements
+    np.random.seed(1234)
+    X = np.random.random((10, 10))
+    Xcsr = csr_array(X)
+
+    # now double-up every other column
+    Xcsr.indices[::2] = Xcsr.indices[1::2]
+
+    # normal sparse toarray() will sum the duplicated edges
+    Xdense = Xcsr.toarray()
+    assert_array_almost_equal(Xdense[:, 1::2],
+                              X[:, ::2] + X[:, 1::2])
+
+    # csgraph_to_dense chooses the minimum of each duplicated edge
+    Xdense = csgraph_to_dense(Xcsr)
+    assert_array_almost_equal(Xdense[:, 1::2],
+                              np.minimum(X[:, ::2], X[:, 1::2]))
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92eb985a1145c4b7c1777f0449bb423402f6d66
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py
@@ -0,0 +1,209 @@
+import numpy as np
+from numpy.testing import assert_array_equal
+import pytest
+
+from scipy.sparse import csr_array, csc_array, csr_matrix
+from scipy.sparse.csgraph import maximum_flow
+from scipy.sparse.csgraph._flow import (
+    _add_reverse_edges, _make_edge_pointers, _make_tails
+)
+
+methods = ['edmonds_karp', 'dinic']
+
+def test_raises_on_dense_input():
+    with pytest.raises(TypeError):
+        graph = np.array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_csc_input():
+    with pytest.raises(TypeError):
+        graph = csc_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_floating_point_input():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1.5], [0, 0]], dtype=np.float64)
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_non_square_input():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1, 2], [2, 1, 0]])
+        maximum_flow(graph, 0, 1)
+
+
+def test_raises_when_source_is_sink():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 0)
+        maximum_flow(graph, 0, 0, method='edmonds_karp')
+
+
+@pytest.mark.parametrize('method', methods)
+@pytest.mark.parametrize('source', [-1, 2, 3])
+def test_raises_when_source_is_out_of_bounds(source, method):
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, source, 1, method=method)
+
+
+@pytest.mark.parametrize('method', methods)
+@pytest.mark.parametrize('sink', [-1, 2, 3])
+def test_raises_when_sink_is_out_of_bounds(sink, method):
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, sink, method=method)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_simple_graph(method):
+    # This graph looks as follows:
+    #     (0) --5--> (1)
+    graph = csr_array([[0, 5], [0, 0]])
+    res = maximum_flow(graph, 0, 1, method=method)
+    assert res.flow_value == 5
+    expected_flow = np.array([[0, 5], [-5, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_return_type(method):
+    graph = csr_array([[0, 5], [0, 0]])
+    assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_array)
+    graph = csr_matrix([[0, 5], [0, 0]])
+    assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_matrix)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_bottle_neck_graph(method):
+    # This graph cannot use the full capacity between 0 and 1:
+    #     (0) --5--> (1) --3--> (2)
+    graph = csr_array([[0, 5, 0], [0, 0, 3], [0, 0, 0]])
+    res = maximum_flow(graph, 0, 2, method=method)
+    assert res.flow_value == 3
+    expected_flow = np.array([[0, 3, 0], [-3, 0, 3], [0, -3, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_backwards_flow(method):
+    # This example causes backwards flow between vertices 3 and 4,
+    # and so this test ensures that we handle that accordingly. See
+    #     https://stackoverflow.com/q/38843963/5085211
+    # for more information.
+    graph = csr_array([[0, 10, 0, 0, 10, 0, 0, 0],
+                       [0, 0, 10, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 10, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0, 0, 10],
+                       [0, 0, 0, 10, 0, 10, 0, 0],
+                       [0, 0, 0, 0, 0, 0, 10, 0],
+                       [0, 0, 0, 0, 0, 0, 0, 10],
+                       [0, 0, 0, 0, 0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 7, method=method)
+    assert res.flow_value == 20
+    expected_flow = np.array([[0, 10, 0, 0, 10, 0, 0, 0],
+                              [-10, 0, 10, 0, 0, 0, 0, 0],
+                              [0, -10, 0, 10, 0, 0, 0, 0],
+                              [0, 0, -10, 0, 0, 0, 0, 10],
+                              [-10, 0, 0, 0, 0, 10, 0, 0],
+                              [0, 0, 0, 0, -10, 0, 10, 0],
+                              [0, 0, 0, 0, 0, -10, 0, 10],
+                              [0, 0, 0, -10, 0, 0, -10, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_example_from_clrs_chapter_26_1(method):
+    # See page 659 in CLRS second edition, but note that the maximum flow
+    # we find is slightly different than the one in CLRS; we push a flow of
+    # 12 to v_1 instead of v_2.
+    graph = csr_array([[0, 16, 13, 0, 0, 0],
+                       [0, 0, 10, 12, 0, 0],
+                       [0, 4, 0, 0, 14, 0],
+                       [0, 0, 9, 0, 0, 20],
+                       [0, 0, 0, 7, 0, 4],
+                       [0, 0, 0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 5, method=method)
+    assert res.flow_value == 23
+    expected_flow = np.array([[0, 12, 11, 0, 0, 0],
+                              [-12, 0, 0, 12, 0, 0],
+                              [-11, 0, 0, 0, 11, 0],
+                              [0, -12, 0, 0, -7, 19],
+                              [0, 0, -11, 7, 0, 4],
+                              [0, 0, 0, -19, -4, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_disconnected_graph(method):
+    # This tests the following disconnected graph:
+    #     (0) --5--> (1)    (2) --3--> (3)
+    graph = csr_array([[0, 5, 0, 0],
+                       [0, 0, 0, 0],
+                       [0, 0, 9, 3],
+                       [0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 3, method=method)
+    assert res.flow_value == 0
+    expected_flow = np.zeros((4, 4), dtype=np.int32)
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_add_reverse_edges_large_graph(method):
+    # Regression test for https://github.com/scipy/scipy/issues/14385
+    n = 100_000
+    indices = np.arange(1, n)
+    indptr = np.array(list(range(n)) + [n - 1])
+    data = np.ones(n - 1, dtype=np.int32)
+    graph = csr_array((data, indices, indptr), shape=(n, n))
+    res = maximum_flow(graph, 0, n - 1, method=method)
+    assert res.flow_value == 1
+    expected_flow = graph - graph.transpose()
+    assert_array_equal(res.flow.data, expected_flow.data)
+    assert_array_equal(res.flow.indices, expected_flow.indices)
+    assert_array_equal(res.flow.indptr, expected_flow.indptr)
+
+
+@pytest.mark.parametrize("a,b_data_expected", [
+    ([[]], []),
+    ([[0], [0]], []),
+    ([[1, 0, 2], [0, 0, 0], [0, 3, 0]], [1, 2, 0, 0, 3]),
+    ([[9, 8, 7], [4, 5, 6], [0, 0, 0]], [9, 8, 7, 4, 5, 6, 0, 0])])
+def test_add_reverse_edges(a, b_data_expected):
+    """Test that the reversal of the edges of the input graph works
+    as expected.
+    """
+    a = csr_array(a, dtype=np.int32, shape=(len(a), len(a)))
+    b = _add_reverse_edges(a)
+    assert_array_equal(b.data, b_data_expected)
+
+
+@pytest.mark.parametrize("a,expected", [
+    ([[]], []),
+    ([[0]], []),
+    ([[1]], [0]),
+    ([[0, 1], [10, 0]], [1, 0]),
+    ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 3, 4, 1, 2])
+])
+def test_make_edge_pointers(a, expected):
+    a = csr_array(a, dtype=np.int32)
+    rev_edge_ptr = _make_edge_pointers(a)
+    assert_array_equal(rev_edge_ptr, expected)
+
+
+@pytest.mark.parametrize("a,expected", [
+    ([[]], []),
+    ([[0]], []),
+    ([[1]], [0]),
+    ([[0, 1], [10, 0]], [0, 1]),
+    ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 0, 1, 2, 2])
+])
+def test_make_tails(a, expected):
+    a = csr_array(a, dtype=np.int32)
+    tails = _make_tails(a)
+    assert_array_equal(tails, expected)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ed5e2edf92ef0cacc819fcbd06bc6d4e195cb44
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py
@@ -0,0 +1,368 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+from scipy import sparse
+
+from scipy.sparse import csgraph
+from scipy._lib._util import np_long, np_ulong
+
+
+def check_int_type(mat):
+    return np.issubdtype(mat.dtype, np.signedinteger) or np.issubdtype(
+        mat.dtype, np_ulong
+    )
+
+
+def test_laplacian_value_error():
+    for t in int, float, complex:
+        for m in ([1, 1],
+                  [[[1]]],
+                  [[1, 2, 3], [4, 5, 6]],
+                  [[1, 2], [3, 4], [5, 5]]):
+            A = np.array(m, dtype=t)
+            assert_raises(ValueError, csgraph.laplacian, A)
+
+
+def _explicit_laplacian(x, normed=False):
+    if sparse.issparse(x):
+        x = x.toarray()
+    x = np.asarray(x)
+    y = -1.0 * x
+    for j in range(y.shape[0]):
+        y[j,j] = x[j,j+1:].sum() + x[j,:j].sum()
+    if normed:
+        d = np.diag(y).copy()
+        d[d == 0] = 1.0
+        y /= d[:,None]**.5
+        y /= d[None,:]**.5
+    return y
+
+
+def _check_symmetric_graph_laplacian(mat, normed, copy=True):
+    if not hasattr(mat, 'shape'):
+        mat = eval(mat, dict(np=np, sparse=sparse))
+
+    if sparse.issparse(mat):
+        sp_mat = mat
+        mat = sp_mat.toarray()
+    else:
+        sp_mat = sparse.csr_array(mat)
+
+    mat_copy = np.copy(mat)
+    sp_mat_copy = sparse.csr_array(sp_mat, copy=True)
+
+    n_nodes = mat.shape[0]
+    explicit_laplacian = _explicit_laplacian(mat, normed=normed)
+    laplacian = csgraph.laplacian(mat, normed=normed, copy=copy)
+    sp_laplacian = csgraph.laplacian(sp_mat, normed=normed,
+                                     copy=copy)
+
+    if copy:
+        assert_allclose(mat, mat_copy)
+        _assert_allclose_sparse(sp_mat, sp_mat_copy)
+    else:
+        if not (normed and check_int_type(mat)):
+            assert_allclose(laplacian, mat)
+            if sp_mat.format == 'coo':
+                _assert_allclose_sparse(sp_laplacian, sp_mat)
+
+    assert_allclose(laplacian, sp_laplacian.toarray())
+
+    for tested in [laplacian, sp_laplacian.toarray()]:
+        if not normed:
+            assert_allclose(tested.sum(axis=0), np.zeros(n_nodes))
+        assert_allclose(tested.T, tested)
+        assert_allclose(tested, explicit_laplacian)
+
+
+def test_symmetric_graph_laplacian():
+    symmetric_mats = (
+        'np.arange(10) * np.arange(10)[:, np.newaxis]',
+        'np.ones((7, 7))',
+        'np.eye(19)',
+        'sparse.diags([1, 1], [-1, 1], shape=(4, 4))',
+        'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).toarray()',
+        'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).todense()',
+        'np.vander(np.arange(4)) + np.vander(np.arange(4)).T'
+    )
+    for mat in symmetric_mats:
+        for normed in True, False:
+            for copy in True, False:
+                _check_symmetric_graph_laplacian(mat, normed, copy)
+
+
+def _assert_allclose_sparse(a, b, **kwargs):
+    # helper function that can deal with sparse matrices
+    if sparse.issparse(a):
+        a = a.toarray()
+    if sparse.issparse(b):
+        b = b.toarray()
+    assert_allclose(a, b, **kwargs)
+
+
+def _check_laplacian_dtype_none(
+    A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type
+):
+    mat = arr_type(A, dtype=dtype)
+    L, d = csgraph.laplacian(
+        mat,
+        normed=normed,
+        return_diag=True,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=None,
+    )
+    if normed and check_int_type(mat):
+        assert L.dtype == np.float64
+        assert d.dtype == np.float64
+        _assert_allclose_sparse(L, desired_L, atol=1e-12)
+        _assert_allclose_sparse(d, desired_d, atol=1e-12)
+    else:
+        assert L.dtype == dtype
+        assert d.dtype == dtype
+        desired_L = np.asarray(desired_L).astype(dtype)
+        desired_d = np.asarray(desired_d).astype(dtype)
+        _assert_allclose_sparse(L, desired_L, atol=1e-12)
+        _assert_allclose_sparse(d, desired_d, atol=1e-12)
+
+    if not copy:
+        if not (normed and check_int_type(mat)):
+            if type(mat) is np.ndarray:
+                assert_allclose(L, mat)
+            elif mat.format == "coo":
+                _assert_allclose_sparse(L, mat)
+
+
+def _check_laplacian_dtype(
+    A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type
+):
+    mat = arr_type(A, dtype=dtype)
+    L, d = csgraph.laplacian(
+        mat,
+        normed=normed,
+        return_diag=True,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+    )
+    assert L.dtype == dtype
+    assert d.dtype == dtype
+    desired_L = np.asarray(desired_L).astype(dtype)
+    desired_d = np.asarray(desired_d).astype(dtype)
+    _assert_allclose_sparse(L, desired_L, atol=1e-12)
+    _assert_allclose_sparse(d, desired_d, atol=1e-12)
+
+    if not copy:
+        if not (normed and check_int_type(mat)):
+            if type(mat) is np.ndarray:
+                assert_allclose(L, mat)
+            elif mat.format == 'coo':
+                _assert_allclose_sparse(L, mat)
+
+
+INT_DTYPES = (np.intc, np_long, np.longlong)
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = INT_DTYPES + REAL_DTYPES + COMPLEX_DTYPES
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("arr_type", [np.array,
+                                      sparse.csr_matrix,
+                                      sparse.coo_matrix,
+                                      sparse.csr_array,
+                                      sparse.coo_array])
+@pytest.mark.parametrize("copy", [True, False])
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("use_out_degree", [True, False])
+def test_asymmetric_laplacian(use_out_degree, normed,
+                              copy, dtype, arr_type):
+    # adjacency matrix
+    A = [[0, 1, 0],
+         [4, 2, 0],
+         [0, 0, 0]]
+    A = arr_type(np.array(A), dtype=dtype)
+    A_copy = A.copy()
+
+    if not normed and use_out_degree:
+        # Laplacian matrix using out-degree
+        L = [[1, -1, 0],
+             [-4, 4, 0],
+             [0, 0, 0]]
+        d = [1, 4, 0]
+
+    if normed and use_out_degree:
+        # normalized Laplacian matrix using out-degree
+        L = [[1, -0.5, 0],
+             [-2, 1, 0],
+             [0, 0, 0]]
+        d = [1, 2, 1]
+
+    if not normed and not use_out_degree:
+        # Laplacian matrix using in-degree
+        L = [[4, -1, 0],
+             [-4, 1, 0],
+             [0, 0, 0]]
+        d = [4, 1, 0]
+
+    if normed and not use_out_degree:
+        # normalized Laplacian matrix using in-degree
+        L = [[1, -0.5, 0],
+             [-2, 1, 0],
+             [0, 0, 0]]
+        d = [2, 1, 1]
+
+    _check_laplacian_dtype_none(
+        A,
+        L,
+        d,
+        normed=normed,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+        arr_type=arr_type,
+    )
+
+    _check_laplacian_dtype(
+        A_copy,
+        L,
+        d,
+        normed=normed,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+        arr_type=arr_type,
+    )
+
+
+@pytest.mark.parametrize("fmt", ['csr', 'csc', 'coo', 'lil',
+                                 'dok', 'dia', 'bsr'])
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("copy", [True, False])
+def test_sparse_formats(fmt, normed, copy):
+    mat = sparse.diags_array([1, 1], offsets=[-1, 1], shape=(4, 4), format=fmt)
+    _check_symmetric_graph_laplacian(mat, normed, copy)
+
+
+@pytest.mark.parametrize(
+    "arr_type", [np.asarray,
+                 sparse.csr_matrix,
+                 sparse.coo_matrix,
+                 sparse.csr_array,
+                 sparse.coo_array]
+)
+@pytest.mark.parametrize("form", ["array", "function", "lo"])
+def test_laplacian_symmetrized(arr_type, form):
+    # adjacency matrix
+    n = 3
+    mat = arr_type(np.arange(n * n).reshape(n, n))
+    L_in, d_in = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        form=form,
+    )
+    L_out, d_out = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        use_out_degree=True,
+        form=form,
+    )
+    Ls, ds = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        symmetrized=True,
+        form=form,
+    )
+    Ls_normed, ds_normed = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        symmetrized=True,
+        normed=True,
+        form=form,
+    )
+    mat += mat.T
+    Lss, dss = csgraph.laplacian(mat, return_diag=True, form=form)
+    Lss_normed, dss_normed = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=True,
+        form=form,
+    )
+
+    assert_allclose(ds, d_in + d_out)
+    assert_allclose(ds, dss)
+    assert_allclose(ds_normed, dss_normed)
+
+    d = {}
+    for L in ["L_in", "L_out", "Ls", "Ls_normed", "Lss", "Lss_normed"]:
+        if form == "array":
+            d[L] = eval(L)
+        else:
+            d[L] = eval(L)(np.eye(n, dtype=mat.dtype))
+
+    _assert_allclose_sparse(d["Ls"], d["L_in"] + d["L_out"].T)
+    _assert_allclose_sparse(d["Ls"], d["Lss"])
+    _assert_allclose_sparse(d["Ls_normed"], d["Lss_normed"])
+
+
+@pytest.mark.parametrize(
+    "arr_type", [np.asarray,
+                 sparse.csr_matrix,
+                 sparse.coo_matrix,
+                 sparse.csr_array,
+                 sparse.coo_array]
+)
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("symmetrized", [True, False])
+@pytest.mark.parametrize("use_out_degree", [True, False])
+@pytest.mark.parametrize("form", ["function", "lo"])
+def test_format(dtype, arr_type, normed, symmetrized, use_out_degree, form):
+    n = 3
+    mat = [[0, 1, 0], [4, 2, 0], [0, 0, 0]]
+    mat = arr_type(np.array(mat), dtype=dtype)
+    Lo, do = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+    )
+    La, da = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+        form="array",
+    )
+    assert_allclose(do, da)
+    _assert_allclose_sparse(Lo, La)
+
+    L, d = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+        form=form,
+    )
+    assert_allclose(d, do)
+    assert d.dtype == dtype
+    Lm = L(np.eye(n, dtype=mat.dtype)).astype(dtype)
+    _assert_allclose_sparse(Lm, Lo, rtol=2e-7, atol=2e-7)
+    x = np.arange(6).reshape(3, 2)
+    if not (normed and dtype in INT_DTYPES):
+        assert_allclose(L(x), Lo @ x)
+    else:
+        # Normalized Lo is casted to integer, but L() is not
+        pass
+
+
+def test_format_error_message():
+    with pytest.raises(ValueError, match="Invalid form: 'toto'"):
+        _ = csgraph.laplacian(np.eye(1), form='toto')
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..8477861d3e563c43379c615ec0913f47a4349abd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py
@@ -0,0 +1,295 @@
+from itertools import product
+
+import numpy as np
+from numpy.testing import assert_array_equal, assert_equal
+import pytest
+
+from scipy.sparse import csr_array, diags_array
+from scipy.sparse.csgraph import (
+    maximum_bipartite_matching, min_weight_full_bipartite_matching
+)
+
+
+def test_maximum_bipartite_matching_raises_on_dense_input():
+    with pytest.raises(TypeError):
+        graph = np.array([[0, 1], [0, 0]])
+        maximum_bipartite_matching(graph)
+
+
+def test_maximum_bipartite_matching_empty_graph():
+    graph = csr_array((0, 0))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    expected_matching = np.array([])
+    assert_array_equal(expected_matching, x)
+    assert_array_equal(expected_matching, y)
+
+
+def test_maximum_bipartite_matching_empty_left_partition():
+    graph = csr_array((2, 0))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert_array_equal(np.array([]), x)
+    assert_array_equal(np.array([-1, -1]), y)
+
+
+def test_maximum_bipartite_matching_empty_right_partition():
+    graph = csr_array((0, 3))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert_array_equal(np.array([-1, -1, -1]), x)
+    assert_array_equal(np.array([]), y)
+
+
+def test_maximum_bipartite_matching_graph_with_no_edges():
+    graph = csr_array((2, 2))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert_array_equal(np.array([-1, -1]), x)
+    assert_array_equal(np.array([-1, -1]), y)
+
+
+def test_maximum_bipartite_matching_graph_that_causes_augmentation():
+    # In this graph, column 1 is initially assigned to row 1, but it should be
+    # reassigned to make room for row 2.
+    graph = csr_array([[1, 1], [1, 0]])
+    x = maximum_bipartite_matching(graph, perm_type='column')
+    y = maximum_bipartite_matching(graph, perm_type='row')
+    expected_matching = np.array([1, 0])
+    assert_array_equal(expected_matching, x)
+    assert_array_equal(expected_matching, y)
+
+
+def test_maximum_bipartite_matching_graph_with_more_rows_than_columns():
+    graph = csr_array([[1, 1], [1, 0], [0, 1]])
+    x = maximum_bipartite_matching(graph, perm_type='column')
+    y = maximum_bipartite_matching(graph, perm_type='row')
+    assert_array_equal(np.array([0, -1, 1]), x)
+    assert_array_equal(np.array([0, 2]), y)
+
+
+def test_maximum_bipartite_matching_graph_with_more_columns_than_rows():
+    graph = csr_array([[1, 1, 0], [0, 0, 1]])
+    x = maximum_bipartite_matching(graph, perm_type='column')
+    y = maximum_bipartite_matching(graph, perm_type='row')
+    assert_array_equal(np.array([0, 2]), x)
+    assert_array_equal(np.array([0, -1, 1]), y)
+
+
+def test_maximum_bipartite_matching_explicit_zeros_count_as_edges():
+    data = [0, 0]
+    indices = [1, 0]
+    indptr = [0, 1, 2]
+    graph = csr_array((data, indices, indptr), shape=(2, 2))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    expected_matching = np.array([1, 0])
+    assert_array_equal(expected_matching, x)
+    assert_array_equal(expected_matching, y)
+
+
+def test_maximum_bipartite_matching_feasibility_of_result():
+    # This is a regression test for GitHub issue #11458
+    data = np.ones(50, dtype=int)
+    indices = [11, 12, 19, 22, 23, 5, 22, 3, 8, 10, 5, 6, 11, 12, 13, 5, 13,
+               14, 20, 22, 3, 15, 3, 13, 14, 11, 12, 19, 22, 23, 5, 22, 3, 8,
+               10, 5, 6, 11, 12, 13, 5, 13, 14, 20, 22, 3, 15, 3, 13, 14]
+    indptr = [0, 5, 7, 10, 10, 15, 20, 22, 22, 23, 25, 30, 32, 35, 35, 40, 45,
+              47, 47, 48, 50]
+    graph = csr_array((data, indices, indptr), shape=(20, 25))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert (x != -1).sum() == 13
+    assert (y != -1).sum() == 13
+    # Ensure that each element of the matching is in fact an edge in the graph.
+    for u, v in zip(range(graph.shape[0]), y):
+        if v != -1:
+            assert graph[u, v]
+    for u, v in zip(x, range(graph.shape[1])):
+        if u != -1:
+            assert graph[u, v]
+
+
+def test_matching_large_random_graph_with_one_edge_incident_to_each_vertex():
+    np.random.seed(42)
+    A = diags_array(np.ones(25), offsets=0, format='csr')
+    rand_perm = np.random.permutation(25)
+    rand_perm2 = np.random.permutation(25)
+
+    Rrow = np.arange(25)
+    Rcol = rand_perm
+    Rdata = np.ones(25, dtype=int)
+    Rmat = csr_array((Rdata, (Rrow, Rcol)))
+
+    Crow = rand_perm2
+    Ccol = np.arange(25)
+    Cdata = np.ones(25, dtype=int)
+    Cmat = csr_array((Cdata, (Crow, Ccol)))
+    # Randomly permute identity matrix
+    B = Rmat @ A @ Cmat
+
+    # Row permute
+    perm = maximum_bipartite_matching(B, perm_type='row')
+    Rrow = np.arange(25)
+    Rcol = perm
+    Rdata = np.ones(25, dtype=int)
+    Rmat = csr_array((Rdata, (Rrow, Rcol)))
+    C1 = Rmat @ B
+
+    # Column permute
+    perm2 = maximum_bipartite_matching(B, perm_type='column')
+    Crow = perm2
+    Ccol = np.arange(25)
+    Cdata = np.ones(25, dtype=int)
+    Cmat = csr_array((Cdata, (Crow, Ccol)))
+    C2 = B @ Cmat
+
+    # Should get identity matrix back
+    assert_equal(any(C1.diagonal() == 0), False)
+    assert_equal(any(C2.diagonal() == 0), False)
+
+
+@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)])
+def test_min_weight_full_matching_trivial_graph(num_rows, num_cols):
+    biadjacency = csr_array((num_cols, num_rows))
+    row_ind, col_ind = min_weight_full_bipartite_matching(biadjacency)
+    assert len(row_ind) == 0
+    assert len(col_ind) == 0
+
+
+@pytest.mark.parametrize('biadjacency',
+                         [
+                            [[1, 1, 1], [1, 0, 0], [1, 0, 0]],
+                            [[1, 1, 1], [0, 0, 1], [0, 0, 1]],
+                            [[1, 0, 0, 1], [1, 1, 0, 1], [0, 0, 0, 0]],
+                            [[1, 0, 0], [2, 0, 0]],
+                            [[0, 1, 0], [0, 2, 0]],
+                            [[1, 0], [2, 0], [5, 0]]
+                         ])
+def test_min_weight_full_matching_infeasible_problems(biadjacency):
+    with pytest.raises(ValueError):
+        min_weight_full_bipartite_matching(csr_array(biadjacency))
+
+
+def test_min_weight_full_matching_large_infeasible():
+    # Regression test for GitHub issue #17269
+    a = np.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.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001],
+        [0.0, 0.11687445, 0.0, 0.0, 0.01319788, 0.07509257, 0.0,
+         0.0, 0.0, 0.74228317, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.81087935, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.8408466, 0.0, 0.0, 0.0, 0.0, 0.01194389,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.82994211, 0.0, 0.0, 0.0, 0.11468516, 0.0, 0.0, 0.0,
+         0.11173505, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0],
+        [0.18796507, 0.0, 0.04002318, 0.0, 0.0, 0.0, 0.0, 0.0, 0.75883335,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.71545464, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02748488,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.78470564, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.14829198,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.10870609, 0.0, 0.0, 0.0, 0.8918677, 0.0, 0.0, 0.0, 0.06306644,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.63844085, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.7442354, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09850549, 0.0, 0.0, 0.18638258,
+         0.2769244, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.73182464, 0.0, 0.0, 0.46443561,
+         0.38589284, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.29510278, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09666032, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
+        ])
+    with pytest.raises(ValueError, match='no full matching exists'):
+        min_weight_full_bipartite_matching(csr_array(a))
+
+
+@pytest.mark.thread_unsafe
+def test_explicit_zero_causes_warning():
+    with pytest.warns(UserWarning):
+        biadjacency = csr_array(((2, 0, 3), (0, 1, 1), (0, 2, 3)))
+        min_weight_full_bipartite_matching(biadjacency)
+
+
+# General test for linear sum assignment solvers to make it possible to rely
+# on the same tests for scipy.optimize.linear_sum_assignment.
+def linear_sum_assignment_assertions(
+    solver, array_type, sign, test_case
+):
+    cost_matrix, expected_cost = test_case
+    maximize = sign == -1
+    cost_matrix = sign * array_type(cost_matrix)
+    expected_cost = sign * np.array(expected_cost)
+
+    row_ind, col_ind = solver(cost_matrix, maximize=maximize)
+    assert_array_equal(row_ind, np.sort(row_ind))
+    assert_array_equal(expected_cost,
+                       np.array(cost_matrix[row_ind, col_ind]).flatten())
+
+    cost_matrix = cost_matrix.T
+    row_ind, col_ind = solver(cost_matrix, maximize=maximize)
+    assert_array_equal(row_ind, np.sort(row_ind))
+    assert_array_equal(np.sort(expected_cost),
+                       np.sort(np.array(
+                           cost_matrix[row_ind, col_ind])).flatten())
+
+
+linear_sum_assignment_test_cases = product(
+    [-1, 1],
+    [
+        # Square
+        ([[400, 150, 400],
+          [400, 450, 600],
+          [300, 225, 300]],
+         [150, 400, 300]),
+
+        # Rectangular variant
+        ([[400, 150, 400, 1],
+          [400, 450, 600, 2],
+          [300, 225, 300, 3]],
+         [150, 2, 300]),
+
+        ([[10, 10, 8],
+          [9, 8, 1],
+          [9, 7, 4]],
+         [10, 1, 7]),
+
+        # Square
+        ([[10, 10, 8, 11],
+          [9, 8, 1, 1],
+          [9, 7, 4, 10]],
+         [10, 1, 4]),
+
+        # Rectangular variant
+        ([[10, float("inf"), float("inf")],
+          [float("inf"), float("inf"), 1],
+          [float("inf"), 7, float("inf")]],
+         [10, 1, 7])
+    ])
+
+
+@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases)
+def test_min_weight_full_matching_small_inputs(sign, test_case):
+    linear_sum_assignment_assertions(
+        min_weight_full_bipartite_matching, csr_array, sign, test_case)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..1476c29a3ba97869c6c38be4d717641a494c1183
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py
@@ -0,0 +1,194 @@
+import pytest
+
+import numpy as np
+import scipy.sparse as sp
+import scipy.sparse.csgraph as spgraph
+from scipy._lib import _pep440
+
+from numpy.testing import assert_equal
+
+try:
+    import sparse
+except Exception:
+    sparse = None
+
+pytestmark = pytest.mark.skipif(sparse is None,
+                                reason="pydata/sparse not installed")
+
+
+msg = "pydata/sparse (0.15.1) does not implement necessary operations"
+
+
+sparse_params = (pytest.param("COO"),
+                 pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)]))
+
+
+def check_sparse_version(min_ver):
+    if sparse is None:
+        return pytest.mark.skip(reason="sparse is not installed")
+    return pytest.mark.skipif(
+        _pep440.parse(sparse.__version__) < _pep440.Version(min_ver),
+        reason=f"sparse version >= {min_ver} required"
+    )
+
+
+@pytest.fixture(params=sparse_params)
+def sparse_cls(request):
+    return getattr(sparse, request.param)
+
+
+@pytest.fixture
+def graphs(sparse_cls):
+    graph = [
+        [0, 1, 1, 0, 0],
+        [0, 0, 1, 0, 0],
+        [0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 1],
+        [0, 0, 0, 0, 0],
+    ]
+    A_dense = np.array(graph)
+    A_sparse = sparse_cls(A_dense)
+    return A_dense, A_sparse
+
+
+@pytest.mark.parametrize(
+    "func",
+    [
+        spgraph.shortest_path,
+        spgraph.dijkstra,
+        spgraph.floyd_warshall,
+        spgraph.bellman_ford,
+        spgraph.johnson,
+        spgraph.reverse_cuthill_mckee,
+        spgraph.maximum_bipartite_matching,
+        spgraph.structural_rank,
+    ]
+)
+def test_csgraph_equiv(func, graphs):
+    A_dense, A_sparse = graphs
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+    assert_equal(actual, desired)
+
+
+def test_connected_components(graphs):
+    A_dense, A_sparse = graphs
+    func = spgraph.connected_components
+
+    actual_comp, actual_labels = func(A_sparse)
+    desired_comp, desired_labels, = func(sp.csc_array(A_dense))
+
+    assert actual_comp == desired_comp
+    assert_equal(actual_labels, desired_labels)
+
+
+def test_laplacian(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.laplacian
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+@pytest.mark.parametrize(
+    "func", [spgraph.breadth_first_order, spgraph.depth_first_order]
+)
+def test_order_search(graphs, func):
+    A_dense, A_sparse = graphs
+
+    actual = func(A_sparse, 0)
+    desired = func(sp.csc_array(A_dense), 0)
+
+    assert_equal(actual, desired)
+
+
+@pytest.mark.parametrize(
+    "func", [spgraph.breadth_first_tree, spgraph.depth_first_tree]
+)
+def test_tree_search(graphs, func):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+
+    actual = func(A_sparse, 0)
+    desired = func(sp.csc_array(A_dense), 0)
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+def test_minimum_spanning_tree(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.minimum_spanning_tree
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+def test_maximum_flow(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.maximum_flow
+
+    actual = func(A_sparse, 0, 2)
+    desired = func(sp.csr_array(A_dense), 0, 2)
+
+    assert actual.flow_value == desired.flow_value
+    assert isinstance(actual.flow, sparse_cls)
+
+    assert_equal(actual.flow.todense(), desired.flow.todense())
+
+
+def test_min_weight_full_bipartite_matching(graphs):
+    A_dense, A_sparse = graphs
+    func = spgraph.min_weight_full_bipartite_matching
+
+    actual = func(A_sparse[0:2, 1:3])
+    desired = func(sp.csc_array(A_dense)[0:2, 1:3])
+
+    assert_equal(actual, desired)
+
+
+@check_sparse_version("0.15.4")
+@pytest.mark.parametrize(
+    "func",
+    [
+        spgraph.shortest_path,
+        spgraph.dijkstra,
+        spgraph.floyd_warshall,
+        spgraph.bellman_ford,
+        spgraph.johnson,
+        spgraph.minimum_spanning_tree,
+    ]
+)
+@pytest.mark.parametrize(
+    "fill_value, comp_func",
+    [(np.inf, np.isposinf), (np.nan, np.isnan)],
+)
+def test_nonzero_fill_value(graphs, func, fill_value, comp_func):
+    A_dense, A_sparse = graphs
+    A_sparse = A_sparse.astype(float)
+    A_sparse.fill_value = fill_value
+    sparse_cls = type(A_sparse)
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    if func == spgraph.minimum_spanning_tree:
+        assert isinstance(actual, sparse_cls)
+        assert comp_func(actual.fill_value)
+        actual = actual.todense()
+        actual[comp_func(actual)] = 0.0
+        assert_equal(actual, desired.todense())
+    else:
+        assert_equal(actual, desired)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py
new file mode 100644
index 0000000000000000000000000000000000000000..add76cdc29c39c079f386a6ca73075bb90b0a6e8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py
@@ -0,0 +1,70 @@
+import numpy as np
+from numpy.testing import assert_equal
+from scipy.sparse.csgraph import reverse_cuthill_mckee, structural_rank
+from scipy.sparse import csc_array, csr_array, coo_array
+
+
+def test_graph_reverse_cuthill_mckee():
+    A = np.array([[1, 0, 0, 0, 1, 0, 0, 0],
+                [0, 1, 1, 0, 0, 1, 0, 1],
+                [0, 1, 1, 0, 1, 0, 0, 0],
+                [0, 0, 0, 1, 0, 0, 1, 0],
+                [1, 0, 1, 0, 1, 0, 0, 0],
+                [0, 1, 0, 0, 0, 1, 0, 1],
+                [0, 0, 0, 1, 0, 0, 1, 0],
+                [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int)
+
+    graph = csr_array(A)
+    perm = reverse_cuthill_mckee(graph)
+    correct_perm = np.array([6, 3, 7, 5, 1, 2, 4, 0])
+    assert_equal(perm, correct_perm)
+
+    # Test int64 indices input
+    graph.indices = graph.indices.astype('int64')
+    graph.indptr = graph.indptr.astype('int64')
+    perm = reverse_cuthill_mckee(graph, True)
+    assert_equal(perm, correct_perm)
+
+
+def test_graph_reverse_cuthill_mckee_ordering():
+    data = np.ones(63,dtype=int)
+    rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2,
+                2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
+                6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9,
+                9, 10, 10, 10, 10, 10, 11, 11, 11, 11,
+                12, 12, 12, 13, 13, 13, 13, 14, 14, 14,
+                14, 15, 15, 15, 15, 15])
+    cols = np.array([0, 2, 5, 8, 10, 1, 3, 9, 11, 0, 2,
+                7, 10, 1, 3, 11, 4, 6, 12, 14, 0, 7, 13,
+                15, 4, 6, 14, 2, 5, 7, 15, 0, 8, 10, 13,
+                1, 9, 11, 0, 2, 8, 10, 15, 1, 3, 9, 11,
+                4, 12, 14, 5, 8, 13, 15, 4, 6, 12, 14,
+                5, 7, 10, 13, 15])
+    graph = csr_array((data, (rows,cols)))
+    perm = reverse_cuthill_mckee(graph)
+    correct_perm = np.array([12, 14, 4, 6, 10, 8, 2, 15,
+                0, 13, 7, 5, 9, 11, 1, 3])
+    assert_equal(perm, correct_perm)
+
+
+def test_graph_structural_rank():
+    # Test square matrix #1
+    A = csc_array([[1, 1, 0],
+                   [1, 0, 1],
+                   [0, 1, 0]])
+    assert_equal(structural_rank(A), 3)
+
+    # Test square matrix #2
+    rows = np.array([0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6,6,7,7])
+    cols = np.array([0,1,2,3,4,2,5,2,6,0,1,3,5,6,7,4,5,5,6,2,6,2,4])
+    data = np.ones_like(rows)
+    B = coo_array((data,(rows,cols)), shape=(8,8))
+    assert_equal(structural_rank(B), 6)
+
+    #Test non-square matrix
+    C = csc_array([[1, 0, 2, 0],
+                   [2, 0, 4, 0]])
+    assert_equal(structural_rank(C), 2)
+
+    #Test tall matrix
+    assert_equal(structural_rank(C.T), 2)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba50f760e750ce1dbdec3624c2ab985fca1af7d1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py
@@ -0,0 +1,484 @@
+from io import StringIO
+import warnings
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose
+from pytest import raises as assert_raises
+from scipy.sparse.csgraph import (shortest_path, dijkstra, johnson,
+                                  bellman_ford, construct_dist_matrix, yen,
+                                  NegativeCycleError)
+import scipy.sparse
+from scipy.io import mmread
+import pytest
+
+directed_G = np.array([[0, 3, 3, 0, 0],
+                       [0, 0, 0, 2, 4],
+                       [0, 0, 0, 0, 0],
+                       [1, 0, 0, 0, 0],
+                       [2, 0, 0, 2, 0]], dtype=float)
+
+undirected_G = np.array([[0, 3, 3, 1, 2],
+                         [3, 0, 0, 2, 4],
+                         [3, 0, 0, 0, 0],
+                         [1, 2, 0, 0, 2],
+                         [2, 4, 0, 2, 0]], dtype=float)
+
+unweighted_G = (directed_G > 0).astype(float)
+
+directed_SP = [[0, 3, 3, 5, 7],
+               [3, 0, 6, 2, 4],
+               [np.inf, np.inf, 0, np.inf, np.inf],
+               [1, 4, 4, 0, 8],
+               [2, 5, 5, 2, 0]]
+
+directed_2SP_0_to_3 = [[-9999, 0, -9999, 1, -9999],
+                       [-9999, 0, -9999, 4, 1]]
+
+directed_sparse_zero_G = scipy.sparse.csr_array(
+    (
+        [0, 1, 2, 3, 1],
+        ([0, 1, 2, 3, 4], [1, 2, 0, 4, 3]),
+    ),
+    shape=(5, 5),
+)
+
+directed_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf],
+                      [3, 0, 1, np.inf, np.inf],
+                      [2, 2, 0, np.inf, np.inf],
+                      [np.inf, np.inf, np.inf, 0, 3],
+                      [np.inf, np.inf, np.inf, 1, 0]]
+
+undirected_sparse_zero_G = scipy.sparse.csr_array(
+    (
+        [0, 0, 1, 1, 2, 2, 1, 1],
+        ([0, 1, 1, 2, 2, 0, 3, 4], [1, 0, 2, 1, 0, 2, 4, 3])
+    ),
+    shape=(5, 5),
+)
+
+undirected_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf],
+                        [0, 0, 1, np.inf, np.inf],
+                        [1, 1, 0, np.inf, np.inf],
+                        [np.inf, np.inf, np.inf, 0, 1],
+                        [np.inf, np.inf, np.inf, 1, 0]]
+
+directed_pred = np.array([[-9999, 0, 0, 1, 1],
+                          [3, -9999, 0, 1, 1],
+                          [-9999, -9999, -9999, -9999, -9999],
+                          [3, 0, 0, -9999, 1],
+                          [4, 0, 0, 4, -9999]], dtype=float)
+
+undirected_SP = np.array([[0, 3, 3, 1, 2],
+                          [3, 0, 6, 2, 4],
+                          [3, 6, 0, 4, 5],
+                          [1, 2, 4, 0, 2],
+                          [2, 4, 5, 2, 0]], dtype=float)
+
+undirected_SP_limit_2 = np.array([[0, np.inf, np.inf, 1, 2],
+                                  [np.inf, 0, np.inf, 2, np.inf],
+                                  [np.inf, np.inf, 0, np.inf, np.inf],
+                                  [1, 2, np.inf, 0, 2],
+                                  [2, np.inf, np.inf, 2, 0]], dtype=float)
+
+undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5)
+undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf
+
+undirected_pred = np.array([[-9999, 0, 0, 0, 0],
+                            [1, -9999, 0, 1, 1],
+                            [2, 0, -9999, 0, 0],
+                            [3, 3, 0, -9999, 3],
+                            [4, 4, 0, 4, -9999]], dtype=float)
+
+directed_negative_weighted_G = np.array([[0, 0, 0],
+                                         [-1, 0, 0],
+                                         [0, -1, 0]], dtype=float)
+
+directed_negative_weighted_SP = np.array([[0, np.inf, np.inf],
+                                          [-1, 0, np.inf],
+                                          [-2, -1, 0]], dtype=float)
+
+methods = ['auto', 'FW', 'D', 'BF', 'J']
+
+
+def test_dijkstra_limit():
+    limits = [0, 2, np.inf]
+    results = [undirected_SP_limit_0,
+               undirected_SP_limit_2,
+               undirected_SP]
+
+    def check(limit, result):
+        SP = dijkstra(undirected_G, directed=False, limit=limit)
+        assert_array_almost_equal(SP, result)
+
+    for limit, result in zip(limits, results):
+        check(limit, result)
+
+
+def test_directed():
+    def check(method):
+        SP = shortest_path(directed_G, method=method, directed=True,
+                           overwrite=False)
+        assert_array_almost_equal(SP, directed_SP)
+
+    for method in methods:
+        check(method)
+
+
+def test_undirected():
+    def check(method, directed_in):
+        if directed_in:
+            SP1 = shortest_path(directed_G, method=method, directed=False,
+                                overwrite=False)
+            assert_array_almost_equal(SP1, undirected_SP)
+        else:
+            SP2 = shortest_path(undirected_G, method=method, directed=True,
+                                overwrite=False)
+            assert_array_almost_equal(SP2, undirected_SP)
+
+    for method in methods:
+        for directed_in in (True, False):
+            check(method, directed_in)
+
+
+def test_directed_sparse_zero():
+    # test directed sparse graph with zero-weight edge and two connected components
+    def check(method):
+        SP = shortest_path(directed_sparse_zero_G, method=method, directed=True,
+                           overwrite=False)
+        assert_array_almost_equal(SP, directed_sparse_zero_SP)
+
+    for method in methods:
+        check(method)
+
+
+def test_undirected_sparse_zero():
+    def check(method, directed_in):
+        if directed_in:
+            SP1 = shortest_path(directed_sparse_zero_G, method=method, directed=False,
+                                overwrite=False)
+            assert_array_almost_equal(SP1, undirected_sparse_zero_SP)
+        else:
+            SP2 = shortest_path(undirected_sparse_zero_G, method=method, directed=True,
+                                overwrite=False)
+            assert_array_almost_equal(SP2, undirected_sparse_zero_SP)
+
+    for method in methods:
+        for directed_in in (True, False):
+            check(method, directed_in)
+
+
+@pytest.mark.parametrize('directed, SP_ans',
+                         ((True, directed_SP),
+                          (False, undirected_SP)))
+@pytest.mark.parametrize('indices', ([0, 2, 4], [0, 4], [3, 4], [0, 0]))
+def test_dijkstra_indices_min_only(directed, SP_ans, indices):
+    SP_ans = np.array(SP_ans)
+    indices = np.array(indices, dtype=np.int64)
+    min_ind_ans = indices[np.argmin(SP_ans[indices, :], axis=0)]
+    min_d_ans = np.zeros(SP_ans.shape[0], SP_ans.dtype)
+    for k in range(SP_ans.shape[0]):
+        min_d_ans[k] = SP_ans[min_ind_ans[k], k]
+    min_ind_ans[np.isinf(min_d_ans)] = -9999
+
+    SP, pred, sources = dijkstra(directed_G,
+                                 directed=directed,
+                                 indices=indices,
+                                 min_only=True,
+                                 return_predecessors=True)
+    assert_array_almost_equal(SP, min_d_ans)
+    assert_array_equal(min_ind_ans, sources)
+    SP = dijkstra(directed_G,
+                  directed=directed,
+                  indices=indices,
+                  min_only=True,
+                  return_predecessors=False)
+    assert_array_almost_equal(SP, min_d_ans)
+
+
+@pytest.mark.parametrize('n', (10, 100, 1000))
+def test_dijkstra_min_only_random(n):
+    rng = np.random.default_rng(7345782358920239234)
+    data = scipy.sparse.random_array((n, n), density=0.5, format='lil',
+                                     rng=rng, dtype=np.float64)
+    data.setdiag(np.zeros(n, dtype=np.bool_))
+    # choose some random vertices
+    v = np.arange(n)
+    rng.shuffle(v)
+    indices = v[:int(n*.1)]
+    ds, pred, sources = dijkstra(data,
+                                 directed=True,
+                                 indices=indices,
+                                 min_only=True,
+                                 return_predecessors=True)
+    for k in range(n):
+        p = pred[k]
+        s = sources[k]
+        while p != -9999:
+            assert sources[p] == s
+            p = pred[p]
+
+
+def test_dijkstra_random():
+    # reproduces the hang observed in gh-17782
+    n = 10
+    indices = [0, 4, 4, 5, 7, 9, 0, 6, 2, 3, 7, 9, 1, 2, 9, 2, 5, 6]
+    indptr = [0, 0, 2, 5, 6, 7, 8, 12, 15, 18, 18]
+    data = [0.33629, 0.40458, 0.47493, 0.42757, 0.11497, 0.91653, 0.69084,
+            0.64979, 0.62555, 0.743, 0.01724, 0.99945, 0.31095, 0.15557,
+            0.02439, 0.65814, 0.23478, 0.24072]
+    graph = scipy.sparse.csr_array((data, indices, indptr), shape=(n, n))
+    dijkstra(graph, directed=True, return_predecessors=True)
+
+
+def test_gh_17782_segfault():
+    text = """%%MatrixMarket matrix coordinate real general
+                84 84 22
+                2 1 4.699999809265137e+00
+                6 14 1.199999973177910e-01
+                9 6 1.199999973177910e-01
+                10 16 2.012000083923340e+01
+                11 10 1.422000026702881e+01
+                12 1 9.645999908447266e+01
+                13 18 2.012000083923340e+01
+                14 13 4.679999828338623e+00
+                15 11 1.199999973177910e-01
+                16 12 1.199999973177910e-01
+                18 15 1.199999973177910e-01
+                32 2 2.299999952316284e+00
+                33 20 6.000000000000000e+00
+                33 32 5.000000000000000e+00
+                36 9 3.720000028610229e+00
+                36 37 3.720000028610229e+00
+                36 38 3.720000028610229e+00
+                37 44 8.159999847412109e+00
+                38 32 7.903999328613281e+01
+                43 20 2.400000000000000e+01
+                43 33 4.000000000000000e+00
+                44 43 6.028000259399414e+01
+    """
+    data = mmread(StringIO(text), spmatrix=False)
+    dijkstra(data, directed=True, return_predecessors=True)
+
+
+def test_shortest_path_indices():
+    indices = np.arange(4)
+
+    def check(func, indshape):
+        outshape = indshape + (5,)
+        SP = func(directed_G, directed=False,
+                  indices=indices.reshape(indshape))
+        assert_array_almost_equal(SP, undirected_SP[indices].reshape(outshape))
+
+    for indshape in [(4,), (4, 1), (2, 2)]:
+        for func in (dijkstra, bellman_ford, johnson, shortest_path):
+            check(func, indshape)
+
+    assert_raises(ValueError, shortest_path, directed_G, method='FW',
+                  indices=indices)
+
+
+def test_predecessors():
+    SP_res = {True: directed_SP,
+              False: undirected_SP}
+    pred_res = {True: directed_pred,
+                False: undirected_pred}
+
+    def check(method, directed):
+        SP, pred = shortest_path(directed_G, method, directed=directed,
+                                 overwrite=False,
+                                 return_predecessors=True)
+        assert_array_almost_equal(SP, SP_res[directed])
+        assert_array_almost_equal(pred, pred_res[directed])
+
+    for method in methods:
+        for directed in (True, False):
+            check(method, directed)
+
+
+def test_construct_shortest_path():
+    def check(method, directed):
+        SP1, pred = shortest_path(directed_G,
+                                  directed=directed,
+                                  overwrite=False,
+                                  return_predecessors=True)
+        SP2 = construct_dist_matrix(directed_G, pred, directed=directed)
+        assert_array_almost_equal(SP1, SP2)
+
+    for method in methods:
+        for directed in (True, False):
+            check(method, directed)
+
+
+def test_unweighted_path():
+    def check(method, directed):
+        SP1 = shortest_path(directed_G,
+                            directed=directed,
+                            overwrite=False,
+                            unweighted=True)
+        SP2 = shortest_path(unweighted_G,
+                            directed=directed,
+                            overwrite=False,
+                            unweighted=False)
+        assert_array_almost_equal(SP1, SP2)
+
+    for method in methods:
+        for directed in (True, False):
+            check(method, directed)
+
+
+def test_negative_cycles():
+    # create a small graph with a negative cycle
+    graph = np.ones([5, 5])
+    graph.flat[::6] = 0
+    graph[1, 2] = -2
+
+    def check(method, directed):
+        assert_raises(NegativeCycleError, shortest_path, graph, method,
+                      directed)
+
+    for directed in (True, False):
+        for method in ['FW', 'J', 'BF']:
+            check(method, directed)
+
+        assert_raises(NegativeCycleError, yen, graph, 0, 1, 1,
+                      directed=directed)
+
+
+@pytest.mark.parametrize("method", ['FW', 'J', 'BF'])
+def test_negative_weights(method):
+    SP = shortest_path(directed_negative_weighted_G, method, directed=True)
+    assert_allclose(SP, directed_negative_weighted_SP, atol=1e-10)
+
+
+def test_masked_input():
+    np.ma.masked_equal(directed_G, 0)
+
+    def check(method):
+        SP = shortest_path(directed_G, method=method, directed=True,
+                           overwrite=False)
+        assert_array_almost_equal(SP, directed_SP)
+
+    for method in methods:
+        check(method)
+
+
+def test_overwrite():
+    G = np.array([[0, 3, 3, 1, 2],
+                  [3, 0, 0, 2, 4],
+                  [3, 0, 0, 0, 0],
+                  [1, 2, 0, 0, 2],
+                  [2, 4, 0, 2, 0]], dtype=float)
+    foo = G.copy()
+    shortest_path(foo, overwrite=False)
+    assert_array_equal(foo, G)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_buffer(method):
+    # Smoke test that sparse matrices with read-only buffers (e.g., those from
+    # joblib workers) do not cause::
+    #
+    #     ValueError: buffer source array is read-only
+    #
+    G = scipy.sparse.csr_array([[1.]])
+    G.data.flags['WRITEABLE'] = False
+    shortest_path(G, method=method)
+
+
+def test_NaN_warnings():
+    with warnings.catch_warnings(record=True) as record:
+        shortest_path(np.array([[0, 1], [np.nan, 0]]))
+    for r in record:
+        assert r.category is not RuntimeWarning
+
+
+def test_sparse_matrices():
+    # Test that using lil,csr and csc sparse matrix do not cause error
+    G_dense = np.array([[0, 3, 0, 0, 0],
+                        [0, 0, -1, 0, 0],
+                        [0, 0, 0, 2, 0],
+                        [0, 0, 0, 0, 4],
+                        [0, 0, 0, 0, 0]], dtype=float)
+    SP = shortest_path(G_dense)
+    G_csr = scipy.sparse.csr_array(G_dense)
+    G_csc = scipy.sparse.csc_array(G_dense)
+    G_lil = scipy.sparse.lil_array(G_dense)
+    assert_array_almost_equal(SP, shortest_path(G_csr))
+    assert_array_almost_equal(SP, shortest_path(G_csc))
+    assert_array_almost_equal(SP, shortest_path(G_lil))
+
+
+def test_yen_directed():
+    distances, predecessors = yen(
+                            directed_G,
+                            source=0,
+                            sink=3,
+                            K=2,
+                            return_predecessors=True
+                        )
+    assert_allclose(distances, [5., 9.])
+    assert_allclose(predecessors, directed_2SP_0_to_3)
+
+
+def test_yen_undirected():
+    distances = yen(
+        undirected_G,
+        source=0,
+        sink=3,
+        K=4,
+    )
+    assert_allclose(distances, [1., 4., 5., 8.])
+
+def test_yen_unweighted():
+    # Ask for more paths than there are, verify only the available paths are returned
+    distances, predecessors = yen(
+        directed_G,
+        source=0,
+        sink=3,
+        K=4,
+        unweighted=True,
+        return_predecessors=True,
+    )
+    assert_allclose(distances, [2., 3.])
+    assert_allclose(predecessors, directed_2SP_0_to_3)
+
+def test_yen_no_paths():
+    distances = yen(
+        directed_G,
+        source=2,
+        sink=3,
+        K=1,
+    )
+    assert distances.size == 0
+
+def test_yen_negative_weights():
+    distances = yen(
+        directed_negative_weighted_G,
+        source=2,
+        sink=0,
+        K=1,
+    )
+    assert_allclose(distances, [-2.])
+
+
+@pytest.mark.parametrize("min_only", (True, False))
+@pytest.mark.parametrize("directed", (True, False))
+@pytest.mark.parametrize("return_predecessors", (True, False))
+@pytest.mark.parametrize("index_dtype", (np.int32, np.int64))
+@pytest.mark.parametrize("indices", (None, [1]))
+def test_20904(min_only, directed, return_predecessors, index_dtype, indices):
+    """Test two failures from gh-20904: int32 and indices-as-None."""
+    adj_mat = scipy.sparse.eye_array(4, format="csr")
+    adj_mat = scipy.sparse.csr_array(
+        (
+            adj_mat.data,
+            adj_mat.indices.astype(index_dtype),
+            adj_mat.indptr.astype(index_dtype),
+        ),
+    )
+    dijkstra(
+        adj_mat,
+        directed,
+        indices=indices,
+        min_only=min_only,
+        return_predecessors=return_predecessors,
+    )
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..3237a14584d42022184a54f174b809a2b06d16ed
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py
@@ -0,0 +1,66 @@
+"""Test the minimum spanning tree function"""
+import numpy as np
+from numpy.testing import assert_
+import numpy.testing as npt
+from scipy.sparse import csr_array
+from scipy.sparse.csgraph import minimum_spanning_tree
+
+
+def test_minimum_spanning_tree():
+
+    # Create a graph with two connected components.
+    graph = [[0,1,0,0,0],
+             [1,0,0,0,0],
+             [0,0,0,8,5],
+             [0,0,8,0,1],
+             [0,0,5,1,0]]
+    graph = np.asarray(graph)
+
+    # Create the expected spanning tree.
+    expected = [[0,1,0,0,0],
+                [0,0,0,0,0],
+                [0,0,0,0,5],
+                [0,0,0,0,1],
+                [0,0,0,0,0]]
+    expected = np.asarray(expected)
+
+    # Ensure minimum spanning tree code gives this expected output.
+    csgraph = csr_array(graph)
+    mintree = minimum_spanning_tree(csgraph)
+    mintree_array = mintree.toarray()
+    npt.assert_array_equal(mintree_array, expected,
+                           'Incorrect spanning tree found.')
+
+    # Ensure that the original graph was not modified.
+    npt.assert_array_equal(csgraph.toarray(), graph,
+        'Original graph was modified.')
+
+    # Now let the algorithm modify the csgraph in place.
+    mintree = minimum_spanning_tree(csgraph, overwrite=True)
+    npt.assert_array_equal(mintree.toarray(), expected,
+        'Graph was not properly modified to contain MST.')
+
+    np.random.seed(1234)
+    for N in (5, 10, 15, 20):
+
+        # Create a random graph.
+        graph = 3 + np.random.random((N, N))
+        csgraph = csr_array(graph)
+
+        # The spanning tree has at most N - 1 edges.
+        mintree = minimum_spanning_tree(csgraph)
+        assert_(mintree.nnz < N)
+
+        # Set the sub diagonal to 1 to create a known spanning tree.
+        idx = np.arange(N-1)
+        graph[idx,idx+1] = 1
+        csgraph = csr_array(graph)
+        mintree = minimum_spanning_tree(csgraph)
+
+        # We expect to see this pattern in the spanning tree and otherwise
+        # have this zero.
+        expected = np.zeros((N, N))
+        expected[idx, idx+1] = 1
+
+        npt.assert_array_equal(mintree.toarray(), expected,
+            'Incorrect spanning tree found.')
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py
new file mode 100644
index 0000000000000000000000000000000000000000..aef6def21b61ff6b8d8bfb990a3a69136349d7c5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py
@@ -0,0 +1,148 @@
+import numpy as np
+import pytest
+from numpy.testing import assert_array_almost_equal
+from scipy.sparse import csr_array, csr_matrix, coo_array, coo_matrix
+from scipy.sparse.csgraph import (breadth_first_tree, depth_first_tree,
+    csgraph_to_dense, csgraph_from_dense, csgraph_masked_from_dense)
+
+
+def test_graph_breadth_first():
+    csgraph = np.array([[0, 1, 2, 0, 0],
+                        [1, 0, 0, 0, 3],
+                        [2, 0, 0, 7, 0],
+                        [0, 0, 7, 0, 1],
+                        [0, 3, 0, 1, 0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    bfirst = np.array([[0, 1, 2, 0, 0],
+                       [0, 0, 0, 0, 3],
+                       [0, 0, 0, 7, 0],
+                       [0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0]])
+
+    for directed in [True, False]:
+        bfirst_test = breadth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(bfirst_test),
+                                  bfirst)
+
+
+def test_graph_depth_first():
+    csgraph = np.array([[0, 1, 2, 0, 0],
+                        [1, 0, 0, 0, 3],
+                        [2, 0, 0, 7, 0],
+                        [0, 0, 7, 0, 1],
+                        [0, 3, 0, 1, 0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    dfirst = np.array([[0, 1, 0, 0, 0],
+                       [0, 0, 0, 0, 3],
+                       [0, 0, 0, 0, 0],
+                       [0, 0, 7, 0, 0],
+                       [0, 0, 0, 1, 0]])
+
+    for directed in [True, False]:
+        dfirst_test = depth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst)
+
+
+def test_return_type():
+    from .._laplacian import laplacian
+    from .._min_spanning_tree import minimum_spanning_tree
+
+    np_csgraph = np.array([[0, 1, 2, 0, 0],
+                           [1, 0, 0, 0, 3],
+                           [2, 0, 0, 7, 0],
+                           [0, 0, 7, 0, 1],
+                           [0, 3, 0, 1, 0]])
+    csgraph = csr_array(np_csgraph)
+    assert isinstance(laplacian(csgraph), coo_array)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_array)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
+
+    csgraph = csgraph_from_dense(np_csgraph, null_value=0)
+    assert isinstance(csgraph, csr_array)
+    assert isinstance(laplacian(csgraph), coo_array)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_array)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
+
+    csgraph = csgraph_masked_from_dense(np_csgraph, null_value=0)
+    assert isinstance(csgraph, np.ma.MaskedArray)
+    assert csgraph._baseclass is np.ndarray
+    # laplacian doesnt work with masked arrays so not here
+    assert isinstance(minimum_spanning_tree(csgraph), csr_array)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
+
+    # start of testing with matrix/spmatrix types
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, "the matrix subclass.*")
+        sup.filter(PendingDeprecationWarning, "the matrix subclass.*")
+
+        nm_csgraph = np.matrix([[0, 1, 2, 0, 0],
+                                [1, 0, 0, 0, 3],
+                                [2, 0, 0, 7, 0],
+                                [0, 0, 7, 0, 1],
+                                [0, 3, 0, 1, 0]])
+
+    csgraph = csr_matrix(nm_csgraph)
+    assert isinstance(laplacian(csgraph), coo_matrix)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
+
+    csgraph = csgraph_from_dense(nm_csgraph, null_value=0)
+    assert isinstance(csgraph, csr_matrix)
+    assert isinstance(laplacian(csgraph), coo_matrix)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
+
+    mm_csgraph = csgraph_masked_from_dense(nm_csgraph, null_value=0)
+    assert isinstance(mm_csgraph, np.ma.MaskedArray)
+    # laplacian doesnt work with masked arrays so not here
+    assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
+    # end of testing with matrix/spmatrix types
+
+
+def test_graph_breadth_first_trivial_graph():
+    csgraph = np.array([[0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    bfirst = np.array([[0]])
+
+    for directed in [True, False]:
+        bfirst_test = breadth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst)
+
+
+def test_graph_depth_first_trivial_graph():
+    csgraph = np.array([[0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    bfirst = np.array([[0]])
+
+    for directed in [True, False]:
+        bfirst_test = depth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(bfirst_test),
+                                  bfirst)
+
+
+@pytest.mark.parametrize('directed', [True, False])
+@pytest.mark.parametrize('tree_func', [breadth_first_tree, depth_first_tree])
+def test_int64_indices(tree_func, directed):
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    tree = tree_func(g, 0, directed=directed)
+    assert_array_almost_equal(csgraph_to_dense(tree), [[0, 1], [0, 0]])
+
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/csr.py b/venv/lib/python3.10/site-packages/scipy/sparse/csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..86bb1e072ebe4480e9dcb01f2d36f7387872b898
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/csr.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'csr_count_blocks',
+    'csr_matrix',
+    'csr_tobsr',
+    'csr_tocsc',
+    'get_csr_submatrix',
+    'isspmatrix_csr',
+    'spmatrix',
+    'upcast',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="csr",
+                                   private_modules=["_csr"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/data.py b/venv/lib/python3.10/site-packages/scipy/sparse/data.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9958bcda6dd35ac0779514d79b7f1c494c1b01a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/data.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'isscalarlike',
+    'name',
+    'npfunc',
+    'validateaxis',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="data",
+                                   private_modules=["_data"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/dia.py b/venv/lib/python3.10/site-packages/scipy/sparse/dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..f79abd39f114b23df8ceb6eafb7fcc1c07218dcb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/dia.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'check_shape',
+    'dia_matrix',
+    'dia_matvec',
+    'get_sum_dtype',
+    'getdtype',
+    'isshape',
+    'isspmatrix_dia',
+    'spmatrix',
+    'upcast_char',
+    'validateaxis',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="dia",
+                                   private_modules=["_dia"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/extract.py b/venv/lib/python3.10/site-packages/scipy/sparse/extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..be5e161b6f99e57e2b2a6b3d4f1ef6427c07658d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/extract.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'coo_matrix',
+    'find',
+    'tril',
+    'triu',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="extract",
+                                   private_modules=["_extract"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/lil.py b/venv/lib/python3.10/site-packages/scipy/sparse/lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7bf8eb03bb36a1b2fa77c5fc0840e532ab64fd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/lil.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'isspmatrix_lil',
+    'lil_array',
+    'lil_matrix',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="lil",
+                                   private_modules=["_lil"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/sparsetools.py b/venv/lib/python3.10/site-packages/scipy/sparse/sparsetools.py
new file mode 100644
index 0000000000000000000000000000000000000000..404e431d89d479520d2198ae73b9eab7b23a80f7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/sparsetools.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.sparse` 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="sparse", module="sparsetools",
+                                   private_modules=["_sparsetools"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/sparse/spfuncs.py b/venv/lib/python3.10/site-packages/scipy/sparse/spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..911969e414d4a1d3888900ad8392b5fc2177c850
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/sparse/spfuncs.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.sparse` 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="sparse", module="spfuncs",
+                                   private_modules=["_spfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__init__.pxd b/venv/lib/python3.10/site-packages/scipy/special/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..1daa9fb379572aac4bc9b6d74330a18c5c52bf79
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/__init__.pxd
@@ -0,0 +1 @@
+from scipy.special cimport cython_special
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__init__.py b/venv/lib/python3.10/site-packages/scipy/special/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8993f522a0fac00e243d361835a42b89a82d11ef
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/__init__.py
@@ -0,0 +1,887 @@
+"""
+========================================
+Special functions (:mod:`scipy.special`)
+========================================
+
+.. currentmodule:: scipy.special
+
+Almost all of the functions below accept NumPy arrays as input
+arguments as well as single numbers. This means they follow
+broadcasting and automatic array-looping rules. Technically,
+they are `NumPy universal functions
+`_.
+Functions which do not accept NumPy arrays are marked by a warning
+in the section description.
+
+.. seealso::
+
+   `scipy.special.cython_special` -- Typed Cython versions of special functions
+
+
+Error handling
+==============
+
+Errors are handled by returning NaNs or other appropriate values.
+Some of the special function routines can emit warnings or raise
+exceptions when an error occurs. By default this is disabled, except
+for memory allocation errors, which result in an exception being raised.
+To query and control the current error handling state the following
+functions are provided.
+
+.. autosummary::
+   :toctree: generated/
+
+   geterr                 -- Get the current way of handling special-function errors.
+   seterr                 -- Set how special-function errors are handled.
+   errstate               -- Context manager for special-function error handling.
+   SpecialFunctionWarning -- Warning that can be emitted by special functions.
+   SpecialFunctionError   -- Exception that can be raised by special functions.
+
+Available functions
+===================
+
+Airy functions
+--------------
+
+.. autosummary::
+   :toctree: generated/
+
+   airy     -- Airy functions and their derivatives.
+   airye    -- Exponentially scaled Airy functions and their derivatives.
+   ai_zeros -- Compute `nt` zeros and values of the Airy function Ai and its derivative.
+   bi_zeros -- Compute `nt` zeros and values of the Airy function Bi and its derivative.
+   itairy   -- Integrals of Airy functions
+
+
+Elliptic functions and integrals
+--------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   ellipj    -- Jacobian elliptic functions.
+   ellipk    -- Complete elliptic integral of the first kind.
+   ellipkm1  -- Complete elliptic integral of the first kind around `m` = 1.
+   ellipkinc -- Incomplete elliptic integral of the first kind.
+   ellipe    -- Complete elliptic integral of the second kind.
+   ellipeinc -- Incomplete elliptic integral of the second kind.
+   elliprc   -- Degenerate symmetric integral RC.
+   elliprd   -- Symmetric elliptic integral of the second kind.
+   elliprf   -- Completely-symmetric elliptic integral of the first kind.
+   elliprg   -- Completely-symmetric elliptic integral of the second kind.
+   elliprj   -- Symmetric elliptic integral of the third kind.
+
+Bessel functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   jv                -- Bessel function of the first kind of real order and \
+                        complex argument.
+   jve               -- Exponentially scaled Bessel function of order `v`.
+   yn                -- Bessel function of the second kind of integer order and \
+                        real argument.
+   yv                -- Bessel function of the second kind of real order and \
+                        complex argument.
+   yve               -- Exponentially scaled Bessel function of the second kind \
+                        of real order.
+   kn                -- Modified Bessel function of the second kind of integer \
+                        order `n`
+   kv                -- Modified Bessel function of the second kind of real order \
+                        `v`
+   kve               -- Exponentially scaled modified Bessel function of the \
+                        second kind.
+   iv                -- Modified Bessel function of the first kind of real order.
+   ive               -- Exponentially scaled modified Bessel function of the \
+                        first kind.
+   hankel1           -- Hankel function of the first kind.
+   hankel1e          -- Exponentially scaled Hankel function of the first kind.
+   hankel2           -- Hankel function of the second kind.
+   hankel2e          -- Exponentially scaled Hankel function of the second kind.
+   wright_bessel     -- Wright's generalized Bessel function.
+   log_wright_bessel -- Logarithm of Wright's generalized Bessel function.
+
+The following function does not accept NumPy arrays (it is not a
+universal function):
+
+.. autosummary::
+   :toctree: generated/
+
+   lmbda -- Jahnke-Emden Lambda function, Lambdav(x).
+
+Zeros of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   jnjnp_zeros -- Compute zeros of integer-order Bessel functions Jn and Jn'.
+   jnyn_zeros  -- Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
+   jn_zeros    -- Compute zeros of integer-order Bessel function Jn(x).
+   jnp_zeros   -- Compute zeros of integer-order Bessel function derivative Jn'(x).
+   yn_zeros    -- Compute zeros of integer-order Bessel function Yn(x).
+   ynp_zeros   -- Compute zeros of integer-order Bessel function derivative Yn'(x).
+   y0_zeros    -- Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
+   y1_zeros    -- Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
+   y1p_zeros   -- Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
+
+Faster versions of common Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   j0  -- Bessel function of the first kind of order 0.
+   j1  -- Bessel function of the first kind of order 1.
+   y0  -- Bessel function of the second kind of order 0.
+   y1  -- Bessel function of the second kind of order 1.
+   i0  -- Modified Bessel function of order 0.
+   i0e -- Exponentially scaled modified Bessel function of order 0.
+   i1  -- Modified Bessel function of order 1.
+   i1e -- Exponentially scaled modified Bessel function of order 1.
+   k0  -- Modified Bessel function of the second kind of order 0, :math:`K_0`.
+   k0e -- Exponentially scaled modified Bessel function K of order 0
+   k1  -- Modified Bessel function of the second kind of order 1, :math:`K_1(x)`.
+   k1e -- Exponentially scaled modified Bessel function K of order 1.
+
+Integrals of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   itj0y0     -- Integrals of Bessel functions of order 0.
+   it2j0y0    -- Integrals related to Bessel functions of order 0.
+   iti0k0     -- Integrals of modified Bessel functions of order 0.
+   it2i0k0    -- Integrals related to modified Bessel functions of order 0.
+   besselpoly -- Weighted integral of a Bessel function.
+
+Derivatives of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   jvp  -- Compute nth derivative of Bessel function Jv(z) with respect to `z`.
+   yvp  -- Compute nth derivative of Bessel function Yv(z) with respect to `z`.
+   kvp  -- Compute nth derivative of real-order modified Bessel function Kv(z)
+   ivp  -- Compute nth derivative of modified Bessel function Iv(z) with respect to `z`.
+   h1vp -- Compute nth derivative of Hankel function H1v(z) with respect to `z`.
+   h2vp -- Compute nth derivative of Hankel function H2v(z) with respect to `z`.
+
+Spherical Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   spherical_jn -- Spherical Bessel function of the first kind or its derivative.
+   spherical_yn -- Spherical Bessel function of the second kind or its derivative.
+   spherical_in -- Modified spherical Bessel function of the first kind or its derivative.
+   spherical_kn -- Modified spherical Bessel function of the second kind or its derivative.
+
+Riccati-Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   riccati_jn -- Compute Ricatti-Bessel function of the first kind and its derivative.
+   riccati_yn -- Compute Ricatti-Bessel function of the second kind and its derivative.
+
+Struve functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   struve       -- Struve function.
+   modstruve    -- Modified Struve function.
+   itstruve0    -- Integral of the Struve function of order 0.
+   it2struve0   -- Integral related to the Struve function of order 0.
+   itmodstruve0 -- Integral of the modified Struve function of order 0.
+
+
+Raw statistical functions
+-------------------------
+
+.. seealso:: :mod:`scipy.stats`: Friendly versions of these functions.
+
+Binomial distribution
+^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   bdtr         -- Binomial distribution cumulative distribution function.
+   bdtrc        -- Binomial distribution survival function.
+   bdtri        -- Inverse function to `bdtr` with respect to `p`.
+   bdtrik       -- Inverse function to `bdtr` with respect to `k`.
+   bdtrin       -- Inverse function to `bdtr` with respect to `n`.
+
+Beta distribution
+^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   btdtria      -- Inverse of `betainc` with respect to `a`.
+   btdtrib      -- Inverse of `betainc` with respect to `b`.
+
+F distribution
+^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   fdtr         -- F cumulative distribution function.
+   fdtrc        -- F survival function.
+   fdtri        -- The `p`-th quantile of the F-distribution.
+   fdtridfd     -- Inverse to `fdtr` vs dfd.
+
+Gamma distribution
+^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   gdtr         -- Gamma distribution cumulative distribution function.
+   gdtrc        -- Gamma distribution survival function.
+   gdtria       -- Inverse of `gdtr` vs a.
+   gdtrib       -- Inverse of `gdtr` vs b.
+   gdtrix       -- Inverse of `gdtr` vs x.
+
+Negative binomial distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nbdtr        -- Negative binomial cumulative distribution function.
+   nbdtrc       -- Negative binomial survival function.
+   nbdtri       -- Inverse of `nbdtr` vs `p`.
+   nbdtrik      -- Inverse of `nbdtr` vs `k`.
+   nbdtrin      -- Inverse of `nbdtr` vs `n`.
+
+Noncentral F distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   ncfdtr       -- Cumulative distribution function of the non-central F distribution.
+   ncfdtridfd   -- Calculate degrees of freedom (denominator) for the noncentral F-distribution.
+   ncfdtridfn   -- Calculate degrees of freedom (numerator) for the noncentral F-distribution.
+   ncfdtri      -- Inverse cumulative distribution function of the non-central F distribution.
+   ncfdtrinc    -- Calculate non-centrality parameter for non-central F distribution.
+
+Noncentral t distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nctdtr       -- Cumulative distribution function of the non-central `t` distribution.
+   nctdtridf    -- Calculate degrees of freedom for non-central t distribution.
+   nctdtrit     -- Inverse cumulative distribution function of the non-central t distribution.
+   nctdtrinc    -- Calculate non-centrality parameter for non-central t distribution.
+
+Normal distribution
+^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nrdtrimn     -- Calculate mean of normal distribution given other params.
+   nrdtrisd     -- Calculate standard deviation of normal distribution given other params.
+   ndtr         -- Normal cumulative distribution function.
+   log_ndtr     -- Logarithm of normal cumulative distribution function.
+   ndtri        -- Inverse of `ndtr` vs x.
+   ndtri_exp    -- Inverse of `log_ndtr` vs x.
+
+Poisson distribution
+^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   pdtr         -- Poisson cumulative distribution function.
+   pdtrc        -- Poisson survival function.
+   pdtri        -- Inverse to `pdtr` vs m.
+   pdtrik       -- Inverse to `pdtr` vs k.
+
+Student t distribution
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   stdtr        -- Student t distribution cumulative distribution function.
+   stdtridf     -- Inverse of `stdtr` vs df.
+   stdtrit      -- Inverse of `stdtr` vs `t`.
+
+Chi square distribution
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   chdtr        -- Chi square cumulative distribution function.
+   chdtrc       -- Chi square survival function.
+   chdtri       -- Inverse to `chdtrc`.
+   chdtriv      -- Inverse to `chdtr` vs `v`.
+
+Non-central chi square distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   chndtr       -- Non-central chi square cumulative distribution function.
+   chndtridf    -- Inverse to `chndtr` vs `df`.
+   chndtrinc    -- Inverse to `chndtr` vs `nc`.
+   chndtrix     -- Inverse to `chndtr` vs `x`.
+
+Kolmogorov distribution
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   smirnov      -- Kolmogorov-Smirnov complementary cumulative distribution function.
+   smirnovi     -- Inverse to `smirnov`.
+   kolmogorov   -- Complementary cumulative distribution function of Kolmogorov distribution.
+   kolmogi      -- Inverse function to `kolmogorov`.
+
+Box-Cox transformation
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   boxcox       -- Compute the Box-Cox transformation.
+   boxcox1p     -- Compute the Box-Cox transformation of 1 + `x`.
+   inv_boxcox   -- Compute the inverse of the Box-Cox transformation.
+   inv_boxcox1p -- Compute the inverse of the Box-Cox transformation.
+
+
+Sigmoidal functions
+^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   logit        -- Logit ufunc for ndarrays.
+   expit        -- Logistic sigmoid function.
+   log_expit    -- Logarithm of the logistic sigmoid function.
+
+Miscellaneous
+^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   tklmbda      -- Tukey-Lambda cumulative distribution function.
+   owens_t      -- Owen's T Function.
+
+
+Information Theory functions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   entr         -- Elementwise function for computing entropy.
+   rel_entr     -- Elementwise function for computing relative entropy.
+   kl_div       -- Elementwise function for computing Kullback-Leibler divergence.
+   huber        -- Huber loss function.
+   pseudo_huber -- Pseudo-Huber loss function.
+
+
+Gamma and related functions
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   gamma        -- Gamma function.
+   gammaln      -- Logarithm of the absolute value of the Gamma function for real inputs.
+   loggamma     -- Principal branch of the logarithm of the Gamma function.
+   gammasgn     -- Sign of the gamma function.
+   gammainc     -- Regularized lower incomplete gamma function.
+   gammaincinv  -- Inverse to `gammainc`.
+   gammaincc    -- Regularized upper incomplete gamma function.
+   gammainccinv -- Inverse to `gammaincc`.
+   beta         -- Beta function.
+   betaln       -- Natural logarithm of absolute value of beta function.
+   betainc      -- Incomplete beta integral.
+   betaincc     -- Complemented incomplete beta integral.
+   betaincinv   -- Inverse function to beta integral.
+   betainccinv  -- Inverse of the complemented incomplete beta integral.
+   psi          -- The digamma function.
+   rgamma       -- Gamma function inverted.
+   polygamma    -- Polygamma function n.
+   multigammaln -- Returns the log of multivariate gamma, also sometimes called the generalized gamma.
+   digamma      -- psi(x[, out]).
+   poch         -- Rising factorial (z)_m.
+
+Error function and Fresnel integrals
+------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   erf           -- Returns the error function of complex argument.
+   erfc          -- Complementary error function, ``1 - erf(x)``.
+   erfcx         -- Scaled complementary error function, ``exp(x**2) * erfc(x)``.
+   erfi          -- Imaginary error function, ``-i erf(i z)``.
+   erfinv        -- Inverse function for erf.
+   erfcinv       -- Inverse function for erfc.
+   wofz          -- Faddeeva function.
+   dawsn         -- Dawson's integral.
+   fresnel       -- Fresnel sin and cos integrals.
+   fresnel_zeros -- Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
+   modfresnelp   -- Modified Fresnel positive integrals.
+   modfresnelm   -- Modified Fresnel negative integrals.
+   voigt_profile -- Voigt profile.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   erf_zeros      -- Compute nt complex zeros of error function erf(z).
+   fresnelc_zeros -- Compute nt complex zeros of cosine Fresnel integral C(z).
+   fresnels_zeros -- Compute nt complex zeros of sine Fresnel integral S(z).
+
+Legendre functions
+------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   legendre_p                 -- Legendre polynomials of the first kind.
+   legendre_p_all             -- All Legendre polynomials of the first kind up to a specified order.
+   assoc_legendre_p           -- Associated Legendre polynomials of the first kind.
+   assoc_legendre_p_all       -- All associated Legendre polynomials of the first kind up to a specified order and degree.
+   sph_legendre_p             -- Spherical Legendre polynomials of the first kind.
+   sph_legendre_p_all         -- All spherical Legendre polynomials of the first kind up to a specified order and degree.
+   sph_harm_y                 -- Spherical harmonics.
+   sph_harm_y_all             -- All spherical harmonics up to a specified order and degree.
+
+The following functions are in the process of being deprecated in favor of the above,
+which provide a more flexible and consistent interface.
+
+.. autosummary::
+   :toctree: generated/
+
+   lpmv                       -- Associated Legendre function of integer order and real degree.
+   sph_harm                   -- Compute spherical harmonics.
+   clpmn                      -- Associated Legendre function of the first kind for complex arguments.
+   lpn                        -- Legendre function of the first kind.
+   lqn                        -- Legendre function of the second kind.
+   lpmn                       -- Sequence of associated Legendre functions of the first kind.
+   lqmn                       -- Sequence of associated Legendre functions of the second kind.
+
+Ellipsoidal harmonics
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   ellip_harm   -- Ellipsoidal harmonic functions E^p_n(l).
+   ellip_harm_2 -- Ellipsoidal harmonic functions F^p_n(l).
+   ellip_normal -- Ellipsoidal harmonic normalization constants gamma^p_n.
+
+Orthogonal polynomials
+----------------------
+
+The following functions evaluate values of orthogonal polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   assoc_laguerre   -- Compute the generalized (associated) Laguerre polynomial of degree n and order k.
+   eval_legendre    -- Evaluate Legendre polynomial at a point.
+   eval_chebyt      -- Evaluate Chebyshev polynomial of the first kind at a point.
+   eval_chebyu      -- Evaluate Chebyshev polynomial of the second kind at a point.
+   eval_chebyc      -- Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a point.
+   eval_chebys      -- Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a point.
+   eval_jacobi      -- Evaluate Jacobi polynomial at a point.
+   eval_laguerre    -- Evaluate Laguerre polynomial at a point.
+   eval_genlaguerre -- Evaluate generalized Laguerre polynomial at a point.
+   eval_hermite     -- Evaluate physicist's Hermite polynomial at a point.
+   eval_hermitenorm -- Evaluate probabilist's (normalized) Hermite polynomial at a point.
+   eval_gegenbauer  -- Evaluate Gegenbauer polynomial at a point.
+   eval_sh_legendre -- Evaluate shifted Legendre polynomial at a point.
+   eval_sh_chebyt   -- Evaluate shifted Chebyshev polynomial of the first kind at a point.
+   eval_sh_chebyu   -- Evaluate shifted Chebyshev polynomial of the second kind at a point.
+   eval_sh_jacobi   -- Evaluate shifted Jacobi polynomial at a point.
+
+The following functions compute roots and quadrature weights for
+orthogonal polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   roots_legendre    -- Gauss-Legendre quadrature.
+   roots_chebyt      -- Gauss-Chebyshev (first kind) quadrature.
+   roots_chebyu      -- Gauss-Chebyshev (second kind) quadrature.
+   roots_chebyc      -- Gauss-Chebyshev (first kind) quadrature.
+   roots_chebys      -- Gauss-Chebyshev (second kind) quadrature.
+   roots_jacobi      -- Gauss-Jacobi quadrature.
+   roots_laguerre    -- Gauss-Laguerre quadrature.
+   roots_genlaguerre -- Gauss-generalized Laguerre quadrature.
+   roots_hermite     -- Gauss-Hermite (physicist's) quadrature.
+   roots_hermitenorm -- Gauss-Hermite (statistician's) quadrature.
+   roots_gegenbauer  -- Gauss-Gegenbauer quadrature.
+   roots_sh_legendre -- Gauss-Legendre (shifted) quadrature.
+   roots_sh_chebyt   -- Gauss-Chebyshev (first kind, shifted) quadrature.
+   roots_sh_chebyu   -- Gauss-Chebyshev (second kind, shifted) quadrature.
+   roots_sh_jacobi   -- Gauss-Jacobi (shifted) quadrature.
+
+The functions below, in turn, return the polynomial coefficients in
+``orthopoly1d`` objects, which function similarly as `numpy.poly1d`.
+The ``orthopoly1d`` class also has an attribute ``weights``, which returns
+the roots, weights, and total weights for the appropriate form of Gaussian
+quadrature. These are returned in an ``n x 3`` array with roots in the first
+column, weights in the second column, and total weights in the final column.
+Note that ``orthopoly1d`` objects are converted to `~numpy.poly1d` when doing
+arithmetic, and lose information of the original orthogonal polynomial.
+
+.. autosummary::
+   :toctree: generated/
+
+   legendre    -- Legendre polynomial.
+   chebyt      -- Chebyshev polynomial of the first kind.
+   chebyu      -- Chebyshev polynomial of the second kind.
+   chebyc      -- Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+   chebys      -- Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+   jacobi      -- Jacobi polynomial.
+   laguerre    -- Laguerre polynomial.
+   genlaguerre -- Generalized (associated) Laguerre polynomial.
+   hermite     -- Physicist's Hermite polynomial.
+   hermitenorm -- Normalized (probabilist's) Hermite polynomial.
+   gegenbauer  -- Gegenbauer (ultraspherical) polynomial.
+   sh_legendre -- Shifted Legendre polynomial.
+   sh_chebyt   -- Shifted Chebyshev polynomial of the first kind.
+   sh_chebyu   -- Shifted Chebyshev polynomial of the second kind.
+   sh_jacobi   -- Shifted Jacobi polynomial.
+
+.. warning::
+
+   Computing values of high-order polynomials (around ``order > 20``) using
+   polynomial coefficients is numerically unstable. To evaluate polynomial
+   values, the ``eval_*`` functions should be used instead.
+
+
+Hypergeometric functions
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   hyp2f1 -- Gauss hypergeometric function 2F1(a, b; c; z).
+   hyp1f1 -- Confluent hypergeometric function 1F1(a, b; x).
+   hyperu -- Confluent hypergeometric function U(a, b, x) of the second kind.
+   hyp0f1 -- Confluent hypergeometric limit function 0F1.
+
+
+Parabolic cylinder functions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   pbdv -- Parabolic cylinder function D.
+   pbvv -- Parabolic cylinder function V.
+   pbwa -- Parabolic cylinder function W.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   pbdv_seq -- Parabolic cylinder functions Dv(x) and derivatives.
+   pbvv_seq -- Parabolic cylinder functions Vv(x) and derivatives.
+   pbdn_seq -- Parabolic cylinder functions Dn(z) and derivatives.
+
+Mathieu and related functions
+-----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_a -- Characteristic value of even Mathieu functions.
+   mathieu_b -- Characteristic value of odd Mathieu functions.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_even_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
+   mathieu_odd_coef  -- Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+The following return both function and first derivative:
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_cem     -- Even Mathieu function and its derivative.
+   mathieu_sem     -- Odd Mathieu function and its derivative.
+   mathieu_modcem1 -- Even modified Mathieu function of the first kind and its derivative.
+   mathieu_modcem2 -- Even modified Mathieu function of the second kind and its derivative.
+   mathieu_modsem1 -- Odd modified Mathieu function of the first kind and its derivative.
+   mathieu_modsem2 -- Odd modified Mathieu function of the second kind and its derivative.
+
+Spheroidal wave functions
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   pro_ang1   -- Prolate spheroidal angular function of the first kind and its derivative.
+   pro_rad1   -- Prolate spheroidal radial function of the first kind and its derivative.
+   pro_rad2   -- Prolate spheroidal radial function of the second kind and its derivative.
+   obl_ang1   -- Oblate spheroidal angular function of the first kind and its derivative.
+   obl_rad1   -- Oblate spheroidal radial function of the first kind and its derivative.
+   obl_rad2   -- Oblate spheroidal radial function of the second kind and its derivative.
+   pro_cv     -- Characteristic value of prolate spheroidal function.
+   obl_cv     -- Characteristic value of oblate spheroidal function.
+   pro_cv_seq -- Characteristic values for prolate spheroidal wave functions.
+   obl_cv_seq -- Characteristic values for oblate spheroidal wave functions.
+
+The following functions require pre-computed characteristic value:
+
+.. autosummary::
+   :toctree: generated/
+
+   pro_ang1_cv -- Prolate spheroidal angular function pro_ang1 for precomputed characteristic value.
+   pro_rad1_cv -- Prolate spheroidal radial function pro_rad1 for precomputed characteristic value.
+   pro_rad2_cv -- Prolate spheroidal radial function pro_rad2 for precomputed characteristic value.
+   obl_ang1_cv -- Oblate spheroidal angular function obl_ang1 for precomputed characteristic value.
+   obl_rad1_cv -- Oblate spheroidal radial function obl_rad1 for precomputed characteristic value.
+   obl_rad2_cv -- Oblate spheroidal radial function obl_rad2 for precomputed characteristic value.
+
+Kelvin functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   kelvin       -- Kelvin functions as complex numbers.
+   kelvin_zeros -- Compute nt zeros of all Kelvin functions.
+   ber          -- Kelvin function ber.
+   bei          -- Kelvin function bei
+   berp         -- Derivative of the Kelvin function `ber`.
+   beip         -- Derivative of the Kelvin function `bei`.
+   ker          -- Kelvin function ker.
+   kei          -- Kelvin function ker.
+   kerp         -- Derivative of the Kelvin function ker.
+   keip         -- Derivative of the Kelvin function kei.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   ber_zeros  -- Compute nt zeros of the Kelvin function ber(x).
+   bei_zeros  -- Compute nt zeros of the Kelvin function bei(x).
+   berp_zeros -- Compute nt zeros of the Kelvin function ber'(x).
+   beip_zeros -- Compute nt zeros of the Kelvin function bei'(x).
+   ker_zeros  -- Compute nt zeros of the Kelvin function ker(x).
+   kei_zeros  -- Compute nt zeros of the Kelvin function kei(x).
+   kerp_zeros -- Compute nt zeros of the Kelvin function ker'(x).
+   keip_zeros -- Compute nt zeros of the Kelvin function kei'(x).
+
+Combinatorics
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   comb -- The number of combinations of N things taken k at a time.
+   perm -- Permutations of N things taken k at a time, i.e., k-permutations of N.
+   stirling2 -- Stirling numbers of the second kind.
+
+Lambert W and related functions
+-------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambertw    -- Lambert W function.
+   wrightomega -- Wright Omega function.
+
+Other special functions
+-----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   agm         -- Arithmetic, Geometric Mean.
+   bernoulli   -- Bernoulli numbers B0..Bn (inclusive).
+   binom       -- Binomial coefficient
+   diric       -- Periodic sinc function, also called the Dirichlet function.
+   euler       -- Euler numbers E0..En (inclusive).
+   expn        -- Exponential integral E_n.
+   exp1        -- Exponential integral E_1 of complex argument z.
+   expi        -- Exponential integral Ei.
+   factorial   -- The factorial of a number or array of numbers.
+   factorial2  -- Double factorial.
+   factorialk  -- Multifactorial of n of order k, n(!!...!).
+   shichi      -- Hyperbolic sine and cosine integrals.
+   sici        -- Sine and cosine integrals.
+   softmax     -- Softmax function.
+   log_softmax -- Logarithm of softmax function.
+   spence      -- Spence's function, also known as the dilogarithm.
+   zeta        -- Riemann zeta function.
+   zetac       -- Riemann zeta function minus 1.
+   softplus    -- Softplus function.
+
+Convenience functions
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   cbrt      -- Cube root of `x`.
+   exp10     -- 10**x.
+   exp2      -- 2**x.
+   radian    -- Convert from degrees to radians.
+   cosdg     -- Cosine of the angle `x` given in degrees.
+   sindg     -- Sine of angle given in degrees.
+   tandg     -- Tangent of angle x given in degrees.
+   cotdg     -- Cotangent of the angle `x` given in degrees.
+   log1p     -- Calculates log(1+x) for use when `x` is near zero.
+   expm1     -- ``exp(x) - 1`` for use when `x` is near zero.
+   cosm1     -- ``cos(x) - 1`` for use when `x` is near zero.
+   powm1     -- ``x**y - 1`` for use when `y` is near zero or `x` is near 1.
+   round     -- Round to nearest integer.
+   xlogy     -- Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
+   xlog1py   -- Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
+   logsumexp -- Compute the log of the sum of exponentials of input elements.
+   exprel    -- Relative error exponential, (exp(x)-1)/x, for use when `x` is near zero.
+   sinc      -- Return the sinc function.
+
+"""  # noqa: E501
+
+import os
+import warnings
+
+
+def _load_libsf_error_state():
+    """Load libsf_error_state.dll shared library on Windows
+
+    libsf_error_state manages shared state used by
+    ``scipy.special.seterr`` and ``scipy.special.geterr`` so that these
+    can work consistently between special functions provided by different
+    extension modules. This shared library is installed in scipy/special
+    alongside this __init__.py file. Due to lack of rpath support, Windows
+    cannot find shared libraries installed within wheels. To circumvent this,
+    we pre-load ``lib_sf_error_state.dll`` when on Windows.
+
+    The logic for this function was borrowed from the function ``make_init``
+    in `scipy/tools/openblas_support.py`:
+    https://github.com/scipy/scipy/blob/bb92c8014e21052e7dde67a76b28214dd1dcb94a/tools/openblas_support.py#L239-L274
+    """  # noqa: E501
+    if os.name == "nt":
+        try:
+            from ctypes import WinDLL
+            basedir = os.path.dirname(__file__)
+        except:  # noqa: E722
+            pass
+        else:
+            dll_path = os.path.join(basedir, "libsf_error_state.dll")
+            if os.path.exists(dll_path):
+                WinDLL(dll_path)
+
+
+_load_libsf_error_state()
+
+
+from ._sf_error import SpecialFunctionWarning, SpecialFunctionError
+
+from . import _ufuncs
+from ._ufuncs import *
+
+# Replace some function definitions from _ufuncs to add Array API support
+from ._support_alternative_backends import (
+    log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln,
+    gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy,
+    chdtr, chdtrc, betainc, betaincc, stdtr)
+
+from . import _basic
+from ._basic import *
+
+from ._logsumexp import logsumexp, softmax, log_softmax
+
+from . import _multiufuncs
+from ._multiufuncs import *
+
+from . import _orthogonal
+from ._orthogonal import *
+
+from ._spfun_stats import multigammaln
+from ._ellip_harm import (
+    ellip_harm,
+    ellip_harm_2,
+    ellip_normal
+)
+from ._lambertw import lambertw
+from ._spherical_bessel import (
+    spherical_jn,
+    spherical_yn,
+    spherical_in,
+    spherical_kn
+)
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import add_newdocs, basic, orthogonal, specfun, sf_error, spfun_stats
+
+# We replace some function definitions from _ufuncs with those from
+# _support_alternative_backends above, but those are all listed in _ufuncs.__all__,
+# so there is no need to consider _support_alternative_backends.__all__ here.
+__all__ = _ufuncs.__all__ + _basic.__all__ + _orthogonal.__all__ + _multiufuncs.__all__
+__all__ += [
+    'SpecialFunctionWarning',
+    'SpecialFunctionError',
+    'logsumexp',
+    'softmax',
+    'log_softmax',
+    'multigammaln',
+    'ellip_harm',
+    'ellip_harm_2',
+    'ellip_normal',
+    'lambertw',
+    'spherical_jn',
+    'spherical_yn',
+    'spherical_in',
+    'spherical_kn',
+]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
+
+
+def _get_include():
+    """This function is for development purposes only.
+
+    This function could disappear or its behavior could change at any time.
+    """
+    import os
+    return os.path.dirname(__file__)
+
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b1e218a3130ddc4974384eda0c62b611189bc4a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b7b090a7702055e555814a13fb493373318887b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bd774b3db8a9deff8e610f400b69fcd093062f6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3de700cd227566ea3d52909a1cd39398289acaad
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f4971fdcddf5730242bfae9132b7dca1328d1280
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..803e903315f1cdbceb4d062021551cc15444bbb6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa0b32365e0eb12dff093358d9ca7d0442847ca8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b8a480d3c063dc4b7b746222600eddc64e05375
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68d7aa00f749a4d06a9c548ad9fd1708ea33436f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c3753fd7e009d96f46443384ea7aa4b9c1da006
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..528327daa81cd52be81b55b3dd07e14697f5d2cb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e368e9abbcde0f6ab544356f190f4fa37cfa6f44
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..526c4ae555fd42b21bef246fd7dfdd8cf1d9d102
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a16990a86a925f63883cde8967d6d3e16aea3f4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a068a0f589e1d6836b3ef5c735489e4e3a51fc3e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee9e63457e19ff70574f3654e85444e74a53f3ac
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aaffd1785c995d8a10397e6230c3ec614a8dcf31
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df2f12f234eae5536c2ef783fa930286bc5f750e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62f0cdae4de78e5875e6cb0ffa3c8a18717c53e3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py b/venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..134604c90128a59d48dee66318fa6fd02308f80c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py
@@ -0,0 +1,10699 @@
+# Docstrings for generated ufuncs
+#
+# The syntax is designed to look like the function add_newdoc is being
+# called from numpy.lib, but in this file add_newdoc puts the
+# docstrings in a dictionary. This dictionary is used in
+# _generate_pyx.py to generate the docstrings for the ufuncs in
+# scipy.special at the C level when the ufuncs are created at compile
+# time.
+
+docdict: dict[str, str] = {}
+
+
+def get(name):
+    return docdict.get(name)
+
+
+def add_newdoc(name, doc):
+    docdict[name] = doc
+
+
+add_newdoc("_sf_error_test_function",
+    """
+    Private function; do not use.
+    """)
+
+
+add_newdoc("_cosine_cdf",
+    """
+    _cosine_cdf(x)
+
+    Cumulative distribution function (CDF) of the cosine distribution::
+
+                 {             0,              x < -pi
+        cdf(x) = { (pi + x + sin(x))/(2*pi),   -pi <= x <= pi
+                 {             1,              x > pi
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+
+    Returns
+    -------
+    scalar or ndarray
+        The cosine distribution CDF evaluated at `x`.
+
+    """)
+
+add_newdoc("_cosine_invcdf",
+    """
+    _cosine_invcdf(p)
+
+    Inverse of the cumulative distribution function (CDF) of the cosine
+    distribution.
+
+    The CDF of the cosine distribution is::
+
+        cdf(x) = (pi + x + sin(x))/(2*pi)
+
+    This function computes the inverse of cdf(x).
+
+    Parameters
+    ----------
+    p : array_like
+        `p` must contain real numbers in the interval ``0 <= p <= 1``.
+        `nan` is returned for values of `p` outside the interval [0, 1].
+
+    Returns
+    -------
+    scalar or ndarray
+        The inverse of the cosine distribution CDF evaluated at `p`.
+
+    """)
+
+add_newdoc("_ellip_harm",
+    """
+    Internal function, use `ellip_harm` instead.
+    """)
+
+add_newdoc("_ellip_norm",
+    """
+    Internal function, use `ellip_norm` instead.
+    """)
+
+add_newdoc("voigt_profile",
+    r"""
+    voigt_profile(x, sigma, gamma, out=None)
+
+    Voigt profile.
+
+    The Voigt profile is a convolution of a 1-D Normal distribution with
+    standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at
+    half-maximum ``gamma``.
+
+    If ``sigma = 0``, PDF of Cauchy distribution is returned.
+    Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.
+    If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,
+    and ``0`` for all other ``x``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument
+    sigma : array_like
+        The standard deviation of the Normal distribution part
+    gamma : array_like
+        The half-width at half-maximum of the Cauchy distribution part
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The Voigt profile at the given arguments
+
+    See Also
+    --------
+    wofz : Faddeeva function
+
+    Notes
+    -----
+    It can be expressed in terms of Faddeeva function
+
+    .. math:: V(x; \sigma, \gamma) = \frac{Re[w(z)]}{\sigma\sqrt{2\pi}},
+    .. math:: z = \frac{x + i\gamma}{\sqrt{2}\sigma}
+
+    where :math:`w(z)` is the Faddeeva function.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Voigt_profile
+
+    Examples
+    --------
+    Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.
+
+    >>> from scipy.special import voigt_profile
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> voigt_profile(2, 1., 1.)
+    0.09071519942627544
+
+    Calculate the function at several points by providing a NumPy array
+    for `x`.
+
+    >>> values = np.array([-2., 0., 5])
+    >>> voigt_profile(values, 1., 1.)
+    array([0.0907152 , 0.20870928, 0.01388492])
+
+    Plot the function for different parameter sets.
+
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> x = np.linspace(-10, 10, 500)
+    >>> parameters_list = [(1.5, 0., "solid"), (1.3, 0.5, "dashed"),
+    ...                    (0., 1.8, "dotted"), (1., 1., "dashdot")]
+    >>> for params in parameters_list:
+    ...     sigma, gamma, linestyle = params
+    ...     voigt = voigt_profile(x, sigma, gamma)
+    ...     ax.plot(x, voigt, label=rf"$\sigma={sigma},\, \gamma={gamma}$",
+    ...             ls=linestyle)
+    >>> ax.legend()
+    >>> plt.show()
+
+    Verify visually that the Voigt profile indeed arises as the convolution
+    of a normal and a Cauchy distribution.
+
+    >>> from scipy.signal import convolve
+    >>> x, dx = np.linspace(-10, 10, 500, retstep=True)
+    >>> def gaussian(x, sigma):
+    ...     return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))
+    >>> def cauchy(x, gamma):
+    ...     return gamma/(np.pi * (np.square(x)+gamma**2))
+    >>> sigma = 2
+    >>> gamma = 1
+    >>> gauss_profile = gaussian(x, sigma)
+    >>> cauchy_profile = cauchy(x, gamma)
+    >>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode="same")
+    >>> voigt = voigt_profile(x, sigma, gamma)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> ax.plot(x, gauss_profile, label="Gauss: $G$", c='b')
+    >>> ax.plot(x, cauchy_profile, label="Cauchy: $C$", c='y', ls="dashed")
+    >>> xx = 0.5*(x[1:] + x[:-1])  # midpoints
+    >>> ax.plot(xx, convolved[1:], label="Convolution: $G * C$", ls='dashdot',
+    ...         c='k')
+    >>> ax.plot(x, voigt, label="Voigt", ls='dotted', c='r')
+    >>> ax.legend()
+    >>> plt.show()
+    """)
+
+add_newdoc("wrightomega",
+    r"""
+    wrightomega(z, out=None)
+
+    Wright Omega function.
+
+    Defined as the solution to
+
+    .. math::
+
+        \omega + \log(\omega) = z
+
+    where :math:`\log` is the principal branch of the complex logarithm.
+
+    Parameters
+    ----------
+    z : array_like
+        Points at which to evaluate the Wright Omega function
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    omega : scalar or ndarray
+        Values of the Wright Omega function
+
+    See Also
+    --------
+    lambertw : The Lambert W function
+
+    Notes
+    -----
+    .. versionadded:: 0.19.0
+
+    The function can also be defined as
+
+    .. math::
+
+        \omega(z) = W_{K(z)}(e^z)
+
+    where :math:`K(z) = \lceil (\Im(z) - \pi)/(2\pi) \rceil` is the
+    unwinding number and :math:`W` is the Lambert W function.
+
+    The implementation here is taken from [1]_.
+
+    References
+    ----------
+    .. [1] Lawrence, Corless, and Jeffrey, "Algorithm 917: Complex
+           Double-Precision Evaluation of the Wright :math:`\omega`
+           Function." ACM Transactions on Mathematical Software,
+           2012. :doi:`10.1145/2168773.2168779`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import wrightomega, lambertw
+
+    >>> wrightomega([-2, -1, 0, 1, 2])
+    array([0.12002824, 0.27846454, 0.56714329, 1.        , 1.5571456 ])
+
+    Complex input:
+
+    >>> wrightomega(3 + 5j)
+    (1.5804428632097158+3.8213626783287937j)
+
+    Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:
+
+    >>> w = -5 + 4j
+    >>> wrightomega(w + np.log(w))
+    (-5+4j)
+
+    Verify the connection to ``lambertw``:
+
+    >>> z = 0.5 + 3j
+    >>> wrightomega(z)
+    (0.0966015889280649+1.4937828458191993j)
+    >>> lambertw(np.exp(z))
+    (0.09660158892806493+1.4937828458191993j)
+
+    >>> z = 0.5 + 4j
+    >>> wrightomega(z)
+    (-0.3362123489037213+2.282986001579032j)
+    >>> lambertw(np.exp(z), k=1)
+    (-0.33621234890372115+2.282986001579032j)
+    """)
+
+
+add_newdoc("agm",
+    """
+    agm(a, b, out=None)
+
+    Compute the arithmetic-geometric mean of `a` and `b`.
+
+    Start with a_0 = a and b_0 = b and iteratively compute::
+
+        a_{n+1} = (a_n + b_n)/2
+        b_{n+1} = sqrt(a_n*b_n)
+
+    a_n and b_n converge to the same limit as n increases; their common
+    limit is agm(a, b).
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real values only. If the values are both negative, the result
+        is negative. If one value is negative and the other is positive,
+        `nan` is returned.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The arithmetic-geometric mean of `a` and `b`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import agm
+    >>> a, b = 24.0, 6.0
+    >>> agm(a, b)
+    13.458171481725614
+
+    Compare that result to the iteration:
+
+    >>> while a != b:
+    ...     a, b = (a + b)/2, np.sqrt(a*b)
+    ...     print("a = %19.16f  b=%19.16f" % (a, b))
+    ...
+    a = 15.0000000000000000  b=12.0000000000000000
+    a = 13.5000000000000000  b=13.4164078649987388
+    a = 13.4582039324993694  b=13.4581390309909850
+    a = 13.4581714817451772  b=13.4581714817060547
+    a = 13.4581714817256159  b=13.4581714817256159
+
+    When array-like arguments are given, broadcasting applies:
+
+    >>> a = np.array([[1.5], [3], [6]])  # a has shape (3, 1).
+    >>> b = np.array([6, 12, 24, 48])    # b has shape (4,).
+    >>> agm(a, b)
+    array([[  3.36454287,   5.42363427,   9.05798751,  15.53650756],
+           [  4.37037309,   6.72908574,  10.84726853,  18.11597502],
+           [  6.        ,   8.74074619,  13.45817148,  21.69453707]])
+    """)
+
+add_newdoc("airy",
+    r"""
+    airy(z, out=None)
+
+    Airy functions and their derivatives.
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex argument.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    Ai, Aip, Bi, Bip : 4-tuple of scalar or ndarray
+        Airy functions Ai and Bi, and their derivatives Aip and Bip.
+
+    See Also
+    --------
+    airye : exponentially scaled Airy functions.
+
+    Notes
+    -----
+    The Airy functions Ai and Bi are two independent solutions of
+
+    .. math:: y''(x) = x y(x).
+
+    For real `z` in [-10, 10], the computation is carried out by calling
+    the Cephes [1]_ `airy` routine, which uses power series summation
+    for small `z` and rational minimax approximations for large `z`.
+
+    Outside this range, the AMOS [2]_ `zairy` and `zbiry` routines are
+    employed.  They are computed using power series for :math:`|z| < 1` and
+    the following relations to modified Bessel functions for larger `z`
+    (where :math:`t \equiv 2 z^{3/2}/3`):
+
+    .. math::
+
+        Ai(z) = \frac{1}{\pi \sqrt{3}} K_{1/3}(t)
+
+        Ai'(z) = -\frac{z}{\pi \sqrt{3}} K_{2/3}(t)
+
+        Bi(z) = \sqrt{\frac{z}{3}} \left(I_{-1/3}(t) + I_{1/3}(t) \right)
+
+        Bi'(z) = \frac{z}{\sqrt{3}} \left(I_{-2/3}(t) + I_{2/3}(t)\right)
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compute the Airy functions on the interval [-15, 5].
+
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> x = np.linspace(-15, 5, 201)
+    >>> ai, aip, bi, bip = special.airy(x)
+
+    Plot Ai(x) and Bi(x).
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x, ai, 'r', label='Ai(x)')
+    >>> plt.plot(x, bi, 'b--', label='Bi(x)')
+    >>> plt.ylim(-0.5, 1.0)
+    >>> plt.grid()
+    >>> plt.legend(loc='upper left')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("airye",
+    """
+    airye(z, out=None)
+
+    Exponentially scaled Airy functions and their derivatives.
+
+    Scaling::
+
+        eAi  = Ai  * exp(2.0/3.0*z*sqrt(z))
+        eAip = Aip * exp(2.0/3.0*z*sqrt(z))
+        eBi  = Bi  * exp(-abs(2.0/3.0*(z*sqrt(z)).real))
+        eBip = Bip * exp(-abs(2.0/3.0*(z*sqrt(z)).real))
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex argument.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    eAi, eAip, eBi, eBip : 4-tuple of scalar or ndarray
+        Exponentially scaled Airy functions eAi and eBi, and their derivatives
+        eAip and eBip
+
+    See Also
+    --------
+    airy
+
+    Notes
+    -----
+    Wrapper for the AMOS [1]_ routines `zairy` and `zbiry`.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    We can compute exponentially scaled Airy functions and their derivatives:
+
+    >>> import numpy as np
+    >>> from scipy.special import airye
+    >>> import matplotlib.pyplot as plt
+    >>> z = np.linspace(0, 50, 500)
+    >>> eAi, eAip, eBi, eBip = airye(z)
+    >>> f, ax = plt.subplots(2, 1, sharex=True)
+    >>> for ind, data in enumerate([[eAi, eAip, ["eAi", "eAip"]],
+    ...                             [eBi, eBip, ["eBi", "eBip"]]]):
+    ...     ax[ind].plot(z, data[0], "-r", z, data[1], "-b")
+    ...     ax[ind].legend(data[2])
+    ...     ax[ind].grid(True)
+    >>> plt.show()
+
+    We can compute these using usual non-scaled Airy functions by:
+
+    >>> from scipy.special import airy
+    >>> Ai, Aip, Bi, Bip = airy(z)
+    >>> np.allclose(eAi, Ai * np.exp(2.0 / 3.0 * z * np.sqrt(z)))
+    True
+    >>> np.allclose(eAip, Aip * np.exp(2.0 / 3.0 * z * np.sqrt(z)))
+    True
+    >>> np.allclose(eBi, Bi * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z)))))
+    True
+    >>> np.allclose(eBip, Bip * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z)))))
+    True
+
+    Comparing non-scaled and exponentially scaled ones, the usual non-scaled
+    function quickly underflows for large values, whereas the exponentially
+    scaled function does not.
+
+    >>> airy(200)
+    (0.0, 0.0, nan, nan)
+    >>> airye(200)
+    (0.07501041684381093, -1.0609012305109042, 0.15003188417418148, 2.1215836725571093)
+
+    """)
+
+add_newdoc("bdtr",
+    r"""
+    bdtr(k, n, p, out=None)
+
+    Binomial distribution cumulative distribution function.
+
+    Sum of the terms 0 through `floor(k)` of the Binomial probability density.
+
+    .. math::
+        \mathrm{bdtr}(k, n, p) =
+        \sum_{j=0}^{\lfloor k \rfloor} {{n}\choose{j}} p^j (1-p)^{n-j}
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (double), rounded down to the nearest integer.
+    n : array_like
+        Number of events (int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Probability of `floor(k)` or fewer successes in `n` independent events with
+        success probabilities of `p`.
+
+    Notes
+    -----
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{bdtr}(k, n, p) =
+        I_{1 - p}(n - \lfloor k \rfloor, \lfloor k \rfloor + 1).
+
+    Wrapper for the Cephes [1]_ routine `bdtr`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    """)
+
+add_newdoc("bdtrc",
+    r"""
+    bdtrc(k, n, p, out=None)
+
+    Binomial distribution survival function.
+
+    Sum of the terms `floor(k) + 1` through `n` of the binomial probability
+    density,
+
+    .. math::
+        \mathrm{bdtrc}(k, n, p) =
+        \sum_{j=\lfloor k \rfloor +1}^n {{n}\choose{j}} p^j (1-p)^{n-j}
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (double), rounded down to nearest integer.
+    n : array_like
+        Number of events (int)
+    p : array_like
+        Probability of success in a single event.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Probability of `floor(k) + 1` or more successes in `n` independent
+        events with success probabilities of `p`.
+
+    See Also
+    --------
+    bdtr
+    betainc
+
+    Notes
+    -----
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{bdtrc}(k, n, p) = I_{p}(\lfloor k \rfloor + 1, n - \lfloor k \rfloor).
+
+    Wrapper for the Cephes [1]_ routine `bdtrc`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    """)
+
+add_newdoc("bdtri",
+    r"""
+    bdtri(k, n, y, out=None)
+
+    Inverse function to `bdtr` with respect to `p`.
+
+    Finds the event probability `p` such that the sum of the terms 0 through
+    `k` of the binomial probability density is equal to the given cumulative
+    probability `y`.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (float), rounded down to the nearest integer.
+    n : array_like
+        Number of events (float)
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    p : scalar or ndarray
+        The event probability such that `bdtr(\lfloor k \rfloor, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+    betaincinv
+
+    Notes
+    -----
+    The computation is carried out using the inverse beta integral function
+    and the relation,::
+
+        1 - p = betaincinv(n - k, k + 1, y).
+
+    Wrapper for the Cephes [1]_ routine `bdtri`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    """)
+
+add_newdoc("bdtrik",
+    """
+    bdtrik(y, n, p, out=None)
+
+    Inverse function to `bdtr` with respect to `k`.
+
+    Finds the number of successes `k` such that the sum of the terms 0 through
+    `k` of the Binomial probability density for `n` events with probability
+    `p` is equal to the given cumulative probability `y`.
+
+    Parameters
+    ----------
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    n : array_like
+        Number of events (float).
+    p : array_like
+        Success probability (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    k : scalar or ndarray
+        The number of successes `k` such that `bdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+
+    Notes
+    -----
+    Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the
+    cumulative incomplete beta distribution.
+
+    Computation of `k` involves a search for a value that produces the desired
+    value of `y`. The search relies on the monotonicity of `y` with `k`.
+
+    Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [2] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+
+    """)
+
+add_newdoc("bdtrin",
+    """
+    bdtrin(k, y, p, out=None)
+
+    Inverse function to `bdtr` with respect to `n`.
+
+    Finds the number of events `n` such that the sum of the terms 0 through
+    `k` of the Binomial probability density for events with probability `p` is
+    equal to the given cumulative probability `y`.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (float).
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    p : array_like
+        Success probability (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    n : scalar or ndarray
+        The number of events `n` such that `bdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+
+    Notes
+    -----
+    Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the
+    cumulative incomplete beta distribution.
+
+    Computation of `n` involves a search for a value that produces the desired
+    value of `y`. The search relies on the monotonicity of `y` with `n`.
+
+    Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [2] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    """)
+
+add_newdoc("btdtria",
+    r"""
+    btdtria(p, b, x, out=None)
+
+    Inverse of `betainc` with respect to `a`.
+
+    This is the inverse of the beta cumulative distribution function, `betainc`,
+    considered as a function of `a`, returning the value of `a` for which
+    `betainc(a, b, x) = p`, or
+
+    .. math::
+        p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt
+
+    Parameters
+    ----------
+    p : array_like
+        Cumulative probability, in [0, 1].
+    b : array_like
+        Shape parameter (`b` > 0).
+    x : array_like
+        The quantile, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    a : scalar or ndarray
+        The value of the shape parameter `a` such that `betainc(a, b, x) = p`.
+
+    See Also
+    --------
+    btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `a` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `a`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Algorithm 708: Significant Digit Computation of the Incomplete Beta
+           Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.
+
+    """)
+
+add_newdoc("btdtrib",
+    r"""
+    btdtria(a, p, x, out=None)
+
+    Inverse of `betainc` with respect to `b`.
+
+    This is the inverse of the beta cumulative distribution function, `betainc`,
+    considered as a function of `b`, returning the value of `b` for which
+    `betainc(a, b, x) = p`, or
+
+    .. math::
+        p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt
+
+    Parameters
+    ----------
+    a : array_like
+        Shape parameter (`a` > 0).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    x : array_like
+        The quantile, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    b : scalar or ndarray
+        The value of the shape parameter `b` such that `betainc(a, b, x) = p`.
+
+    See Also
+    --------
+    btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `b` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `b`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Algorithm 708: Significant Digit Computation of the Incomplete Beta
+           Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.
+
+
+    """)
+
+add_newdoc(
+    "betainc",
+    r"""
+    betainc(a, b, x, out=None)
+
+    Regularized incomplete beta function.
+
+    Computes the regularized incomplete beta function, defined as [1]_:
+
+    .. math::
+
+        I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x
+        t^{a-1}(1-t)^{b-1}dt,
+
+    for :math:`0 \leq x \leq 1`.
+
+    This function is the cumulative distribution function for the beta
+    distribution; its range is [0, 1].
+
+    Parameters
+    ----------
+    a, b : array_like
+           Positive, real-valued parameters
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the regularized incomplete beta function
+
+    See Also
+    --------
+    beta : beta function
+    betaincinv : inverse of the regularized incomplete beta function
+    betaincc : complement of the regularized incomplete beta function
+    scipy.stats.beta : beta distribution
+
+    Notes
+    -----
+    The term *regularized* in the name of this function refers to the
+    scaling of the function by the gamma function terms shown in the
+    formula.  When not qualified as *regularized*, the name *incomplete
+    beta function* often refers to just the integral expression,
+    without the gamma terms.  One can use the function `beta` from
+    `scipy.special` to get this "nonregularized" incomplete beta
+    function by multiplying the result of ``betainc(a, b, x)`` by
+    ``beta(a, b)``.
+
+    This function wraps the ``ibeta`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+
+    Let :math:`B(a, b)` be the `beta` function.
+
+    >>> import scipy.special as sc
+
+    The coefficient in terms of `gamma` is equal to
+    :math:`1/B(a, b)`. Also, when :math:`x=1`
+    the integral is equal to :math:`B(a, b)`.
+    Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.
+
+    >>> sc.betainc(0.2, 3.5, 1.0)
+    1.0
+
+    It satisfies
+    :math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,
+    where :math:`F` is the hypergeometric function `hyp2f1`:
+
+    >>> a, b, x = 1.4, 3.1, 0.5
+    >>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))
+    0.8148904036225295
+    >>> sc.betainc(a, b, x)
+    0.8148904036225296
+
+    This functions satisfies the relationship
+    :math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:
+
+    >>> sc.betainc(2.2, 3.1, 0.4)
+    0.49339638807619446
+    >>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)
+    0.49339638807619446
+
+    """)
+
+
+add_newdoc(
+    "betaincc",
+    r"""
+    betaincc(a, b, x, out=None)
+
+    Complement of the regularized incomplete beta function.
+
+    Computes the complement of the regularized incomplete beta function,
+    defined as [1]_:
+
+    .. math::
+
+        \bar{I}_x(a, b) = 1 - I_x(a, b)
+                        = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x
+                                  t^{a-1}(1-t)^{b-1}dt,
+
+    for :math:`0 \leq x \leq 1`.
+
+    Parameters
+    ----------
+    a, b : array_like
+           Positive, real-valued parameters
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    betaincinv : inverse of the regularized incomplete beta function
+    betainccinv :
+        inverse of the complement of the regularized incomplete beta function
+    beta : beta function
+    scipy.stats.beta : beta distribution
+
+    Notes
+    -----
+    .. versionadded:: 1.11.0
+
+    This function wraps the ``ibetac`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import betaincc, betainc
+
+    The naive calculation ``1 - betainc(a, b, x)`` loses precision when
+    the values of ``betainc(a, b, x)`` are close to 1:
+
+    >>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])
+    array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])
+
+    By using ``betaincc``, we get the correct values:
+
+    >>> betaincc(0.5, 8, [0.9, 0.99, 0.999])
+    array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])
+
+    """)
+
+add_newdoc(
+    "betaincinv",
+    r"""
+    betaincinv(a, b, y, out=None)
+
+    Inverse of the regularized incomplete beta function.
+
+    Computes :math:`x` such that:
+
+    .. math::
+
+        y = I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}
+        \int_0^x t^{a-1}(1-t)^{b-1}dt,
+
+    where :math:`I_x` is the normalized incomplete beta function `betainc`
+    and :math:`\Gamma` is the `gamma` function [1]_.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Positive, real-valued parameters
+    y : array_like
+        Real-valued input
+    out : ndarray, optional
+        Optional output array for function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the inverse of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    gamma : gamma function
+
+    Notes
+    -----
+    This function wraps the ``ibeta_inv`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    This function is the inverse of `betainc` for fixed
+    values of :math:`a` and :math:`b`.
+
+    >>> a, b = 1.2, 3.1
+    >>> y = sc.betainc(a, b, 0.2)
+    >>> sc.betaincinv(a, b, y)
+    0.2
+    >>>
+    >>> a, b = 7.5, 0.4
+    >>> x = sc.betaincinv(a, b, 0.5)
+    >>> sc.betainc(a, b, x)
+    0.5
+
+    """)
+
+
+add_newdoc(
+    "betainccinv",
+    r"""
+    betainccinv(a, b, y, out=None)
+
+    Inverse of the complemented regularized incomplete beta function.
+
+    Computes :math:`x` such that:
+
+    .. math::
+
+        y = 1 - I_x(a, b) = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}
+        \int_0^x t^{a-1}(1-t)^{b-1}dt,
+
+    where :math:`I_x` is the normalized incomplete beta function `betainc`
+    and :math:`\Gamma` is the `gamma` function [1]_.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Positive, real-valued parameters
+    y : array_like
+        Real-valued input
+    out : ndarray, optional
+        Optional output array for function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the inverse of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    betaincc : complement of the regularized incomplete beta function
+
+    Notes
+    -----
+    .. versionadded:: 1.11.0
+
+    This function wraps the ``ibetac_inv`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import betainccinv, betaincc
+
+    This function is the inverse of `betaincc` for fixed
+    values of :math:`a` and :math:`b`.
+
+    >>> a, b = 1.2, 3.1
+    >>> y = betaincc(a, b, 0.2)
+    >>> betainccinv(a, b, y)
+    0.2
+
+    >>> a, b = 7, 2.5
+    >>> x = betainccinv(a, b, 0.875)
+    >>> betaincc(a, b, x)
+    0.875
+
+    """)
+
+add_newdoc("boxcox",
+    """
+    boxcox(x, lmbda, out=None)
+
+    Compute the Box-Cox transformation.
+
+    The Box-Cox transformation is::
+
+        y = (x**lmbda - 1) / lmbda  if lmbda != 0
+            log(x)                  if lmbda == 0
+
+    Returns `nan` if ``x < 0``.
+    Returns `-inf` if ``x == 0`` and ``lmbda < 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox
+    >>> boxcox([1, 4, 10], 2.5)
+    array([   0.        ,   12.4       ,  126.09110641])
+    >>> boxcox(2, [0, 1, 2])
+    array([ 0.69314718,  1.        ,  1.5       ])
+    """)
+
+add_newdoc("boxcox1p",
+    """
+    boxcox1p(x, lmbda, out=None)
+
+    Compute the Box-Cox transformation of 1 + `x`.
+
+    The Box-Cox transformation computed by `boxcox1p` is::
+
+        y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0
+            log(1+x)                    if lmbda == 0
+
+    Returns `nan` if ``x < -1``.
+    Returns `-inf` if ``x == -1`` and ``lmbda < 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox1p
+    >>> boxcox1p(1e-4, [0, 0.5, 1])
+    array([  9.99950003e-05,   9.99975001e-05,   1.00000000e-04])
+    >>> boxcox1p([0.01, 0.1], 0.25)
+    array([ 0.00996272,  0.09645476])
+    """)
+
+add_newdoc("inv_boxcox",
+    """
+    inv_boxcox(y, lmbda, out=None)
+
+    Compute the inverse of the Box-Cox transformation.
+
+    Find ``x`` such that::
+
+        y = (x**lmbda - 1) / lmbda  if lmbda != 0
+            log(x)                  if lmbda == 0
+
+    Parameters
+    ----------
+    y : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox, inv_boxcox
+    >>> y = boxcox([1, 4, 10], 2.5)
+    >>> inv_boxcox(y, 2.5)
+    array([1., 4., 10.])
+    """)
+
+add_newdoc("inv_boxcox1p",
+    """
+    inv_boxcox1p(y, lmbda, out=None)
+
+    Compute the inverse of the Box-Cox transformation.
+
+    Find ``x`` such that::
+
+        y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0
+            log(1+x)                    if lmbda == 0
+
+    Parameters
+    ----------
+    y : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox1p, inv_boxcox1p
+    >>> y = boxcox1p([1, 4, 10], 2.5)
+    >>> inv_boxcox1p(y, 2.5)
+    array([1., 4., 10.])
+    """)
+
+add_newdoc("chdtr",
+    r"""
+    chdtr(v, x, out=None)
+
+    Chi square cumulative distribution function.
+
+    Returns the area under the left tail (from 0 to `x`) of the Chi
+    square probability density function with `v` degrees of freedom:
+
+    .. math::
+
+        \frac{1}{2^{v/2} \Gamma(v/2)} \int_0^x t^{v/2 - 1} e^{-t/2} dt
+
+    Here :math:`\Gamma` is the Gamma function; see `gamma`. This
+    integral can be expressed in terms of the regularized lower
+    incomplete gamma function `gammainc` as
+    ``gammainc(v / 2, x / 2)``. [1]_
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    x : array_like
+        Upper bound of the integral.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the cumulative distribution function.
+
+    See Also
+    --------
+    chdtrc, chdtri, chdtriv, gammainc
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It can be expressed in terms of the regularized lower incomplete
+    gamma function.
+
+    >>> v = 1
+    >>> x = np.arange(4)
+    >>> sc.chdtr(v, x)
+    array([0.        , 0.68268949, 0.84270079, 0.91673548])
+    >>> sc.gammainc(v / 2, x / 2)
+    array([0.        , 0.68268949, 0.84270079, 0.91673548])
+
+    """)
+
+add_newdoc("chdtrc",
+    r"""
+    chdtrc(v, x, out=None)
+
+    Chi square survival function.
+
+    Returns the area under the right hand tail (from `x` to infinity)
+    of the Chi square probability density function with `v` degrees of
+    freedom:
+
+    .. math::
+
+        \frac{1}{2^{v/2} \Gamma(v/2)} \int_x^\infty t^{v/2 - 1} e^{-t/2} dt
+
+    Here :math:`\Gamma` is the Gamma function; see `gamma`. This
+    integral can be expressed in terms of the regularized upper
+    incomplete gamma function `gammaincc` as
+    ``gammaincc(v / 2, x / 2)``. [1]_
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    x : array_like
+        Lower bound of the integral.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the survival function.
+
+    See Also
+    --------
+    chdtr, chdtri, chdtriv, gammaincc
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It can be expressed in terms of the regularized upper incomplete
+    gamma function.
+
+    >>> v = 1
+    >>> x = np.arange(4)
+    >>> sc.chdtrc(v, x)
+    array([1.        , 0.31731051, 0.15729921, 0.08326452])
+    >>> sc.gammaincc(v / 2, x / 2)
+    array([1.        , 0.31731051, 0.15729921, 0.08326452])
+
+    """)
+
+add_newdoc("chdtri",
+    """
+    chdtri(v, p, out=None)
+
+    Inverse to `chdtrc` with respect to `x`.
+
+    Returns `x` such that ``chdtrc(v, x) == p``.
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    p : array_like
+        Probability.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value so that the probability a Chi square random variable
+        with `v` degrees of freedom is greater than `x` equals `p`.
+
+    See Also
+    --------
+    chdtrc, chdtr, chdtriv
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It inverts `chdtrc`.
+
+    >>> v, p = 1, 0.3
+    >>> sc.chdtrc(v, sc.chdtri(v, p))
+    0.3
+    >>> x = 1
+    >>> sc.chdtri(v, sc.chdtrc(v, x))
+    1.0
+
+    """)
+
+add_newdoc("chdtriv",
+    """
+    chdtriv(p, x, out=None)
+
+    Inverse to `chdtr` with respect to `v`.
+
+    Returns `v` such that ``chdtr(v, x) == p``.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability that the Chi square random variable is less than
+        or equal to `x`.
+    x : array_like
+        Nonnegative input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Degrees of freedom.
+
+    See Also
+    --------
+    chdtr, chdtrc, chdtri
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It inverts `chdtr`.
+
+    >>> p, x = 0.5, 1
+    >>> sc.chdtr(sc.chdtriv(p, x), x)
+    0.5000000000202172
+    >>> v = 1
+    >>> sc.chdtriv(sc.chdtr(v, x), v)
+    1.0000000000000013
+
+    """)
+
+add_newdoc("chndtr",
+    r"""
+    chndtr(x, df, nc, out=None)
+
+    Non-central chi square cumulative distribution function
+
+    The cumulative distribution function is given by:
+
+    .. math::
+
+        P(\chi^{\prime 2} \vert \nu, \lambda) =\sum_{j=0}^{\infty}
+        e^{-\lambda /2}
+        \frac{(\lambda /2)^j}{j!} P(\chi^{\prime 2} \vert \nu + 2j),
+
+    where :math:`\nu > 0` is the degrees of freedom (``df``) and
+    :math:`\lambda \geq 0` is the non-centrality parameter (``nc``).
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value of the non-central chi square cumulative distribution function.
+
+    See Also
+    --------
+    chndtrix, chndtridf, chndtrinc
+
+    """)
+
+add_newdoc("chndtrix",
+    """
+    chndtrix(p, df, nc, out=None)
+
+    Inverse to `chndtr` vs `x`
+
+    Calculated using a search to find a value for `x` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value so that the probability a non-central Chi square random variable
+        with `df` degrees of freedom and non-centrality, `nc`, is greater than
+        `x` equals `p`.
+
+    See Also
+    --------
+    chndtr, chndtridf, chndtrinc
+
+    """)
+
+add_newdoc("chndtridf",
+    """
+    chndtridf(x, p, nc, out=None)
+
+    Inverse to `chndtr` vs `df`
+
+    Calculated using a search to find a value for `df` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        Degrees of freedom
+
+    See Also
+    --------
+    chndtr, chndtrix, chndtrinc
+
+    """)
+
+add_newdoc("chndtrinc",
+    """
+    chndtrinc(x, df, p, out=None)
+
+    Inverse to `chndtr` vs `nc`
+
+    Calculated using a search to find a value for `df` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Non-centrality
+
+    See Also
+    --------
+    chndtr, chndtrix, chndtrinc
+
+    """)
+
+add_newdoc("dawsn",
+    """
+    dawsn(x, out=None)
+
+    Dawson's integral.
+
+    Computes::
+
+        exp(-x**2) * integral(exp(t**2), t=0..x).
+
+    Parameters
+    ----------
+    x : array_like
+        Function parameter.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Value of the integral.
+
+    See Also
+    --------
+    wofz, erf, erfc, erfcx, erfi
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-15, 15, num=1000)
+    >>> plt.plot(x, special.dawsn(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$dawsn(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "elliprc",
+    r"""
+    elliprc(x, y, out=None)
+
+    Degenerate symmetric elliptic integral.
+
+    The function RC is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{C}}(x, y) =
+           \frac{1}{2} \int_0^{+\infty} (t + x)^{-1/2} (t + y)^{-1} dt
+           = R_{\mathrm{F}}(x, y, y)
+
+    Parameters
+    ----------
+    x, y : array_like
+        Real or complex input parameters. `x` can be any number in the
+        complex plane cut along the negative real axis. `y` must be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If `y` is real and negative, the Cauchy
+        principal value is returned. If both of `x` and `y` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==
+    elliprf(x, y, y)``. It is an elementary function rather than an elliptic
+    integral.
+
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E6
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprc
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprc(scale*x, scale*y)
+    (0.5484493976710874-0.4169557678995833j)
+
+    >>> elliprc(x, y)/np.sqrt(scale)
+    (0.5484493976710874-0.41695576789958333j)
+
+    When the two arguments coincide, the integral is particularly
+    simple:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprc(x, x)
+    (0.4299173120614631-0.3041729818745595j)
+
+    >>> 1/np.sqrt(x)
+    (0.4299173120614631-0.30417298187455954j)
+
+    Another simple case: the first argument vanishes:
+
+    >>> y = 1.2 + 3.4j
+    >>> elliprc(0, y)
+    (0.6753125346116815-0.47779380263880866j)
+
+    >>> np.pi/2/np.sqrt(y)
+    (0.6753125346116815-0.4777938026388088j)
+
+    When `x` and `y` are both positive, we can express
+    :math:`R_C(x,y)` in terms of more elementary functions.  For the
+    case :math:`0 \le x < y`,
+
+    >>> x = 3.2
+    >>> y = 6.
+    >>> elliprc(x, y)
+    0.44942991498453444
+
+    >>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)
+    0.44942991498453433
+
+    And for the case :math:`0 \le y < x`,
+
+    >>> x = 6.
+    >>> y = 3.2
+    >>> elliprc(x,y)
+    0.4989837501576147
+
+    >>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)
+    0.49898375015761476
+
+    """)
+
+add_newdoc(
+    "elliprd",
+    r"""
+    elliprd(x, y, z, out=None)
+
+    Symmetric elliptic integral of the second kind.
+
+    The function RD is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{D}}(x, y, z) =
+           \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}
+           dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x` or `y` can be any number in the
+        complex plane cut along the negative real axis, but at most one of them
+        can be zero, while `z` must be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric elliptic integral.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==
+    elliprj(x, y, z, z)``.
+
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E5
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprd
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprd(scale*x, scale*y, scale*z)
+    (-0.03703043835680379-0.24500934665683802j)
+
+    >>> elliprd(x, y, z)*np.power(scale, -1.5)
+    (-0.0370304383568038-0.24500934665683805j)
+
+    All three arguments coincide:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprd(x, x, x)
+    (-0.03986825876151896-0.14051741840449586j)
+
+    >>> np.power(x, -1.5)
+    (-0.03986825876151894-0.14051741840449583j)
+
+    The so-called "second lemniscate constant":
+
+    >>> elliprd(0, 2, 1)/3
+    0.5990701173677961
+
+    >>> from scipy.special import gamma
+    >>> gamma(0.75)**2/np.sqrt(2*np.pi)
+    0.5990701173677959
+
+    """)
+
+add_newdoc(
+    "elliprf",
+    r"""
+    elliprf(x, y, z, out=None)
+
+    Completely-symmetric elliptic integral of the first kind.
+
+    The function RF is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{F}}(x, y, z) =
+           \frac{1}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x`, `y`, or `z` can be any number in
+        the complex plane cut along the negative real axis, but at most one of
+        them can be zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the return
+        value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order (cf.:
+    https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete
+    integral. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E1
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprf
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprf(scale*x, scale*y, scale*z)
+    (0.5328051227278146-0.4008623567957094j)
+
+    >>> elliprf(x, y, z)/np.sqrt(scale)
+    (0.5328051227278147-0.4008623567957095j)
+
+    All three arguments coincide:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprf(x, x, x)
+    (0.42991731206146316-0.30417298187455954j)
+
+    >>> 1/np.sqrt(x)
+    (0.4299173120614631-0.30417298187455954j)
+
+    The so-called "first lemniscate constant":
+
+    >>> elliprf(0, 1, 2)
+    1.3110287771460598
+
+    >>> from scipy.special import gamma
+    >>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))
+    1.3110287771460598
+
+    """)
+
+add_newdoc(
+    "elliprg",
+    r"""
+    elliprg(x, y, z, out=None)
+
+    Completely-symmetric elliptic integral of the second kind.
+
+    The function RG is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{G}}(x, y, z) =
+           \frac{1}{4} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2}
+           \left(\frac{x}{t + x} + \frac{y}{t + y} + \frac{z}{t + z}\right) t
+           dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x`, `y`, or `z` can be any number in
+        the complex plane cut along the negative real axis.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the return
+        value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    The implementation uses the relation [1]_
+
+    .. math::
+
+        2 R_{\mathrm{G}}(x, y, z) =
+           z R_{\mathrm{F}}(x, y, z) -
+           \frac{1}{3} (x - z) (y - z) R_{\mathrm{D}}(x, y, z) +
+           \sqrt{\frac{x y}{z}}
+
+    and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can
+    be chosen as the pivot. When one of the arguments is close to zero, the AGM
+    method is applied instead. Other special cases are computed following Ref.
+    [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+    .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E1
+           https://dlmf.nist.gov/19.20.ii
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprg
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprg(scale*x, scale*y, scale*z)
+    (1.195936862005246+0.8470988320464167j)
+
+    >>> elliprg(x, y, z)*np.sqrt(scale)
+    (1.195936862005246+0.8470988320464165j)
+
+    Simplifications:
+
+    >>> elliprg(0, y, y)
+    1.756203682760182
+
+    >>> 0.25*np.pi*np.sqrt(y)
+    1.7562036827601817
+
+    >>> elliprg(0, 0, z)
+    1.224744871391589
+
+    >>> 0.5*np.sqrt(z)
+    1.224744871391589
+
+    The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and
+    ``c`` is given by
+
+    .. math::
+
+        S = 4 \pi a b c R_{\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).
+
+    >>> def ellipsoid_area(a, b, c):
+    ...     r = 4.0 * np.pi * a * b * c
+    ...     return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))
+    >>> print(ellipsoid_area(1, 3, 5))
+    108.62688289491807
+    """)
+
+add_newdoc(
+    "elliprj",
+    r"""
+    elliprj(x, y, z, p, out=None)
+
+    Symmetric elliptic integral of the third kind.
+
+    The function RJ is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{J}}(x, y, z, p) =
+           \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2}
+           (t + p)^{-1} dt
+
+    .. warning::
+        This function should be considered experimental when the inputs are
+        unbalanced.  Check correctness with another independent implementation.
+
+    Parameters
+    ----------
+    x, y, z, p : array_like
+        Real or complex input parameters. `x`, `y`, or `z` are numbers in
+        the complex plane cut along the negative real axis (subject to further
+        constraints, see Notes), and at most one of them can be zero. `p` must
+        be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+        If `p` is real and negative, while `x`, `y`, and `z` are real,
+        non-negative, and at most one of them is zero, the Cauchy principal
+        value is returned. [1]_ [2]_
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+
+    Notes
+    -----
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [3]_ The algorithm is slightly
+    different from its earlier incarnation as it appears in [1]_, in that the
+    call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in
+    the inner loop. Asymptotic approximations are used where arguments differ
+    widely in the order of magnitude. [5]_
+
+    The input values are subject to certain sufficient but not necessary
+    constraints when input arguments are complex. Notably, ``x``, ``y``, and
+    ``z`` must have non-negative real parts, unless two of them are
+    non-negative and complex-conjugates to each other while the other is a real
+    non-negative number. [1]_ If the inputs do not satisfy the sufficient
+    condition described in Ref. [1]_ they are rejected outright with the output
+    set to NaN.
+
+    In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the
+    function ``elliprd`` should be preferred because of its less restrictive
+    domain.
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+    .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.20.iii
+    .. [3] B. C. Carlson, J. FitzSimmons, "Reduction Theorems for Elliptic
+           Integrands with the Square Root of Two Quadratic Factors," J.
+           Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.
+           https://doi.org/10.1016/S0377-0427(00)00282-X
+    .. [4] F. Johansson, "Numerical Evaluation of Elliptic Functions, Elliptic
+           Integrals and Modular Forms," in J. Blumlein, C. Schneider, P.
+           Paule, eds., "Elliptic Integrals, Elliptic Functions and Modular
+           Forms in Quantum Field Theory," pp. 269-293, 2019 (Cham,
+           Switzerland: Springer Nature Switzerland)
+           https://arxiv.org/abs/1806.06725
+           https://doi.org/10.1007/978-3-030-04480-0
+    .. [5] B. C. Carlson, J. L. Gustafson, "Asymptotic Approximations for
+           Symmetric Elliptic Integrals," SIAM J. Math. Anls., vol. 25, no. 2,
+           pp. 288-303, 1994.
+           https://arxiv.org/abs/math/9310223
+           https://doi.org/10.1137/S0036141092228477
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprj
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> p = 7.
+    >>> scale = 0.3 - 0.4j
+    >>> elliprj(scale*x, scale*y, scale*z, scale*p)
+    (0.10834905565679157+0.19694950747103812j)
+
+    >>> elliprj(x, y, z, p)*np.power(scale, -1.5)
+    (0.10834905565679556+0.19694950747103854j)
+
+    Reduction to simpler elliptic integral:
+
+    >>> elliprj(x, y, z, z)
+    (0.08288462362195129-0.028376809745123258j)
+
+    >>> from scipy.special import elliprd
+    >>> elliprd(x, y, z)
+    (0.08288462362195136-0.028376809745123296j)
+
+    All arguments coincide:
+
+    >>> elliprj(x, x, x, x)
+    (-0.03986825876151896-0.14051741840449586j)
+
+    >>> np.power(x, -1.5)
+    (-0.03986825876151894-0.14051741840449583j)
+
+    """)
+
+add_newdoc("entr",
+    r"""
+    entr(x, out=None)
+
+    Elementwise function for computing entropy.
+
+    .. math:: \text{entr}(x) = \begin{cases} - x \log(x) & x > 0  \\ 0 & x = 0
+              \\ -\infty & \text{otherwise} \end{cases}
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The value of the elementwise entropy function at the given points `x`.
+
+    See Also
+    --------
+    kl_div, rel_entr, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is concave.
+
+    The origin of this function is in convex programming; see [1]_.
+    Given a probability distribution :math:`p_1, \ldots, p_n`,
+    the definition of entropy in the context of *information theory* is
+
+    .. math::
+
+        \sum_{i = 1}^n \mathrm{entr}(p_i).
+
+    To compute the latter quantity, use `scipy.stats.entropy`.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+
+    """)
+
+add_newdoc("erf",
+    """
+    erf(z, out=None)
+
+    Returns the error function of complex argument.
+
+    It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The values of the error function at the given points `x`.
+
+    See Also
+    --------
+    erfc, erfinv, erfcinv, wofz, erfcx, erfi
+
+    Notes
+    -----
+    The cumulative of the unit normal distribution is given by
+    ``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Error_function
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover,
+        1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm
+    .. [3] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erf(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erf(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfc",
+    """
+    erfc(x, out=None)
+
+    Complementary error function, ``1 - erf(x)``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the complementary error function
+
+    See Also
+    --------
+    erf, erfi, erfcx, dawsn, wofz
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfc(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfc(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfi",
+    """
+    erfi(z, out=None)
+
+    Imaginary error function, ``-i erf(i z)``.
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the imaginary error function
+
+    See Also
+    --------
+    erf, erfc, erfcx, dawsn, wofz
+
+    Notes
+    -----
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfi(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfi(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfcx",
+    """
+    erfcx(x, out=None)
+
+    Scaled complementary error function, ``exp(x**2) * erfc(x)``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the scaled complementary error function
+
+
+    See Also
+    --------
+    erf, erfc, erfi, dawsn, wofz
+
+    Notes
+    -----
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfcx(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfcx(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "erfinv",
+    """
+    erfinv(y, out=None)
+
+    Inverse of the error function.
+
+    Computes the inverse of the error function.
+
+    In the complex domain, there is no unique complex number w satisfying
+    erf(w)=z. This indicates a true inverse function would be multivalued.
+    When the domain restricts to the real, -1 < x < 1, there is a unique real
+    number satisfying erf(erfinv(x)) = x.
+
+    Parameters
+    ----------
+    y : ndarray
+        Argument at which to evaluate. Domain: [-1, 1]
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    erfinv : scalar or ndarray
+        The inverse of erf of y, element-wise
+
+    See Also
+    --------
+    erf : Error function of a complex argument
+    erfc : Complementary error function, ``1 - erf(x)``
+    erfcinv : Inverse of the complementary error function
+
+    Notes
+    -----
+    This function wraps the ``erf_inv`` routine from the
+    Boost Math C++ library [1]_.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import erfinv, erf
+
+    >>> erfinv(0.5)
+    0.4769362762044699
+
+    >>> y = np.linspace(-1.0, 1.0, num=9)
+    >>> x = erfinv(y)
+    >>> x
+    array([       -inf, -0.81341985, -0.47693628, -0.22531206,  0.        ,
+            0.22531206,  0.47693628,  0.81341985,         inf])
+
+    Verify that ``erf(erfinv(y))`` is ``y``.
+
+    >>> erf(x)
+    array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])
+
+    Plot the function:
+
+    >>> y = np.linspace(-1, 1, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(y, erfinv(y))
+    >>> ax.grid(True)
+    >>> ax.set_xlabel('y')
+    >>> ax.set_title('erfinv(y)')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "erfcinv",
+    """
+    erfcinv(y, out=None)
+
+    Inverse of the complementary error function.
+
+    Computes the inverse of the complementary error function.
+
+    In the complex domain, there is no unique complex number w satisfying
+    erfc(w)=z. This indicates a true inverse function would be multivalued.
+    When the domain restricts to the real, 0 < x < 2, there is a unique real
+    number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).
+
+    It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)
+
+    Parameters
+    ----------
+    y : ndarray
+        Argument at which to evaluate. Domain: [0, 2]
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    erfcinv : scalar or ndarray
+        The inverse of erfc of y, element-wise
+
+    See Also
+    --------
+    erf : Error function of a complex argument
+    erfc : Complementary error function, ``1 - erf(x)``
+    erfinv : Inverse of the error function
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import erfcinv
+
+    >>> erfcinv(0.5)
+    0.4769362762044699
+
+    >>> y = np.linspace(0.0, 2.0, num=11)
+    >>> erfcinv(y)
+    array([        inf,  0.9061938 ,  0.59511608,  0.37080716,  0.17914345,
+           -0.        , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,
+                  -inf])
+
+    Plot the function:
+
+    >>> y = np.linspace(0, 2, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(y, erfcinv(y))
+    >>> ax.grid(True)
+    >>> ax.set_xlabel('y')
+    >>> ax.set_title('erfcinv(y)')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("eval_jacobi",
+    r"""
+    eval_jacobi(n, alpha, beta, x, out=None)
+
+    Evaluate Jacobi polynomial at a point.
+
+    The Jacobi polynomials can be defined via the Gauss hypergeometric
+    function :math:`{}_2F_1` as
+
+    .. math::
+
+        P_n^{(\alpha, \beta)}(x) = \frac{(\alpha + 1)_n}{\Gamma(n + 1)}
+          {}_2F_1(-n, 1 + \alpha + \beta + n; \alpha + 1; (1 - z)/2)
+
+    where :math:`(\cdot)_n` is the Pochhammer symbol; see `poch`. When
+    :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.42 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    alpha : array_like
+        Parameter
+    beta : array_like
+        Parameter
+    x : array_like
+        Points at which to evaluate the polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the Jacobi polynomial
+
+    See Also
+    --------
+    roots_jacobi : roots and quadrature weights of Jacobi polynomials
+    jacobi : Jacobi polynomial object
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_sh_jacobi",
+    r"""
+    eval_sh_jacobi(n, p, q, x, out=None)
+
+    Evaluate shifted Jacobi polynomial at a point.
+
+    Defined by
+
+    .. math::
+
+        G_n^{(p, q)}(x)
+          = \binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),
+
+    where :math:`P_n^{(\cdot, \cdot)}` is the n-th Jacobi
+    polynomial. See 22.5.2 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `binom` and `eval_jacobi`.
+    p : float
+        Parameter
+    q : float
+        Parameter
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    G : scalar or ndarray
+        Values of the shifted Jacobi polynomial.
+
+    See Also
+    --------
+    roots_sh_jacobi : roots and quadrature weights of shifted Jacobi
+                      polynomials
+    sh_jacobi : shifted Jacobi polynomial object
+    eval_jacobi : evaluate Jacobi polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_gegenbauer",
+    r"""
+    eval_gegenbauer(n, alpha, x, out=None)
+
+    Evaluate Gegenbauer polynomial at a point.
+
+    The Gegenbauer polynomials can be defined via the Gauss
+    hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        C_n^{(\alpha)} = \frac{(2\alpha)_n}{\Gamma(n + 1)}
+          {}_2F_1(-n, 2\alpha + n; \alpha + 1/2; (1 - z)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.46 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    alpha : array_like
+        Parameter
+    x : array_like
+        Points at which to evaluate the Gegenbauer polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    C : scalar or ndarray
+        Values of the Gegenbauer polynomial
+
+    See Also
+    --------
+    roots_gegenbauer : roots and quadrature weights of Gegenbauer
+                       polynomials
+    gegenbauer : Gegenbauer polynomial object
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebyt",
+    r"""
+    eval_chebyt(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the first kind at a point.
+
+    The Chebyshev polynomials of the first kind can be defined via the
+    Gauss hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.47 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    T : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyt : roots and quadrature weights of Chebyshev
+                   polynomials of the first kind
+    chebyu : Chebychev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+    hyp2f1 : Gauss hypergeometric function
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+
+    Notes
+    -----
+    This routine is numerically stable for `x` in ``[-1, 1]`` at least
+    up to order ``10000``.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebyu",
+    r"""
+    eval_chebyu(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the second kind at a point.
+
+    The Chebyshev polynomials of the second kind can be defined via
+    the Gauss hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.48 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    U : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyu : roots and quadrature weights of Chebyshev
+                   polynomials of the second kind
+    chebyu : Chebyshev polynomial object
+    eval_chebyt : evaluate Chebyshev polynomials of the first kind
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebys",
+    r"""
+    eval_chebys(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        S_n(x) = U_n(x/2)
+
+    where :math:`U_n` is a Chebyshev polynomial of the second
+    kind. See 22.5.13 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyu`.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    S : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebys : roots and quadrature weights of Chebyshev
+                   polynomials of the second kind on [-2, 2]
+    chebys : Chebyshev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    They are a scaled version of the Chebyshev polynomials of the
+    second kind.
+
+    >>> x = np.linspace(-2, 2, 6)
+    >>> sc.eval_chebys(3, x)
+    array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])
+    >>> sc.eval_chebyu(3, x / 2)
+    array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])
+
+    """)
+
+add_newdoc("eval_chebyc",
+    r"""
+    eval_chebyc(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        C_n(x) = 2 T_n(x/2)
+
+    where :math:`T_n` is a Chebyshev polynomial of the first kind. See
+    22.5.11 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyt`.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    C : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyc : roots and quadrature weights of Chebyshev
+                   polynomials of the first kind on [-2, 2]
+    chebyc : Chebyshev polynomial object
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+    eval_chebyt : evaluate Chebycshev polynomials of the first kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    They are a scaled version of the Chebyshev polynomials of the
+    first kind.
+
+    >>> x = np.linspace(-2, 2, 6)
+    >>> sc.eval_chebyc(3, x)
+    array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])
+    >>> 2 * sc.eval_chebyt(3, x / 2)
+    array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])
+
+    """)
+
+add_newdoc("eval_sh_chebyt",
+    r"""
+    eval_sh_chebyt(n, x, out=None)
+
+    Evaluate shifted Chebyshev polynomial of the first kind at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        T_n^*(x) = T_n(2x - 1)
+
+    where :math:`T_n` is a Chebyshev polynomial of the first kind. See
+    22.5.14 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyt`.
+    x : array_like
+        Points at which to evaluate the shifted Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    T : scalar or ndarray
+        Values of the shifted Chebyshev polynomial
+
+    See Also
+    --------
+    roots_sh_chebyt : roots and quadrature weights of shifted
+                      Chebyshev polynomials of the first kind
+    sh_chebyt : shifted Chebyshev polynomial object
+    eval_chebyt : evaluate Chebyshev polynomials of the first kind
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_sh_chebyu",
+    r"""
+    eval_sh_chebyu(n, x, out=None)
+
+    Evaluate shifted Chebyshev polynomial of the second kind at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        U_n^*(x) = U_n(2x - 1)
+
+    where :math:`U_n` is a Chebyshev polynomial of the first kind. See
+    22.5.15 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyu`.
+    x : array_like
+        Points at which to evaluate the shifted Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    U : scalar or ndarray
+        Values of the shifted Chebyshev polynomial
+
+    See Also
+    --------
+    roots_sh_chebyu : roots and quadrature weights of shifted
+                      Chebychev polynomials of the second kind
+    sh_chebyu : shifted Chebyshev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_legendre",
+    r"""
+    eval_legendre(n, x, out=None)
+
+    Evaluate Legendre polynomial at a point.
+
+    The Legendre polynomials can be defined via the Gauss
+    hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.49 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Legendre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the Legendre polynomial
+
+    See Also
+    --------
+    roots_legendre : roots and quadrature weights of Legendre
+                     polynomials
+    legendre : Legendre polynomial object
+    hyp2f1 : Gauss hypergeometric function
+    numpy.polynomial.legendre.Legendre : Legendre series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import eval_legendre
+
+    Evaluate the zero-order Legendre polynomial at x = 0
+
+    >>> eval_legendre(0, 0)
+    1.0
+
+    Evaluate the first-order Legendre polynomial between -1 and 1
+
+    >>> X = np.linspace(-1, 1, 5)  # Domain of Legendre polynomials
+    >>> eval_legendre(1, X)
+    array([-1. , -0.5,  0. ,  0.5,  1. ])
+
+    Evaluate Legendre polynomials of order 0 through 4 at x = 0
+
+    >>> N = range(0, 5)
+    >>> eval_legendre(N, 0)
+    array([ 1.   ,  0.   , -0.5  ,  0.   ,  0.375])
+
+    Plot Legendre polynomials of order 0 through 4
+
+    >>> X = np.linspace(-1, 1)
+
+    >>> import matplotlib.pyplot as plt
+    >>> for n in range(0, 5):
+    ...     y = eval_legendre(n, X)
+    ...     plt.plot(X, y, label=r'$P_{}(x)$'.format(n))
+
+    >>> plt.title("Legendre Polynomials")
+    >>> plt.xlabel("x")
+    >>> plt.ylabel(r'$P_n(x)$')
+    >>> plt.legend(loc='lower right')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("eval_sh_legendre",
+    r"""
+    eval_sh_legendre(n, x, out=None)
+
+    Evaluate shifted Legendre polynomial at a point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        P_n^*(x) = P_n(2x - 1)
+
+    where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_
+    for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the value is
+        determined via the relation to `eval_legendre`.
+    x : array_like
+        Points at which to evaluate the shifted Legendre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the shifted Legendre polynomial
+
+    See Also
+    --------
+    roots_sh_legendre : roots and quadrature weights of shifted
+                        Legendre polynomials
+    sh_legendre : shifted Legendre polynomial object
+    eval_legendre : evaluate Legendre polynomials
+    numpy.polynomial.legendre.Legendre : Legendre series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_genlaguerre",
+    r"""
+    eval_genlaguerre(n, alpha, x, out=None)
+
+    Evaluate generalized Laguerre polynomial at a point.
+
+    The generalized Laguerre polynomials can be defined via the
+    confluent hypergeometric function :math:`{}_1F_1` as
+
+    .. math::
+
+        L_n^{(\alpha)}(x) = \binom{n + \alpha}{n}
+          {}_1F_1(-n, \alpha + 1, x).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre
+    polynomials are the special case where :math:`\alpha = 0`.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the confluent hypergeometric
+        function.
+    alpha : array_like
+        Parameter; must have ``alpha > -1``
+    x : array_like
+        Points at which to evaluate the generalized Laguerre
+        polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    L : scalar or ndarray
+        Values of the generalized Laguerre polynomial
+
+    See Also
+    --------
+    roots_genlaguerre : roots and quadrature weights of generalized
+                        Laguerre polynomials
+    genlaguerre : generalized Laguerre polynomial object
+    hyp1f1 : confluent hypergeometric function
+    eval_laguerre : evaluate Laguerre polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_laguerre",
+    r"""
+    eval_laguerre(n, x, out=None)
+
+    Evaluate Laguerre polynomial at a point.
+
+    The Laguerre polynomials can be defined via the confluent
+    hypergeometric function :math:`{}_1F_1` as
+
+    .. math::
+
+        L_n(x) = {}_1F_1(-n, 1, x).
+
+    See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an
+    integer the result is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer the result is
+        determined via the relation to the confluent hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Laguerre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    L : scalar or ndarray
+        Values of the Laguerre polynomial
+
+    See Also
+    --------
+    roots_laguerre : roots and quadrature weights of Laguerre
+                     polynomials
+    laguerre : Laguerre polynomial object
+    numpy.polynomial.laguerre.Laguerre : Laguerre series
+    eval_genlaguerre : evaluate generalized Laguerre polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+     """)
+
+add_newdoc("eval_hermite",
+    r"""
+    eval_hermite(n, x, out=None)
+
+    Evaluate physicist's Hermite polynomial at a point.
+
+    Defined by
+
+    .. math::
+
+        H_n(x) = (-1)^n e^{x^2} \frac{d^n}{dx^n} e^{-x^2};
+
+    :math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial
+    x : array_like
+        Points at which to evaluate the Hermite polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    H : scalar or ndarray
+        Values of the Hermite polynomial
+
+    See Also
+    --------
+    roots_hermite : roots and quadrature weights of physicist's
+                    Hermite polynomials
+    hermite : physicist's Hermite polynomial object
+    numpy.polynomial.hermite.Hermite : Physicist's Hermite series
+    eval_hermitenorm : evaluate Probabilist's Hermite polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_hermitenorm",
+    r"""
+    eval_hermitenorm(n, x, out=None)
+
+    Evaluate probabilist's (normalized) Hermite polynomial at a
+    point.
+
+    Defined by
+
+    .. math::
+
+        He_n(x) = (-1)^n e^{x^2/2} \frac{d^n}{dx^n} e^{-x^2/2};
+
+    :math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial
+    x : array_like
+        Points at which to evaluate the Hermite polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    He : scalar or ndarray
+        Values of the Hermite polynomial
+
+    See Also
+    --------
+    roots_hermitenorm : roots and quadrature weights of probabilist's
+                        Hermite polynomials
+    hermitenorm : probabilist's Hermite polynomial object
+    numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series
+    eval_hermite : evaluate physicist's Hermite polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+
+add_newdoc("exp10",
+    """
+    exp10(x, out=None)
+
+    Compute ``10**x`` element-wise.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``10**x``, computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import exp10
+
+    >>> exp10(3)
+    1000.0
+    >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])
+    >>> exp10(x)
+    array([[  0.1       ,   0.31622777,   1.        ],
+           [  3.16227766,  10.        ,  31.6227766 ]])
+
+    """)
+
+add_newdoc("exp2",
+    """
+    exp2(x, out=None)
+
+    Compute ``2**x`` element-wise.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``2**x``, computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import exp2
+
+    >>> exp2(3)
+    8.0
+    >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])
+    >>> exp2(x)
+    array([[ 0.5       ,  0.70710678,  1.        ],
+           [ 1.41421356,  2.        ,  2.82842712]])
+    """)
+
+add_newdoc("expm1",
+    """
+    expm1(x, out=None)
+
+    Compute ``exp(x) - 1``.
+
+    When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation
+    of ``exp(x) - 1`` can suffer from catastrophic loss of precision.
+    ``expm1(x)`` is implemented to avoid the loss of precision that occurs when
+    `x` is near zero.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``exp(x) - 1`` computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import expm1
+
+    >>> expm1(1.0)
+    1.7182818284590451
+    >>> expm1([-0.2, -0.1, 0, 0.1, 0.2])
+    array([-0.18126925, -0.09516258,  0.        ,  0.10517092,  0.22140276])
+
+    The exact value of ``exp(7.5e-13) - 1`` is::
+
+        7.5000000000028125000000007031250000001318...*10**-13.
+
+    Here is what ``expm1(7.5e-13)`` gives:
+
+    >>> expm1(7.5e-13)
+    7.5000000000028135e-13
+
+    Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in
+    a "catastrophic" loss of precision:
+
+    >>> np.exp(7.5e-13) - 1
+    7.5006667543675576e-13
+
+    """)
+
+add_newdoc("expn",
+    r"""
+    expn(n, x, out=None)
+
+    Generalized exponential integral En.
+
+    For integer :math:`n \geq 0` and real :math:`x \geq 0` the
+    generalized exponential integral is defined as [dlmf]_
+
+    .. math::
+
+        E_n(x) = x^{n - 1} \int_x^\infty \frac{e^{-t}}{t^n} dt.
+
+    Parameters
+    ----------
+    n : array_like
+        Non-negative integers
+    x : array_like
+        Real argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the generalized exponential integral
+
+    See Also
+    --------
+    exp1 : special case of :math:`E_n` for :math:`n = 1`
+    expi : related to :math:`E_n` when :math:`n = 1`
+
+    References
+    ----------
+    .. [dlmf] Digital Library of Mathematical Functions, 8.19.2
+              https://dlmf.nist.gov/8.19#E2
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    Its domain is nonnegative n and x.
+
+    >>> sc.expn(-1, 1.0), sc.expn(1, -1.0)
+    (nan, nan)
+
+    It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it
+    is equal to ``1 / (n - 1)``.
+
+    >>> sc.expn([0, 1, 2, 3, 4], 0)
+    array([       inf,        inf, 1.        , 0.5       , 0.33333333])
+
+    For n equal to 0 it reduces to ``exp(-x) / x``.
+
+    >>> x = np.array([1, 2, 3, 4])
+    >>> sc.expn(0, x)
+    array([0.36787944, 0.06766764, 0.01659569, 0.00457891])
+    >>> np.exp(-x) / x
+    array([0.36787944, 0.06766764, 0.01659569, 0.00457891])
+
+    For n equal to 1 it reduces to `exp1`.
+
+    >>> sc.expn(1, x)
+    array([0.21938393, 0.04890051, 0.01304838, 0.00377935])
+    >>> sc.exp1(x)
+    array([0.21938393, 0.04890051, 0.01304838, 0.00377935])
+
+    """)
+
+add_newdoc("fdtr",
+    r"""
+    fdtr(dfn, dfd, x, out=None)
+
+    F cumulative distribution function.
+
+    Returns the value of the cumulative distribution function of the
+    F-distribution, also known as Snedecor's F-distribution or the
+    Fisher-Snedecor distribution.
+
+    The F-distribution with parameters :math:`d_n` and :math:`d_d` is the
+    distribution of the random variable,
+
+    .. math::
+        X = \frac{U_n/d_n}{U_d/d_d},
+
+    where :math:`U_n` and :math:`U_d` are random variables distributed
+    :math:`\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,
+    respectively.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.
+
+    See Also
+    --------
+    fdtrc : F distribution survival function
+    fdtri : F distribution inverse cumulative distribution
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The regularized incomplete beta function is used, according to the
+    formula,
+
+    .. math::
+        F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).
+
+    Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also
+    available as `scipy.stats.f`. Calling `fdtr` directly can improve
+    performance compared to the ``cdf`` method of `scipy.stats.f` (see last
+    example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtr
+    >>> fdtr(1, 2, 1)
+    0.5773502691896258
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.5, 2., 3.])
+    >>> fdtr(1, 2, x)
+    array([0.4472136 , 0.70710678, 0.77459667])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [1, 5, 10, 50]
+    >>> dfd_parameters = [1, 1, 2, 3]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtr_vals = fdtr(dfn, dfd, x)
+    ...     ax.plot(x, fdtr_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("F distribution cumulative distribution function")
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtr`
+    directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 1
+    >>> fdtr_res = fdtr(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).cdf(x)
+    >>> fdtr_res == f_dist_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtrc",
+    r"""
+    fdtrc(dfn, dfd, x, out=None)
+
+    F survival function.
+
+    Returns the complemented F-distribution function (the integral of the
+    density from `x` to infinity).
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        The complemented F-distribution function with parameters `dfn` and
+        `dfd` at `x`.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtri : F distribution inverse cumulative distribution function
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The regularized incomplete beta function is used, according to the
+    formula,
+
+    .. math::
+        F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).
+
+    Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also
+    available as `scipy.stats.f`. Calling `fdtrc` directly can improve
+    performance compared to the ``sf`` method of `scipy.stats.f` (see last
+    example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtrc
+    >>> fdtrc(1, 2, 1)
+    0.42264973081037427
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.5, 2., 3.])
+    >>> fdtrc(1, 2, x)
+    array([0.5527864 , 0.29289322, 0.22540333])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [1, 5, 10, 50]
+    >>> dfd_parameters = [1, 1, 2, 3]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtrc_vals = fdtrc(dfn, dfd, x)
+    ...     ax.plot(x, fdtrc_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("F distribution survival function")
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtrc`
+    directly can be much faster than calling the ``sf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 1
+    >>> fdtrc_res = fdtrc(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).sf(x)
+    >>> f_dist_res == fdtrc_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtri",
+    r"""
+    fdtri(dfn, dfd, p, out=None)
+
+    The `p`-th quantile of the F-distribution.
+
+    This function is the inverse of the F-distribution CDF, `fdtr`, returning
+    the `x` such that `fdtr(dfn, dfd, x) = p`.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        The quantile corresponding to `p`.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtrc : F distribution survival function
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The computation is carried out using the relation to the inverse
+    regularized beta function, :math:`I^{-1}_x(a, b)`.  Let
+    :math:`z = I^{-1}_p(d_d/2, d_n/2).`  Then,
+
+    .. math::
+        x = \frac{d_d (1 - z)}{d_n z}.
+
+    If `p` is such that :math:`x < 0.5`, the following relation is used
+    instead for improved stability: let
+    :math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,
+
+    .. math::
+        x = \frac{d_d z'}{d_n (1 - z')}.
+
+    Wrapper for the Cephes [1]_ routine `fdtri`.
+
+    The F distribution is also available as `scipy.stats.f`. Calling
+    `fdtri` directly can improve performance compared to the ``ppf``
+    method of `scipy.stats.f` (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    `fdtri` represents the inverse of the F distribution CDF which is
+    available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``
+    at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,
+    `df2` and the computed CDF value.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtri, fdtr
+    >>> df1, df2 = 1, 2
+    >>> x = 3
+    >>> cdf_value =  fdtr(df1, df2, x)
+    >>> fdtri(df1, df2, cdf_value)
+    3.000000000000006
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.1, 0.4, 0.7])
+    >>> fdtri(1, 2, x)
+    array([0.02020202, 0.38095238, 1.92156863])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [50, 10, 1, 50]
+    >>> dfd_parameters = [0.5, 1, 1, 5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtri_vals = fdtri(dfn, dfd, x)
+    ...     ax.plot(x, fdtri_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> title = "F distribution inverse cumulative distribution function"
+    >>> ax.set_title(title)
+    >>> ax.set_ylim(0, 30)
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtri`
+    directly can be much faster than calling the ``ppf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 0.7
+    >>> fdtri_res = fdtri(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).ppf(x)
+    >>> f_dist_res == fdtri_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtridfd",
+    """
+    fdtridfd(dfn, p, x, out=None)
+
+    Inverse to `fdtr` vs dfd
+
+    Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    dfd : scalar or ndarray
+        `dfd` such that ``fdtr(dfn, dfd, x) == p``.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtrc : F distribution survival function
+    fdtri : F distribution quantile function
+    scipy.stats.f : F distribution
+
+    Examples
+    --------
+    Compute the F distribution cumulative distribution function for one
+    parameter set.
+
+    >>> from scipy.special import fdtridfd, fdtr
+    >>> dfn, dfd, x = 10, 5, 2
+    >>> cdf_value = fdtr(dfn, dfd, x)
+    >>> cdf_value
+    0.7700248806501017
+
+    Verify that `fdtridfd` recovers the original value for `dfd`:
+
+    >>> fdtridfd(dfn, cdf_value, x)
+    5.0
+    """)
+
+'''
+commented out as fdtridfn seems to have bugs and is not in functions.json
+see: https://github.com/scipy/scipy/pull/15622#discussion_r811440983
+
+add_newdoc(
+    "fdtridfn",
+    """
+    fdtridfn(p, dfd, x, out=None)
+
+    Inverse to `fdtr` vs dfn
+
+    finds the F density argument dfn such that ``fdtr(dfn, dfd, x) == p``.
+
+
+    Parameters
+    ----------
+    p : array_like
+        Cumulative probability, in [0, 1].
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    dfn : scalar or ndarray
+        `dfn` such that ``fdtr(dfn, dfd, x) == p``.
+
+    See Also
+    --------
+    fdtr, fdtrc, fdtri, fdtridfd
+
+
+    """)
+'''
+
+add_newdoc("gdtr",
+    r"""
+    gdtr(a, b, x, out=None)
+
+    Gamma distribution cumulative distribution function.
+
+    Returns the integral from zero to `x` of the gamma probability density
+    function,
+
+    .. math::
+
+        F = \int_0^x \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt,
+
+    where :math:`\Gamma` is the gamma function.
+
+    Parameters
+    ----------
+    a : array_like
+        The rate parameter of the gamma distribution, sometimes denoted
+        :math:`\beta` (float).  It is also the reciprocal of the scale
+        parameter :math:`\theta`.
+    b : array_like
+        The shape parameter of the gamma distribution, sometimes denoted
+        :math:`\alpha` (float).
+    x : array_like
+        The quantile (upper limit of integration; float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The CDF of the gamma distribution with parameters `a` and `b`
+        evaluated at `x`.
+
+    See Also
+    --------
+    gdtrc : 1 - CDF of the gamma distribution.
+    scipy.stats.gamma: Gamma distribution
+
+    Notes
+    -----
+    The evaluation is carried out using the relation to the incomplete gamma
+    integral (regularized gamma function).
+
+    Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can
+    improve performance compared to the ``cdf`` method of `scipy.stats.gamma`
+    (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``a=1``, ``b=2`` at ``x=5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import gdtr
+    >>> import matplotlib.pyplot as plt
+    >>> gdtr(1., 2., 5.)
+    0.9595723180054873
+
+    Compute the function for ``a=1`` and ``b=2`` at several points by
+    providing a NumPy array for `x`.
+
+    >>> xvalues = np.array([1., 2., 3., 4])
+    >>> gdtr(1., 1., xvalues)
+    array([0.63212056, 0.86466472, 0.95021293, 0.98168436])
+
+    `gdtr` can evaluate different parameter sets by providing arrays with
+    broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the
+    function for three different `a` at four positions `x` and ``b=3``,
+    resulting in a 3x4 array.
+
+    >>> a = np.array([[0.5], [1.5], [2.5]])
+    >>> x = np.array([1., 2., 3., 4])
+    >>> a.shape, x.shape
+    ((3, 1), (4,))
+
+    >>> gdtr(a, 3., x)
+    array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],
+           [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],
+           [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])
+
+    Plot the function for four different parameter sets.
+
+    >>> a_parameters = [0.3, 1, 2, 6]
+    >>> b_parameters = [2, 10, 15, 20]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     a, b, style = parameter_set
+    ...     gdtr_vals = gdtr(a, b, x)
+    ...     ax.plot(x, gdtr_vals, label=fr"$a= {a},\, b={b}$", ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("Gamma distribution cumulative distribution function")
+    >>> plt.show()
+
+    The gamma distribution is also available as `scipy.stats.gamma`. Using
+    `gdtr` directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.gamma`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.
+
+    >>> from scipy.stats import gamma
+    >>> a = 2.
+    >>> b = 3
+    >>> x = 1.
+    >>> gdtr_result = gdtr(a, b, x)  # this will often be faster than below
+    >>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)
+    >>> gdtr_result == gamma_dist_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("gdtrc",
+    r"""
+    gdtrc(a, b, x, out=None)
+
+    Gamma distribution survival function.
+
+    Integral from `x` to infinity of the gamma probability density function,
+
+    .. math::
+
+        F = \int_x^\infty \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt,
+
+    where :math:`\Gamma` is the gamma function.
+
+    Parameters
+    ----------
+    a : array_like
+        The rate parameter of the gamma distribution, sometimes denoted
+        :math:`\beta` (float). It is also the reciprocal of the scale
+        parameter :math:`\theta`.
+    b : array_like
+        The shape parameter of the gamma distribution, sometimes denoted
+        :math:`\alpha` (float).
+    x : array_like
+        The quantile (lower limit of integration; float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The survival function of the gamma distribution with parameters `a`
+        and `b` evaluated at `x`.
+
+    See Also
+    --------
+    gdtr: Gamma distribution cumulative distribution function
+    scipy.stats.gamma: Gamma distribution
+    gdtrix
+
+    Notes
+    -----
+    The evaluation is carried out using the relation to the incomplete gamma
+    integral (regularized gamma function).
+
+    Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can
+    improve performance compared to the ``sf`` method of `scipy.stats.gamma`
+    (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``a=1`` and ``b=2`` at ``x=5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import gdtrc
+    >>> import matplotlib.pyplot as plt
+    >>> gdtrc(1., 2., 5.)
+    0.04042768199451279
+
+    Compute the function for ``a=1``, ``b=2`` at several points by providing
+    a NumPy array for `x`.
+
+    >>> xvalues = np.array([1., 2., 3., 4])
+    >>> gdtrc(1., 1., xvalues)
+    array([0.36787944, 0.13533528, 0.04978707, 0.01831564])
+
+    `gdtrc` can evaluate different parameter sets by providing arrays with
+    broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the
+    function for three different `a` at four positions `x` and ``b=3``,
+    resulting in a 3x4 array.
+
+    >>> a = np.array([[0.5], [1.5], [2.5]])
+    >>> x = np.array([1., 2., 3., 4])
+    >>> a.shape, x.shape
+    ((3, 1), (4,))
+
+    >>> gdtrc(a, 3., x)
+    array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],
+           [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],
+           [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])
+
+    Plot the function for four different parameter sets.
+
+    >>> a_parameters = [0.3, 1, 2, 6]
+    >>> b_parameters = [2, 10, 15, 20]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     a, b, style = parameter_set
+    ...     gdtrc_vals = gdtrc(a, b, x)
+    ...     ax.plot(x, gdtrc_vals, label=fr"$a= {a},\, b={b}$", ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("Gamma distribution survival function")
+    >>> plt.show()
+
+    The gamma distribution is also available as `scipy.stats.gamma`.
+    Using `gdtrc` directly can be much faster than calling the ``sf`` method
+    of `scipy.stats.gamma`, especially for small arrays or individual
+    values. To get the same results one must use the following parametrization:
+    ``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.
+
+    >>> from scipy.stats import gamma
+    >>> a = 2
+    >>> b = 3
+    >>> x = 1.
+    >>> gdtrc_result = gdtrc(a, b, x)  # this will often be faster than below
+    >>> gamma_dist_result = gamma(b, scale=1/a).sf(x)
+    >>> gdtrc_result == gamma_dist_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("gdtria",
+    """
+    gdtria(p, b, x, out=None)
+
+    Inverse of `gdtr` vs a.
+
+    Returns the inverse with respect to the parameter `a` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability values.
+    b : array_like
+        `b` parameter values of `gdtr(a, b, x)`. `b` is the "shape" parameter
+        of the gamma distribution.
+    x : array_like
+        Nonnegative real values, from the domain of the gamma distribution.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`.  `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    a : scalar or ndarray
+        Values of the `a` parameter such that ``p = gdtr(a, b, x)`.  ``1/a``
+        is the "scale" parameter of the gamma distribution.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.
+    gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `a` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `a`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Computation of the incomplete gamma function ratios and their
+           inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtria
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtria(p, 3.4, 5.6)
+    1.2
+    """)
+
+add_newdoc("gdtrib",
+    """
+    gdtrib(a, p, x, out=None)
+
+    Inverse of `gdtr` vs b.
+
+    Returns the inverse with respect to the parameter `b` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the "scale"
+        parameter of the gamma distribution.
+    p : array_like
+        Probability values.
+    x : array_like
+        Nonnegative real values, from the domain of the gamma distribution.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`.  `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    b : scalar or ndarray
+        Values of the `b` parameter such that `p = gdtr(a, b, x)`.  `b` is
+        the "shape" parameter of the gamma distribution.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.
+    gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.
+
+    Notes
+    -----
+
+    The cumulative distribution function `p` is computed using the Cephes [1]_
+    routines `igam` and `igamc`. Computation of `b` involves a search for a value
+    that produces the desired value of `p` using Chandrupatla's bracketing
+    root finding algorithm [2]_.
+
+    Note that there are some edge cases where `gdtrib` is extended by taking
+    limits where they are uniquely defined. In particular
+    ``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.
+    For these edge cases, a numerical result will be returned for
+    ``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is
+    undefined.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [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), 145-149.
+           https://doi.org/10.1016/s0965-9978(96)00051-8
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtrib
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtrib(1.2, p, 5.6)
+    3.3999999999999995
+    """)
+
+add_newdoc("gdtrix",
+    """
+    gdtrix(a, b, p, out=None)
+
+    Inverse of `gdtr` vs x.
+
+    Returns the inverse with respect to the parameter `x` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution. This is also known as the pth quantile of the
+    distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the "scale"
+        parameter of the gamma distribution.
+    b : array_like
+        `b` parameter values of ``gdtr(a, b, x)``. `b` is the "shape" parameter
+        of the gamma distribution.
+    p : array_like
+        Probability values.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`. `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Values of the `x` parameter such that `p = gdtr(a, b, x)`.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.
+    gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `x` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `x`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Computation of the incomplete gamma function ratios and their
+           inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtrix
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtrix(1.2, 3.4, p)
+    5.5999999999999996
+    """)
+
+add_newdoc("hankel1",
+    r"""
+    hankel1(v, z, out=None)
+
+    Hankel function of the first kind
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Hankel function of the first kind.
+
+    See Also
+    --------
+    hankel1e : ndarray
+        This function with leading exponential behavior stripped off.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(1)}_v(z) =
+              \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel1e",
+    r"""
+    hankel1e(v, z, out=None)
+
+    Exponentially scaled Hankel function of the first kind
+
+    Defined as::
+
+        hankel1e(v, z) = hankel1(v, z) * exp(-1j * z)
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled Hankel function.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(1)}_v(z) =
+              \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel2",
+    r"""
+    hankel2(v, z, out=None)
+
+    Hankel function of the second kind
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Hankel function of the second kind.
+
+    See Also
+    --------
+    hankel2e : this function with leading exponential behavior stripped off.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(2)}_v(z) =
+              -\frac{2}{\imath\pi} \exp(\imath \pi v/2) K_v(z \exp(\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel2e",
+    r"""
+    hankel2e(v, z, out=None)
+
+    Exponentially scaled Hankel function of the second kind
+
+    Defined as::
+
+        hankel2e(v, z) = hankel2(v, z) * exp(1j * z)
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled Hankel function of the second kind.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(2)}_v(z) = -\frac{2}{\imath\pi}
+              \exp(\frac{\imath \pi v}{2}) K_v(z exp(\frac{\imath\pi}{2}))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    """)
+
+add_newdoc("huber",
+    r"""
+    huber(delta, r, out=None)
+
+    Huber loss function.
+
+    .. math:: \text{huber}(\delta, r) = \begin{cases} \infty & \delta < 0  \\
+              \frac{1}{2}r^2 & 0 \le \delta, | r | \le \delta \\
+              \delta ( |r| - \frac{1}{2}\delta ) & \text{otherwise} \end{cases}
+
+    Parameters
+    ----------
+    delta : ndarray
+        Input array, indicating the quadratic vs. linear loss changepoint.
+    r : ndarray
+        Input array, possibly representing residuals.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The computed Huber loss function values.
+
+    See Also
+    --------
+    pseudo_huber : smooth approximation of this function
+
+    Notes
+    -----
+    `huber` is useful as a loss function in robust statistics or machine
+    learning to reduce the influence of outliers as compared to the common
+    squared error loss, residuals with a magnitude higher than `delta` are
+    not squared [1]_.
+
+    Typically, `r` represents residuals, the difference
+    between a model prediction and data. Then, for :math:`|r|\leq\delta`,
+    `huber` resembles the squared error and for :math:`|r|>\delta` the
+    absolute error. This way, the Huber loss often achieves
+    a fast convergence in model fitting for small residuals like the squared
+    error loss function and still reduces the influence of outliers
+    (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is
+    the cutoff between squared and absolute error regimes, it has
+    to be tuned carefully for each problem. `huber` is also
+    convex, making it suitable for gradient based optimization.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Peter Huber. "Robust Estimation of a Location Parameter",
+           1964. Annals of Statistics. 53 (1): 73 - 101.
+
+    Examples
+    --------
+    Import all necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.special import huber
+    >>> import matplotlib.pyplot as plt
+
+    Compute the function for ``delta=1`` at ``r=2``
+
+    >>> huber(1., 2.)
+    1.5
+
+    Compute the function for different `delta` by providing a NumPy array or
+    list for `delta`.
+
+    >>> huber([1., 3., 5.], 4.)
+    array([3.5, 7.5, 8. ])
+
+    Compute the function at different points by providing a NumPy array or
+    list for `r`.
+
+    >>> huber(2., np.array([1., 1.5, 3.]))
+    array([0.5  , 1.125, 4.   ])
+
+    The function can be calculated for different `delta` and `r` by
+    providing arrays for both with compatible shapes for broadcasting.
+
+    >>> r = np.array([1., 2.5, 8., 10.])
+    >>> deltas = np.array([[1.], [5.], [9.]])
+    >>> print(r.shape, deltas.shape)
+    (4,) (3, 1)
+
+    >>> huber(deltas, r)
+    array([[ 0.5  ,  2.   ,  7.5  ,  9.5  ],
+           [ 0.5  ,  3.125, 27.5  , 37.5  ],
+           [ 0.5  ,  3.125, 32.   , 49.5  ]])
+
+    Plot the function for different `delta`.
+
+    >>> x = np.linspace(-4, 4, 500)
+    >>> deltas = [1, 2, 3]
+    >>> linestyles = ["dashed", "dotted", "dashdot"]
+    >>> fig, ax = plt.subplots()
+    >>> combined_plot_parameters = list(zip(deltas, linestyles))
+    >>> for delta, style in combined_plot_parameters:
+    ...     ax.plot(x, huber(delta, x), label=fr"$\delta={delta}$", ls=style)
+    >>> ax.legend(loc="upper center")
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title(r"Huber loss function $h_{\delta}(x)$")
+    >>> ax.set_xlim(-4, 4)
+    >>> ax.set_ylim(0, 8)
+    >>> plt.show()
+    """)
+
+add_newdoc("hyp0f1",
+    r"""
+    hyp0f1(v, z, out=None)
+
+    Confluent hypergeometric limit function 0F1.
+
+    Parameters
+    ----------
+    v : array_like
+        Real-valued parameter
+    z : array_like
+        Real- or complex-valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The confluent hypergeometric limit function
+
+    Notes
+    -----
+    This function is defined as:
+
+    .. math:: _0F_1(v, z) = \sum_{k=0}^{\infty}\frac{z^k}{(v)_k k!}.
+
+    It's also the limit as :math:`q \to \infty` of :math:`_1F_1(q; v; z/q)`,
+    and satisfies the differential equation :math:`f''(z) + vf'(z) =
+    f(z)`. See [1]_ for more information.
+
+    References
+    ----------
+    .. [1] Wolfram MathWorld, "Confluent Hypergeometric Limit Function",
+           http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is one when `z` is zero.
+
+    >>> sc.hyp0f1(1, 0)
+    1.0
+
+    It is the limit of the confluent hypergeometric function as `q`
+    goes to infinity.
+
+    >>> q = np.array([1, 10, 100, 1000])
+    >>> v = 1
+    >>> z = 1
+    >>> sc.hyp1f1(q, v, z / q)
+    array([2.71828183, 2.31481985, 2.28303778, 2.27992985])
+    >>> sc.hyp0f1(v, z)
+    2.2795853023360673
+
+    It is related to Bessel functions.
+
+    >>> n = 1
+    >>> x = np.linspace(0, 1, 5)
+    >>> sc.jv(n, x)
+    array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])
+    >>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)
+    array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])
+
+    """)
+
+add_newdoc("hyp1f1",
+    r"""
+    hyp1f1(a, b, x, out=None)
+
+    Confluent hypergeometric function 1F1.
+
+    The confluent hypergeometric function is defined by the series
+
+    .. math::
+
+       {}_1F_1(a; b; x) = \sum_{k = 0}^\infty \frac{(a)_k}{(b)_k k!} x^k.
+
+    See [dlmf]_ for more details. Here :math:`(\cdot)_k` is the
+    Pochhammer symbol; see `poch`.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real parameters
+    x : array_like
+        Real or complex argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the confluent hypergeometric function
+
+    See Also
+    --------
+    hyperu : another confluent hypergeometric function
+    hyp0f1 : confluent hypergeometric limit function
+    hyp2f1 : Gaussian hypergeometric function
+
+    Notes
+    -----
+    For real values, this function uses the ``hyp1f1`` routine from the C++ Boost
+    library [2]_, for complex values a C translation of the specfun
+    Fortran library [3]_.
+
+    References
+    ----------
+    .. [dlmf] NIST Digital Library of Mathematical Functions
+              https://dlmf.nist.gov/13.2#E2
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [3] Zhang, Jin, "Computation of Special Functions", John Wiley
+           and Sons, Inc, 1996.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is one when `x` is zero:
+
+    >>> sc.hyp1f1(0.5, 0.5, 0)
+    1.0
+
+    It is singular when `b` is a nonpositive integer.
+
+    >>> sc.hyp1f1(0.5, -1, 0)
+    inf
+
+    It is a polynomial when `a` is a nonpositive integer.
+
+    >>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])
+    >>> sc.hyp1f1(a, b, x)
+    array([-1., -3., -5., -7.])
+    >>> 1 + (a / b) * x
+    array([-1., -3., -5., -7.])
+
+    It reduces to the exponential function when ``a = b``.
+
+    >>> sc.hyp1f1(2, 2, [1, 2, 3, 4])
+    array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])
+    >>> np.exp([1, 2, 3, 4])
+    array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])
+
+    """)
+
+add_newdoc("hyperu",
+    r"""
+    hyperu(a, b, x, out=None)
+
+    Confluent hypergeometric function U
+
+    It is defined as the solution to the equation
+
+    .. math::
+
+       x \frac{d^2w}{dx^2} + (b - x) \frac{dw}{dx} - aw = 0
+
+    which satisfies the property
+
+    .. math::
+
+       U(a, b, x) \sim x^{-a}
+
+    as :math:`x \to \infty`. See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real-valued parameters
+    x : array_like
+        Real-valued argument
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of `U`
+
+    References
+    ----------
+    .. [dlmf] NIST Digital Library of Mathematics Functions
+              https://dlmf.nist.gov/13.2#E6
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It has a branch cut along the negative `x` axis.
+
+    >>> x = np.linspace(-0.1, -10, 5)
+    >>> sc.hyperu(1, 1, x)
+    array([nan, nan, nan, nan, nan])
+
+    It approaches zero as `x` goes to infinity.
+
+    >>> x = np.array([1, 10, 100])
+    >>> sc.hyperu(1, 1, x)
+    array([0.59634736, 0.09156333, 0.00990194])
+
+    It satisfies Kummer's transformation.
+
+    >>> a, b, x = 2, 1, 1
+    >>> sc.hyperu(a, b, x)
+    0.1926947246463881
+    >>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)
+    0.1926947246463881
+
+    """)
+
+add_newdoc("_igam_fac",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("iv",
+    r"""
+    iv(v, z, out=None)
+
+    Modified Bessel function of the first kind of real order.
+
+    Parameters
+    ----------
+    v : array_like
+        Order. If `z` is of real type and negative, `v` must be integer
+        valued.
+    z : array_like of float or complex
+        Argument.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the modified Bessel function.
+
+    See Also
+    --------
+    ive : This function with leading exponential behavior stripped off.
+    i0 : Faster version of this function for order 0.
+    i1 : Faster version of this function for order 1.
+
+    Notes
+    -----
+    For real `z` and :math:`v \in [-50, 50]`, the evaluation is carried out
+    using Temme's method [1]_.  For larger orders, uniform asymptotic
+    expansions are applied.
+
+    For complex `z` and positive `v`, the AMOS [2]_ `zbesi` routine is
+    called. It uses a power series for small `z`, the asymptotic expansion
+    for large `abs(z)`, the Miller algorithm normalized by the Wronskian
+    and a Neumann series for intermediate magnitudes, and the uniform
+    asymptotic expansions for :math:`I_v(z)` and :math:`J_v(z)` for large
+    orders. Backward recurrence is used to generate sequences or reduce
+    orders when necessary.
+
+    The calculations above are done in the right half plane and continued
+    into the left half plane by the formula,
+
+    .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z)
+
+    (valid when the real part of `z` is positive).  For negative `v`, the
+    formula
+
+    .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z)
+
+    is used, where :math:`K_v(z)` is the modified Bessel function of the
+    second kind, evaluated using the AMOS routine `zbesk`.
+
+    References
+    ----------
+    .. [1] Temme, Journal of Computational Physics, vol 21, 343 (1976)
+    .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import iv
+    >>> iv(0, 1.)
+    1.2660658777520084
+
+    Evaluate the function at one point for different orders.
+
+    >>> iv(0, 1.), iv(1, 1.), iv(1.5, 1.)
+    (1.2660658777520084, 0.565159103992485, 0.2935253263474798)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> iv([0, 1, 1.5], 1.)
+    array([1.26606588, 0.5651591 , 0.29352533])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([-2., 0., 3.])
+    >>> iv(0, points)
+    array([2.2795853 , 1.        , 4.88079259])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> iv(orders, points)
+    array([[ 2.2795853 ,  1.        ,  4.88079259],
+           [-1.59063685,  0.        ,  3.95337022]])
+
+    Plot the functions of order 0 to 3 from -5 to 5.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-5., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, iv(i, x), label=f'$I_{i!r}$')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("ive",
+    r"""
+    ive(v, z, out=None)
+
+    Exponentially scaled modified Bessel function of the first kind.
+
+    Defined as::
+
+        ive(v, z) = iv(v, z) * exp(-abs(z.real))
+
+    For imaginary numbers without a real part, returns the unscaled
+    Bessel function of the first kind `iv`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order.
+    z : array_like of float or complex
+        Argument.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled modified Bessel function.
+
+    See Also
+    --------
+    iv: Modified Bessel function of the first kind
+    i0e: Faster implementation of this function for order 0
+    i1e: Faster implementation of this function for order 1
+
+    Notes
+    -----
+    For positive `v`, the AMOS [1]_ `zbesi` routine is called. It uses a
+    power series for small `z`, the asymptotic expansion for large
+    `abs(z)`, the Miller algorithm normalized by the Wronskian and a
+    Neumann series for intermediate magnitudes, and the uniform asymptotic
+    expansions for :math:`I_v(z)` and :math:`J_v(z)` for large orders.
+    Backward recurrence is used to generate sequences or reduce orders when
+    necessary.
+
+    The calculations above are done in the right half plane and continued
+    into the left half plane by the formula,
+
+    .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z)
+
+    (valid when the real part of `z` is positive).  For negative `v`, the
+    formula
+
+    .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z)
+
+    is used, where :math:`K_v(z)` is the modified Bessel function of the
+    second kind, evaluated using the AMOS routine `zbesk`.
+
+    `ive` is useful for large arguments `z`: for these, `iv` easily overflows,
+    while `ive` does not due to the exponential scaling.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    In the following example `iv` returns infinity whereas `ive` still returns
+    a finite number.
+
+    >>> from scipy.special import iv, ive
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> iv(3, 1000.), ive(3, 1000.)
+    (inf, 0.01256056218254712)
+
+    Evaluate the function at one point for different orders by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> ive([0, 1, 1.5], 1.)
+    array([0.46575961, 0.20791042, 0.10798193])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> points = np.array([-2., 0., 3.])
+    >>> ive(0, points)
+    array([0.30850832, 1.        , 0.24300035])
+
+    Evaluate the function at several points for different orders by
+    providing arrays for both `v` for `z`. Both arrays have to be
+    broadcastable to the correct shape. To calculate the orders 0, 1
+    and 2 for a 1D array of points:
+
+    >>> ive([[0], [1], [2]], points)
+    array([[ 0.30850832,  1.        ,  0.24300035],
+           [-0.21526929,  0.        ,  0.19682671],
+           [ 0.09323903,  0.        ,  0.11178255]])
+
+    Plot the functions of order 0 to 3 from -5 to 5.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-5., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, ive(i, x), label=fr'$I_{i!r}(z)\cdot e^{{-|z|}}$')
+    >>> ax.legend()
+    >>> ax.set_xlabel(r"$z$")
+    >>> plt.show()
+    """)
+
+add_newdoc("jn",
+    """
+    jn(n, x, out=None)
+
+    Bessel function of the first kind of integer order and real argument.
+
+    Parameters
+    ----------
+    n : array_like
+        order of the Bessel function
+    x : array_like
+        argument of the Bessel function
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the bessel function
+
+    See Also
+    --------
+    jv
+    spherical_jn : spherical Bessel functions.
+
+    Notes
+    -----
+    `jn` is an alias of `jv`.
+    Not to be confused with the spherical Bessel functions (see
+    `spherical_jn`).
+
+    """)
+
+add_newdoc("jv",
+    r"""
+    jv(v, z, out=None)
+
+    Bessel function of the first kind of real order and complex argument.
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    J : scalar or ndarray
+        Value of the Bessel function, :math:`J_v(z)`.
+
+    See Also
+    --------
+    jve : :math:`J_v` with leading exponential behavior stripped off.
+    spherical_jn : spherical Bessel functions.
+    j0 : faster version of this function for order 0.
+    j1 : faster version of this function for order 1.
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the AMOS
+    [1]_ `zbesj` routine, which exploits the connection to the modified
+    Bessel function :math:`I_v`,
+
+    .. math::
+        J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0)
+
+        J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0)
+
+    For negative `v` values the formula,
+
+    .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v)
+
+    is used, where :math:`Y_v(z)` is the Bessel function of the second
+    kind, computed using the AMOS routine `zbesy`.  Note that the second
+    term is exactly zero for integer `v`; to improve accuracy the second
+    term is explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Not to be confused with the spherical Bessel functions (see `spherical_jn`).
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import jv
+    >>> jv(0, 1.)
+    0.7651976865579666
+
+    Evaluate the function at one point for different orders.
+
+    >>> jv(0, 1.), jv(1, 1.), jv(1.5, 1.)
+    (0.7651976865579666, 0.44005058574493355, 0.24029783912342725)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> jv([0, 1, 1.5], 1.)
+    array([0.76519769, 0.44005059, 0.24029784])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([-2., 0., 3.])
+    >>> jv(0, points)
+    array([ 0.22389078,  1.        , -0.26005195])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> jv(orders, points)
+    array([[ 0.22389078,  1.        , -0.26005195],
+           [-0.57672481,  0.        ,  0.33905896]])
+
+    Plot the functions of order 0 to 3 from -10 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-10., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, jv(i, x), label=f'$J_{i!r}$')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("jve",
+    r"""
+    jve(v, z, out=None)
+
+    Exponentially scaled Bessel function of the first kind of order `v`.
+
+    Defined as::
+
+        jve(v, z) = jv(v, z) * exp(-abs(z.imag))
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    J : scalar or ndarray
+        Value of the exponentially scaled Bessel function.
+
+    See Also
+    --------
+    jv: Unscaled Bessel function of the first kind
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the AMOS
+    [1]_ `zbesj` routine, which exploits the connection to the modified
+    Bessel function :math:`I_v`,
+
+    .. math::
+        J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0)
+
+        J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0)
+
+    For negative `v` values the formula,
+
+    .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v)
+
+    is used, where :math:`Y_v(z)` is the Bessel function of the second
+    kind, computed using the AMOS routine `zbesy`.  Note that the second
+    term is exactly zero for integer `v`; to improve accuracy the second
+    term is explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Exponentially scaled Bessel functions are useful for large arguments `z`:
+    for these, the unscaled Bessel functions can easily under-or overflow.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compare the output of `jv` and `jve` for large complex arguments for `z`
+    by computing their values for order ``v=1`` at ``z=1000j``. We see that
+    `jv` overflows but `jve` returns a finite number:
+
+    >>> import numpy as np
+    >>> from scipy.special import jv, jve
+    >>> v = 1
+    >>> z = 1000j
+    >>> jv(v, z), jve(v, z)
+    ((inf+infj), (7.721967686709077e-19+0.012610930256928629j))
+
+    For real arguments for `z`, `jve` returns the same as `jv`.
+
+    >>> v, z = 1, 1000
+    >>> jv(v, z), jve(v, z)
+    (0.004728311907089523, 0.004728311907089523)
+
+    The function can be evaluated for several orders at the same time by
+    providing a list or NumPy array for `v`:
+
+    >>> jve([1, 3, 5], 1j)
+    array([1.27304208e-17+2.07910415e-01j, -4.99352086e-19-8.15530777e-03j,
+           6.11480940e-21+9.98657141e-05j])
+
+    In the same way, the function can be evaluated at several points in one
+    call by providing a list or NumPy array for `z`:
+
+    >>> jve(1, np.array([1j, 2j, 3j]))
+    array([1.27308412e-17+0.20791042j, 1.31814423e-17+0.21526929j,
+           1.20521602e-17+0.19682671j])
+
+    It is also possible to evaluate several orders at several points
+    at the same time by providing arrays for `v` and `z` with
+    compatible shapes for broadcasting. Compute `jve` for two different orders
+    `v` and three points `z` resulting in a 2x3 array.
+
+    >>> v = np.array([[1], [3]])
+    >>> z = np.array([1j, 2j, 3j])
+    >>> v.shape, z.shape
+    ((2, 1), (3,))
+
+    >>> jve(v, z)
+    array([[1.27304208e-17+0.20791042j,  1.31810070e-17+0.21526929j,
+            1.20517622e-17+0.19682671j],
+           [-4.99352086e-19-0.00815531j, -1.76289571e-18-0.02879122j,
+            -2.92578784e-18-0.04778332j]])
+    """)
+
+add_newdoc("kelvin",
+    """
+    kelvin(x, out=None)
+
+    Kelvin functions as complex numbers
+
+    Parameters
+    ----------
+    x : array_like
+        Argument
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    Be, Ke, Bep, Kep : 4-tuple of scalar or ndarray
+        The tuple (Be, Ke, Bep, Kep) contains complex numbers
+        representing the real and imaginary Kelvin functions and their
+        derivatives evaluated at `x`.  For example, kelvin(x)[0].real =
+        ber x and kelvin(x)[0].imag = bei x with similar relationships
+        for ker and kei.
+    """)
+
+add_newdoc("ker",
+    r"""
+    ker(x, out=None)
+
+    Kelvin function ker.
+
+    Defined as
+
+    .. math::
+
+        \mathrm{ker}(x) = \Re[K_0(x e^{\pi i / 4})]
+
+    Where :math:`K_0` is the modified Bessel function of the second
+    kind (see `kv`). See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Kelvin function.
+
+    See Also
+    --------
+    kei : the corresponding imaginary part
+    kerp : the derivative of ker
+    kv : modified Bessel function of the second kind
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/10.61
+
+    Examples
+    --------
+    It can be expressed using the modified Bessel function of the
+    second kind.
+
+    >>> import numpy as np
+    >>> import scipy.special as sc
+    >>> x = np.array([1.0, 2.0, 3.0, 4.0])
+    >>> sc.kv(0, x * np.exp(np.pi * 1j / 4)).real
+    array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885])
+    >>> sc.ker(x)
+    array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885])
+
+    """)
+
+add_newdoc("kerp",
+    r"""
+    kerp(x, out=None)
+
+    Derivative of the Kelvin function ker.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of ker.
+
+    See Also
+    --------
+    ker
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/10#PT5
+
+    """)
+
+add_newdoc("kl_div",
+    r"""
+    kl_div(x, y, out=None)
+
+    Elementwise function for computing Kullback-Leibler divergence.
+
+    .. math::
+
+        \mathrm{kl\_div}(x, y) =
+          \begin{cases}
+            x \log(x / y) - x + y & x > 0, y > 0 \\
+            y & x = 0, y \ge 0 \\
+            \infty & \text{otherwise}
+          \end{cases}
+
+    Parameters
+    ----------
+    x, y : array_like
+        Real arguments
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Kullback-Liebler divergence.
+
+    See Also
+    --------
+    entr, rel_entr, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is non-negative and is jointly convex in `x` and `y`.
+
+    The origin of this function is in convex programming; see [1]_ for
+    details. This is why the function contains the extra :math:`-x
+    + y` terms over what might be expected from the Kullback-Leibler
+    divergence. For a version of the function without the extra terms,
+    see `rel_entr`.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+
+    """)
+
+add_newdoc("kn",
+    r"""
+    kn(n, x, out=None)
+
+    Modified Bessel function of the second kind of integer order `n`
+
+    Returns the modified Bessel function of the second kind for integer order
+    `n` at real `z`.
+
+    These are also sometimes called functions of the third kind, Basset
+    functions, or Macdonald functions.
+
+    Parameters
+    ----------
+    n : array_like of int
+        Order of Bessel functions (floats will truncate with a warning)
+    x : array_like of float
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Modified Bessel function of the second kind,
+        :math:`K_n(x)`.
+
+    See Also
+    --------
+    kv : Same function, but accepts real order and complex argument
+    kvp : Derivative of this function
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+
+    Examples
+    --------
+    Plot the function of several orders for real input:
+
+    >>> import numpy as np
+    >>> from scipy.special import kn
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> for N in range(6):
+    ...     plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))
+    >>> plt.ylim(0, 10)
+    >>> plt.legend()
+    >>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')
+    >>> plt.show()
+
+    Calculate for a single value at multiple orders:
+
+    >>> kn([4, 5, 6], 1)
+    array([   44.23241585,   360.9605896 ,  3653.83831186])
+    """)
+
+add_newdoc("kolmogi",
+    """
+    kolmogi(p, out=None)
+
+    Inverse Survival Function of Kolmogorov distribution
+
+    It is the inverse function to `kolmogorov`.
+    Returns y such that ``kolmogorov(y) == p``.
+
+    Parameters
+    ----------
+    p : float array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of kolmogi(p)
+
+    See Also
+    --------
+    kolmogorov : The Survival Function for the distribution
+    scipy.stats.kstwobign : Provides the functionality as a continuous distribution
+    smirnov, smirnovi : Functions for the one-sided distribution
+
+    Notes
+    -----
+    `kolmogorov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.kstwobign` distribution.
+
+    Examples
+    --------
+    >>> from scipy.special import kolmogi
+    >>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])
+    array([        inf,  1.22384787,  1.01918472,  0.82757356,  0.67644769,
+            0.57117327,  0.        ])
+
+    """)
+
+add_newdoc("kolmogorov",
+    r"""
+    kolmogorov(y, out=None)
+
+    Complementary cumulative distribution (Survival Function) function of
+    Kolmogorov distribution.
+
+    Returns the complementary cumulative distribution function of
+    Kolmogorov's limiting distribution (``D_n*\sqrt(n)`` as n goes to infinity)
+    of a two-sided test for equality between an empirical and a theoretical
+    distribution. It is equal to the (limit as n->infinity of the)
+    probability that ``sqrt(n) * max absolute deviation > y``.
+
+    Parameters
+    ----------
+    y : float array_like
+      Absolute deviation between the Empirical CDF (ECDF) and the target CDF,
+      multiplied by sqrt(n).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of kolmogorov(y)
+
+    See Also
+    --------
+    kolmogi : The Inverse Survival Function for the distribution
+    scipy.stats.kstwobign : Provides the functionality as a continuous distribution
+    smirnov, smirnovi : Functions for the one-sided distribution
+
+    Notes
+    -----
+    `kolmogorov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.kstwobign` distribution.
+
+    Examples
+    --------
+    Show the probability of a gap at least as big as 0, 0.5 and 1.0.
+
+    >>> import numpy as np
+    >>> from scipy.special import kolmogorov
+    >>> from scipy.stats import kstwobign
+    >>> kolmogorov([0, 0.5, 1.0])
+    array([ 1.        ,  0.96394524,  0.26999967])
+
+    Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against
+    the target distribution, a Normal(0, 1) distribution.
+
+    >>> from scipy.stats import norm, laplace
+    >>> rng = np.random.default_rng()
+    >>> n = 1000
+    >>> lap01 = laplace(0, 1)
+    >>> x = np.sort(lap01.rvs(n, random_state=rng))
+    >>> np.mean(x), np.std(x)
+    (-0.05841730131499543, 1.3968109101997568)
+
+    Construct the Empirical CDF and the K-S statistic Dn.
+
+    >>> target = norm(0,1)  # Normal mean 0, stddev 1
+    >>> cdfs = target.cdf(x)
+    >>> ecdfs = np.arange(n+1, dtype=float)/n
+    >>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])
+    >>> Dn = np.max(gaps)
+    >>> Kn = np.sqrt(n) * Dn
+    >>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))
+    Dn=0.043363, sqrt(n)*Dn=1.371265
+    >>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',
+    ...   ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %
+    ...    (Kn, kolmogorov(Kn)),
+    ...   ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %
+    ...    (Kn, kstwobign.cdf(Kn))]))
+    For a sample of size n drawn from a N(0, 1) distribution:
+     the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533
+     the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467
+
+    Plot the Empirical CDF against the target N(0, 1) CDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')
+    >>> x3 = np.linspace(-3, 3, 100)
+    >>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')
+    >>> plt.ylim([0, 1]); plt.grid(True); plt.legend();
+    >>> # Add vertical lines marking Dn+ and Dn-
+    >>> iminus, iplus = np.argmax(gaps, axis=0)
+    >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],
+    ...            color='r', linestyle='dashed', lw=4)
+    >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],
+    ...            color='r', linestyle='dashed', lw=4)
+    >>> plt.show()
+    """)
+
+add_newdoc("_kolmogc",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("_kolmogci",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("_kolmogp",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("kv",
+    r"""
+    kv(v, z, out=None)
+
+    Modified Bessel function of the second kind of real order `v`
+
+    Returns the modified Bessel function of the second kind for real order
+    `v` at complex `z`.
+
+    These are also sometimes called functions of the third kind, Basset
+    functions, or Macdonald functions.  They are defined as those solutions
+    of the modified Bessel equation for which,
+
+    .. math::
+        K_v(x) \sim \sqrt{\pi/(2x)} \exp(-x)
+
+    as :math:`x \to \infty` [3]_.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel functions
+    z : array_like of complex
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The results. Note that input must be of complex type to get complex
+        output, e.g. ``kv(3, -2+0j)`` instead of ``kv(3, -2)``.
+
+    See Also
+    --------
+    kve : This function with leading exponential behavior stripped off.
+    kvp : Derivative of this function
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+    .. [3] NIST Digital Library of Mathematical Functions,
+           Eq. 10.25.E3. https://dlmf.nist.gov/10.25.E3
+
+    Examples
+    --------
+    Plot the function of several orders for real input:
+
+    >>> import numpy as np
+    >>> from scipy.special import kv
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> for N in np.linspace(0, 6, 5):
+    ...     plt.plot(x, kv(N, x), label='$K_{{{}}}(x)$'.format(N))
+    >>> plt.ylim(0, 10)
+    >>> plt.legend()
+    >>> plt.title(r'Modified Bessel function of the second kind $K_\nu(x)$')
+    >>> plt.show()
+
+    Calculate for a single value at multiple orders:
+
+    >>> kv([4, 4.5, 5], 1+2j)
+    array([ 0.1992+2.3892j,  2.3493+3.6j   ,  7.2827+3.8104j])
+
+    """)
+
+add_newdoc("kve",
+    r"""
+    kve(v, z, out=None)
+
+    Exponentially scaled modified Bessel function of the second kind.
+
+    Returns the exponentially scaled, modified Bessel function of the
+    second kind (sometimes called the third kind) for real order `v` at
+    complex `z`::
+
+        kve(v, z) = kv(v, z) * exp(z)
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel functions
+    z : array_like of complex
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The exponentially scaled modified Bessel function of the second kind.
+
+    See Also
+    --------
+    kv : This function without exponential scaling.
+    k0e : Faster version of this function for order 0.
+    k1e : Faster version of this function for order 1.
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+
+    Examples
+    --------
+    In the following example `kv` returns 0 whereas `kve` still returns
+    a useful finite number.
+
+    >>> import numpy as np
+    >>> from scipy.special import kv, kve
+    >>> import matplotlib.pyplot as plt
+    >>> kv(3, 1000.), kve(3, 1000.)
+    (0.0, 0.03980696128440973)
+
+    Evaluate the function at one point for different orders by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> kve([0, 1, 1.5], 1.)
+    array([1.14446308, 1.63615349, 2.50662827])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> points = np.array([1., 3., 10.])
+    >>> kve(0, points)
+    array([1.14446308, 0.6977616 , 0.39163193])
+
+    Evaluate the function at several points for different orders by
+    providing arrays for both `v` for `z`. Both arrays have to be
+    broadcastable to the correct shape. To calculate the orders 0, 1
+    and 2 for a 1D array of points:
+
+    >>> kve([[0], [1], [2]], points)
+    array([[1.14446308, 0.6977616 , 0.39163193],
+           [1.63615349, 0.80656348, 0.41076657],
+           [4.41677005, 1.23547058, 0.47378525]])
+
+    Plot the functions of order 0 to 3 from 0 to 5.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, kve(i, x), label=fr'$K_{i!r}(z)\cdot e^z$')
+    >>> ax.legend()
+    >>> ax.set_xlabel(r"$z$")
+    >>> ax.set_ylim(0, 4)
+    >>> ax.set_xlim(0, 5)
+    >>> plt.show()
+    """)
+
+add_newdoc("_lanczos_sum_expg_scaled",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc(
+    "_landau_pdf",
+    """
+    _landau_pdf(x, loc, scale)
+
+    Probability density function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_cdf",
+    """
+    _landau_cdf(x, loc, scale)
+
+    Cumulative distribution function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_sf",
+    """
+    _landau_sf(x, loc, scale)
+
+    Survival function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_ppf",
+    """
+    _landau_ppf(p, loc, scale)
+
+    Percent point function of the Landau distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Real-valued argument between 0 and 1
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_isf",
+    """
+    _landau_isf(p, loc, scale)
+
+    Inverse survival function of the Landau distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Real-valued argument between 0 and 1
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc("_lgam1p",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("log1p",
+    """
+    log1p(x, out=None)
+
+    Calculates log(1 + x) for use when `x` is near zero.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of ``log(1 + x)``.
+
+    See Also
+    --------
+    expm1, cosm1
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is more accurate than using ``log(1 + x)`` directly for ``x``
+    near 0. Note that in the below example ``1 + 1e-17 == 1`` to
+    double precision.
+
+    >>> sc.log1p(1e-17)
+    1e-17
+    >>> np.log(1 + 1e-17)
+    0.0
+
+    """)
+
+add_newdoc("_log1pmx",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("lpmv",
+    r"""
+    lpmv(m, v, x, out=None)
+
+    Associated Legendre function of integer order and real degree.
+
+    Defined as
+
+    .. math::
+
+        P_v^m = (-1)^m (1 - x^2)^{m/2} \frac{d^m}{dx^m} P_v(x)
+
+    where
+
+    .. math::
+
+        P_v = \sum_{k = 0}^\infty \frac{(-v)_k (v + 1)_k}{(k!)^2}
+                \left(\frac{1 - x}{2}\right)^k
+
+    is the Legendre function of the first kind. Here :math:`(\cdot)_k`
+    is the Pochhammer symbol; see `poch`.
+
+    Parameters
+    ----------
+    m : array_like
+        Order (int or float). If passed a float not equal to an
+        integer the function returns NaN.
+    v : array_like
+        Degree (float).
+    x : array_like
+        Argument (float). Must have ``|x| <= 1``.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    pmv : scalar or ndarray
+        Value of the associated Legendre function.
+
+    See Also
+    --------
+    lpmn : Compute the associated Legendre function for all orders
+           ``0, ..., m`` and degrees ``0, ..., n``.
+    clpmn : Compute the associated Legendre function at complex
+            arguments.
+
+    Notes
+    -----
+    Note that this implementation includes the Condon-Shortley phase.
+
+    References
+    ----------
+    .. [1] Zhang, Jin, "Computation of Special Functions", John Wiley
+           and Sons, Inc, 1996.
+
+    """)
+
+add_newdoc("nbdtr",
+    r"""
+    nbdtr(k, n, p, out=None)
+
+    Negative binomial cumulative distribution function.
+
+    Returns the sum of the terms 0 through `k` of the negative binomial
+    distribution probability mass function,
+
+    .. math::
+
+        F = \sum_{j=0}^k {{n + j - 1}\choose{j}} p^n (1 - p)^j.
+
+    In a sequence of Bernoulli trials with individual success probabilities
+    `p`, this is the probability that `k` or fewer failures precede the nth
+    success.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The probability of `k` or fewer failures before `n` successes in a
+        sequence of events with individual success probability `p`.
+
+    See Also
+    --------
+    nbdtrc : Negative binomial survival function
+    nbdtrik : Negative binomial quantile function
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    If floating point values are passed for `k` or `n`, they will be truncated
+    to integers.
+
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).
+
+    Wrapper for the Cephes [1]_ routine `nbdtr`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtr` directly can improve performance
+    compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtr
+    >>> nbdtr(10, 5, 0.5)
+    0.940765380859375
+
+    Compute the function for ``n=10`` and ``p=0.5`` at several points by
+    providing a NumPy array or list for `k`.
+
+    >>> nbdtr([5, 10, 15], 10, 0.5)
+    array([0.15087891, 0.58809853, 0.88523853])
+
+    Plot the function for four different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> k = np.arange(130)
+    >>> n_parameters = [20, 20, 20, 80]
+    >>> p_parameters = [0.2, 0.5, 0.8, 0.5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters,
+    ...                            linestyles))
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtr_vals = nbdtr(k, n, p)
+    ...     ax.plot(k, nbdtr_vals, label=rf"$n={n},\, p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$k$")
+    >>> ax.set_title("Negative binomial cumulative distribution function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than
+    calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small
+    arrays or individual values. To get the same results one must use the
+    following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.
+
+    >>> from scipy.stats import nbinom
+    >>> k, n, p = 5, 3, 0.5
+    >>> nbdtr_res = nbdtr(k, n, p)  # this will often be faster than below
+    >>> stats_res = nbinom(n, p).cdf(k)
+    >>> stats_res, nbdtr_res  # test that results are equal
+    (0.85546875, 0.85546875)
+
+    `nbdtr` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> p = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> nbdtr(k, 5, p)
+    array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],
+           [0.48450894, 0.94076538, 0.99932777, 0.99999999],
+           [0.76249222, 0.99409103, 0.99999445, 1.        ]])
+    """)
+
+add_newdoc("nbdtrc",
+    r"""
+    nbdtrc(k, n, p, out=None)
+
+    Negative binomial survival function.
+
+    Returns the sum of the terms `k + 1` to infinity of the negative binomial
+    distribution probability mass function,
+
+    .. math::
+
+        F = \sum_{j=k + 1}^\infty {{n + j - 1}\choose{j}} p^n (1 - p)^j.
+
+    In a sequence of Bernoulli trials with individual success probabilities
+    `p`, this is the probability that more than `k` failures precede the nth
+    success.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The probability of `k + 1` or more failures before `n` successes in a
+        sequence of events with individual success probability `p`.
+
+    See Also
+    --------
+    nbdtr : Negative binomial cumulative distribution function
+    nbdtrik : Negative binomial percentile function
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    If floating point values are passed for `k` or `n`, they will be truncated
+    to integers.
+
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).
+
+    Wrapper for the Cephes [1]_ routine `nbdtrc`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance
+    compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtrc
+    >>> nbdtrc(10, 5, 0.5)
+    0.059234619140624986
+
+    Compute the function for ``n=10`` and ``p=0.5`` at several points by
+    providing a NumPy array or list for `k`.
+
+    >>> nbdtrc([5, 10, 15], 10, 0.5)
+    array([0.84912109, 0.41190147, 0.11476147])
+
+    Plot the function for four different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> k = np.arange(130)
+    >>> n_parameters = [20, 20, 20, 80]
+    >>> p_parameters = [0.2, 0.5, 0.8, 0.5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters,
+    ...                            linestyles))
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtrc_vals = nbdtrc(k, n, p)
+    ...     ax.plot(k, nbdtrc_vals, label=rf"$n={n},\, p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$k$")
+    >>> ax.set_title("Negative binomial distribution survival function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than
+    calling the ``sf`` method of `scipy.stats.nbinom`, especially for small
+    arrays or individual values. To get the same results one must use the
+    following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.
+
+    >>> from scipy.stats import nbinom
+    >>> k, n, p = 3, 5, 0.5
+    >>> nbdtr_res = nbdtrc(k, n, p)  # this will often be faster than below
+    >>> stats_res = nbinom(n, p).sf(k)
+    >>> stats_res, nbdtr_res  # test that results are equal
+    (0.6367187499999999, 0.6367187499999999)
+
+    `nbdtrc` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> p = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> nbdtrc(k, 5, p)
+    array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],
+           [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],
+           [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])
+    """)
+
+add_newdoc(
+    "nbdtri",
+    r"""
+    nbdtri(k, n, y, out=None)
+
+    Returns the inverse with respect to the parameter `p` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    p : scalar or ndarray
+        Probability of success in a single event (float) such that
+        `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtrc : Negative binomial survival function.
+    scipy.stats.nbinom : negative binomial distribution.
+    nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.
+    nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    Wrapper for the Cephes [1]_ routine `nbdtri`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtri` directly can improve performance
+    compared to the ``ppf`` method of `scipy.stats.nbinom`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    `nbdtri` is the inverse of `nbdtr` with respect to `p`.
+    Up to floating point errors the following holds:
+    ``nbdtri(k, n, nbdtr(k, n, p))=p``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtri, nbdtr
+    >>> k, n, y = 5, 10, 0.2
+    >>> cdf_val = nbdtr(k, n, y)
+    >>> nbdtri(k, n, cdf_val)
+    0.20000000000000004
+
+    Compute the function for ``k=10`` and ``n=5`` at several points by
+    providing a NumPy array or list for `y`.
+
+    >>> y = np.array([0.1, 0.4, 0.8])
+    >>> nbdtri(3, 5, y)
+    array([0.34462319, 0.51653095, 0.69677416])
+
+    Plot the function for three different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> n_parameters = [5, 20, 30, 30]
+    >>> k_parameters = [20, 20, 60, 80]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))
+    >>> cdf_vals = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     n, k, style = parameter_set
+    ...     nbdtri_vals = nbdtri(k, n, cdf_vals)
+    ...     ax.plot(cdf_vals, nbdtri_vals, label=rf"$k={k},\ n={n}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_ylabel("$p$")
+    >>> ax.set_xlabel("$CDF$")
+    >>> title = "nbdtri: inverse of negative binomial CDF with respect to $p$"
+    >>> ax.set_title(title)
+    >>> plt.show()
+
+    `nbdtri` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> y = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, y.shape
+    ((3, 1), (4,))
+
+    >>> nbdtri(k, 5, y)
+    array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],
+           [0.24588501, 0.30451981, 0.36778453, 0.46397088],
+           [0.18362101, 0.22966758, 0.28054743, 0.36066188]])
+    """)
+
+add_newdoc("nbdtrik",
+    r"""
+    nbdtrik(y, n, p, out=None)
+
+    Negative binomial percentile function.
+
+    Returns the inverse with respect to the parameter `k` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    k : scalar or ndarray
+        The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtrc : Survival function of the negative binomial.
+    nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.
+    nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.
+
+    Formula 26.5.26 of [2]_,
+
+    .. math::
+        \sum_{j=k + 1}^\infty {{n + j - 1}
+        \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),
+
+    is used to reduce calculation of the cumulative distribution function to
+    that of a regularized incomplete beta :math:`I`.
+
+    Computation of `k` involves a search for a value that produces the desired
+    value of `y`.  The search relies on the monotonicity of `y` with `k`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Compute the negative binomial cumulative distribution function for an
+    exemplary parameter set.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtr, nbdtrik
+    >>> k, n, p = 5, 2, 0.5
+    >>> cdf_value = nbdtr(k, n, p)
+    >>> cdf_value
+    0.9375
+
+    Verify that `nbdtrik` recovers the original value for `k`.
+
+    >>> nbdtrik(cdf_value, n, p)
+    5.0
+
+    Plot the function for different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> p_parameters = [0.2, 0.5, 0.7, 0.5]
+    >>> n_parameters = [30, 30, 30, 80]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))
+    >>> cdf_vals = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtrik_vals = nbdtrik(cdf_vals, n, p)
+    ...     ax.plot(cdf_vals, nbdtrik_vals, label=rf"$n={n},\ p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_ylabel("$k$")
+    >>> ax.set_xlabel("$CDF$")
+    >>> ax.set_title("Negative binomial percentile function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. The percentile function  method ``ppf``
+    returns the result of `nbdtrik` rounded up to integers:
+
+    >>> from scipy.stats import nbinom
+    >>> q, n, p = 0.6, 5, 0.5
+    >>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)
+    (5.0, 4.800428460273882)
+
+    """)
+
+add_newdoc("nbdtrin",
+    r"""
+    nbdtrin(k, y, p, out=None)
+
+    Inverse of `nbdtr` vs `n`.
+
+    Returns the inverse with respect to the parameter `n` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    n : scalar or ndarray
+        The number of successes `n` such that `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.
+    nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.
+
+    Formula 26.5.26 of [2]_,
+
+    .. math::
+        \sum_{j=k + 1}^\infty {{n + j - 1}
+        \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),
+
+    is used to reduce calculation of the cumulative distribution function to
+    that of a regularized incomplete beta :math:`I`.
+
+    Computation of `n` involves a search for a value that produces the desired
+    value of `y`.  The search relies on the monotonicity of `y` with `n`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Compute the negative binomial cumulative distribution function for an
+    exemplary parameter set.
+
+    >>> from scipy.special import nbdtr, nbdtrin
+    >>> k, n, p = 5, 2, 0.5
+    >>> cdf_value = nbdtr(k, n, p)
+    >>> cdf_value
+    0.9375
+
+    Verify that `nbdtrin` recovers the original value for `n` up to floating
+    point accuracy.
+
+    >>> nbdtrin(k, cdf_value, p)
+    1.999999999998137
+    """)
+
+add_newdoc("ncfdtr",
+    r"""
+    ncfdtr(dfn, dfd, nc, f, out=None)
+
+    Cumulative distribution function of the non-central F distribution.
+
+    The non-central F describes the distribution of,
+
+    .. math::
+        Z = \frac{X/d_n}{Y/d_d}
+
+    where :math:`X` and :math:`Y` are independently distributed, with
+    :math:`X` distributed non-central :math:`\chi^2` with noncentrality
+    parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`
+    distributed :math:`\chi^2` with :math:`d_d` degrees of freedom.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares.  Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Range [0, inf).
+    f : array_like
+        Quantiles, i.e. the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        The calculated CDF.  If all inputs are scalar, the return will be a
+        float.  Otherwise it will be an array.
+
+    See Also
+    --------
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+    scipy.stats.ncf : Non-central F distribution.
+
+    Notes
+    -----
+    This function calculates the CDF of the non-central f distribution using
+    the Boost Math C++ library [1]_.
+
+    The cumulative distribution function is computed using Formula 26.6.20 of
+    [2]_:
+
+    .. math::
+        F(d_n, d_d, n_c, f) = \sum_{j=0}^\infty e^{-n_c/2}
+        \frac{(n_c/2)^j}{j!} I_{x}(\frac{d_n}{2} + j, \frac{d_d}{2}),
+
+    where :math:`I` is the regularized incomplete beta function, and
+    :math:`x = f d_n/(f d_n + d_d)`.
+
+    Note that argument order of `ncfdtr` is different from that of the
+    similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last
+    parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Plot the CDF of the non-central F distribution, for nc=0.  Compare with the
+    F-distribution from scipy.stats:
+
+    >>> x = np.linspace(-1, 8, num=500)
+    >>> dfn = 3
+    >>> dfd = 2
+    >>> ncf_stats = stats.f.cdf(x, dfn, dfd)
+    >>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, ncf_stats, 'b-', lw=3)
+    >>> ax.plot(x, ncf_special, 'r-')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("ncfdtri",
+    """
+    ncfdtri(dfn, dfd, nc, p, out=None)
+
+    Inverse with respect to `f` of the CDF of the non-central F distribution.
+
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares.  Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Range [0, inf).
+    p : array_like
+        Value of the cumulative distribution function.  Must be in the
+        range [0, 1].
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    f : scalar or ndarray
+        Quantiles, i.e., the upper limit of integration.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+    scipy.stats.ncf : Non-central F distribution.
+
+    Notes
+    -----
+    This function calculates the Quantile of the non-central f distribution
+    using the Boost Math C++ library [1]_.
+
+    Note that argument order of `ncfdtri` is different from that of the
+    similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter
+    of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtri
+
+    Compute the CDF for several values of `f`:
+
+    >>> f = [0.5, 1, 1.5]
+    >>> p = ncfdtr(2, 3, 1.5, f)
+    >>> p
+    array([ 0.20782291,  0.36107392,  0.47345752])
+
+    Compute the inverse.  We recover the values of `f`, as expected:
+
+    >>> ncfdtri(2, 3, 1.5, p)
+    array([ 0.5,  1. ,  1.5])
+
+    """)
+
+add_newdoc("ncfdtridfd",
+    """
+    ncfdtridfd(dfn, p, nc, f, out=None)
+
+    Calculate degrees of freedom (denominator) for the noncentral F-distribution.
+
+    This is the inverse with respect to `dfd` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    p : array_like
+        Value of the cumulative distribution function.  Must be in the
+        range [0, 1].
+    nc : array_like
+        Noncentrality parameter.  Should be in range (0, 1e4).
+    f : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    dfd : scalar or ndarray
+        Degrees of freedom of the denominator sum of squares.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+
+    Notes
+    -----
+    The value of the cumulative noncentral F distribution is not necessarily
+    monotone in either degrees of freedom. There thus may be two values that
+    provide a given CDF value. This routine assumes monotonicity and will
+    find an arbitrary one of the two values.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtridfd
+
+    Compute the CDF for several values of `dfd`:
+
+    >>> dfd = [1, 2, 3]
+    >>> p = ncfdtr(2, dfd, 0.25, 15)
+    >>> p
+    array([ 0.8097138 ,  0.93020416,  0.96787852])
+
+    Compute the inverse.  We recover the values of `dfd`, as expected:
+
+    >>> ncfdtridfd(2, p, 0.25, 15)
+    array([ 1.,  2.,  3.])
+
+    """)
+
+add_newdoc("ncfdtridfn",
+    """
+    ncfdtridfn(p, dfd, nc, f, out=None)
+
+    Calculate degrees of freedom (numerator) for the noncentral F-distribution.
+
+    This is the inverse with respect to `dfn` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    p : array_like
+        Value of the cumulative distribution function. Must be in the
+        range [0, 1].
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares. Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Should be in range (0, 1e4).
+    f : float
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    dfn : scalar or ndarray
+        Degrees of freedom of the numerator sum of squares.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+
+    Notes
+    -----
+    The value of the cumulative noncentral F distribution is not necessarily
+    monotone in either degrees of freedom. There thus may be two values that
+    provide a given CDF value. This routine assumes monotonicity and will
+    find an arbitrary one of the two values.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtridfn
+
+    Compute the CDF for several values of `dfn`:
+
+    >>> dfn = [1, 2, 3]
+    >>> p = ncfdtr(dfn, 2, 0.25, 15)
+    >>> p
+    array([ 0.92562363,  0.93020416,  0.93188394])
+
+    Compute the inverse. We recover the values of `dfn`, as expected:
+
+    >>> ncfdtridfn(p, 2, 0.25, 15)
+    array([ 1.,  2.,  3.])
+
+    """)
+
+add_newdoc("ncfdtrinc",
+    """
+    ncfdtrinc(dfn, dfd, p, f, out=None)
+
+    Calculate non-centrality parameter for non-central F distribution.
+
+    This is the inverse with respect to `nc` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares. Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares. Range (0, inf).
+    p : array_like
+        Value of the cumulative distribution function. Must be in the
+        range [0, 1].
+    f : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Noncentrality parameter.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtrinc
+
+    Compute the CDF for several values of `nc`:
+
+    >>> nc = [0.5, 1.5, 2.0]
+    >>> p = ncfdtr(2, 3, nc, 15)
+    >>> p
+    array([ 0.96309246,  0.94327955,  0.93304098])
+
+    Compute the inverse. We recover the values of `nc`, as expected:
+
+    >>> ncfdtrinc(2, 3, p, 15)
+    array([ 0.5,  1.5,  2. ])
+
+    """)
+
+add_newdoc("nctdtr",
+    """
+    nctdtr(df, nc, t, out=None)
+
+    Cumulative distribution function of the non-central `t` distribution.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    nc : array_like
+        Noncentrality parameter.
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        The calculated CDF. If all inputs are scalar, the return will be a
+        float. Otherwise, it will be an array.
+
+    See Also
+    --------
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Notes
+    -----
+    This function calculates the CDF of the non-central t distribution using
+    the Boost Math C++ library [1]_.
+
+    Note that the argument order of `nctdtr` is different from that of the
+    similar ``cdf`` method of `scipy.stats.nct`: `t` is the last
+    parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Plot the CDF of the non-central t distribution, for nc=0. Compare with the
+    t-distribution from scipy.stats:
+
+    >>> x = np.linspace(-5, 5, num=500)
+    >>> df = 3
+    >>> nct_stats = stats.t.cdf(x, df)
+    >>> nct_special = special.nctdtr(df, 0, x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, nct_stats, 'b-', lw=3)
+    >>> ax.plot(x, nct_special, 'r-')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("nctdtridf",
+    """
+    nctdtridf(p, nc, t, out=None)
+
+    Calculate degrees of freedom for non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    p : array_like
+        CDF values, in range (0, 1].
+    nc : array_like
+        Noncentrality parameter. Should be in range (-1e6, 1e6).
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        The degrees of freedom. If all inputs are scalar, the return will be a
+        float. Otherwise, it will be an array.
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtridf
+
+    Compute the CDF for several values of `df`:
+
+    >>> df = [1, 2, 3]
+    >>> p = nctdtr(df, 0.25, 1)
+    >>> p
+    array([0.67491974, 0.716464  , 0.73349456])
+
+    Compute the inverse. We recover the values of `df`, as expected:
+
+    >>> nctdtridf(p, 0.25, 1)
+    array([1., 2., 3.])
+
+    """)
+
+add_newdoc("nctdtrinc",
+    """
+    nctdtrinc(df, p, t, out=None)
+
+    Calculate non-centrality parameter for non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    p : array_like
+        CDF values, in range (0, 1].
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Noncentrality parameter
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtrinc
+
+    Compute the CDF for several values of `nc`:
+
+    >>> nc = [0.5, 1.5, 2.5]
+    >>> p = nctdtr(3, nc, 1.5)
+    >>> p
+    array([0.77569497, 0.45524533, 0.1668691 ])
+
+    Compute the inverse. We recover the values of `nc`, as expected:
+
+    >>> nctdtrinc(3, p, 1.5)
+    array([0.5, 1.5, 2.5])
+
+    """)
+
+add_newdoc("nctdtrit",
+    """
+    nctdtrit(df, nc, p, out=None)
+
+    Inverse cumulative distribution function of the non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    nc : array_like
+        Noncentrality parameter. Should be in range (-1e6, 1e6).
+    p : array_like
+        CDF values, in range (0, 1].
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t : scalar or ndarray
+        Quantiles
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtrit
+
+    Compute the CDF for several values of `t`:
+
+    >>> t = [0.5, 1, 1.5]
+    >>> p = nctdtr(3, 1, t)
+    >>> p
+    array([0.29811049, 0.46922687, 0.6257559 ])
+
+    Compute the inverse. We recover the values of `t`, as expected:
+
+    >>> nctdtrit(3, 1, p)
+    array([0.5, 1. , 1.5])
+
+    """)
+
+add_newdoc("ndtr",
+    r"""
+    ndtr(x, out=None)
+
+    Cumulative distribution of the standard normal distribution.
+
+    Returns the area under the standard Gaussian probability
+    density function, integrated from minus infinity to `x`
+
+    .. math::
+
+       \frac{1}{\sqrt{2\pi}} \int_{-\infty}^x \exp(-t^2/2) dt
+
+    Parameters
+    ----------
+    x : array_like, real or complex
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the normal CDF evaluated at `x`
+
+    See Also
+    --------
+    log_ndtr : Logarithm of ndtr
+    ndtri : Inverse of ndtr, standard normal percentile function
+    erf : Error function
+    erfc : 1 - erf
+    scipy.stats.norm : Normal distribution
+
+    Examples
+    --------
+    Evaluate `ndtr` at one point.
+
+    >>> import numpy as np
+    >>> from scipy.special import ndtr
+    >>> ndtr(0.5)
+    0.6914624612740131
+
+    Evaluate the function at several points by providing a NumPy array
+    or list for `x`.
+
+    >>> ndtr([0, 0.5, 2])
+    array([0.5       , 0.69146246, 0.97724987])
+
+    Plot the function.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-5, 5, 100)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ndtr(x))
+    >>> ax.set_title(r"Standard normal cumulative distribution function $\Phi$")
+    >>> plt.show()
+    """)
+
+
+add_newdoc("nrdtrimn",
+    """
+    nrdtrimn(p, std, x, out=None)
+
+    Calculate mean of normal distribution given other params.
+
+    Parameters
+    ----------
+    p : array_like
+        CDF values, in range (0, 1].
+    std : array_like
+        Standard deviation.
+    x : array_like
+        Quantiles, i.e. the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    mn : scalar or ndarray
+        The mean of the normal distribution.
+
+    See Also
+    --------
+    scipy.stats.norm : Normal distribution
+    ndtr : Standard normal cumulative probability distribution
+    ndtri : Inverse of standard normal CDF with respect to quantile
+    nrdtrisd : Inverse of normal distribution CDF with respect to
+               standard deviation
+
+    Examples
+    --------
+    `nrdtrimn` can be used to recover the mean of a normal distribution
+    if we know the CDF value `p` for a given quantile `x` and the
+    standard deviation `std`. First, we calculate
+    the normal distribution CDF for an exemplary parameter set.
+
+    >>> from scipy.stats import norm
+    >>> mean = 3.
+    >>> std = 2.
+    >>> x = 6.
+    >>> p = norm.cdf(x, loc=mean, scale=std)
+    >>> p
+    0.9331927987311419
+
+    Verify that `nrdtrimn` returns the original value for `mean`.
+
+    >>> from scipy.special import nrdtrimn
+    >>> nrdtrimn(p, std, x)
+    3.0000000000000004
+
+    """)
+
+add_newdoc("nrdtrisd",
+    """
+    nrdtrisd(mn, p, x, out=None)
+
+    Calculate standard deviation of normal distribution given other params.
+
+    Parameters
+    ----------
+    mn : scalar or ndarray
+        The mean of the normal distribution.
+    p : array_like
+        CDF values, in range (0, 1].
+    x : array_like
+        Quantiles, i.e. the upper limit of integration.
+
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    std : scalar or ndarray
+        Standard deviation.
+
+    See Also
+    --------
+    scipy.stats.norm : Normal distribution
+    ndtr : Standard normal cumulative probability distribution
+    ndtri : Inverse of standard normal CDF with respect to quantile
+    nrdtrimn : Inverse of normal distribution CDF with respect to
+               mean
+
+    Examples
+    --------
+    `nrdtrisd` can be used to recover the standard deviation of a normal
+    distribution if we know the CDF value `p` for a given quantile `x` and
+    the mean `mn`. First, we calculate the normal distribution CDF for an
+    exemplary parameter set.
+
+    >>> from scipy.stats import norm
+    >>> mean = 3.
+    >>> std = 2.
+    >>> x = 6.
+    >>> p = norm.cdf(x, loc=mean, scale=std)
+    >>> p
+    0.9331927987311419
+
+    Verify that `nrdtrisd` returns the original value for `std`.
+
+    >>> from scipy.special import nrdtrisd
+    >>> nrdtrisd(mean, p, x)
+    2.0000000000000004
+
+    """)
+
+add_newdoc("log_ndtr",
+    """
+    log_ndtr(x, out=None)
+
+    Logarithm of Gaussian cumulative distribution function.
+
+    Returns the log of the area under the standard Gaussian probability
+    density function, integrated from minus infinity to `x`::
+
+        log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))
+
+    Parameters
+    ----------
+    x : array_like, real or complex
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the log of the normal CDF evaluated at `x`
+
+    See Also
+    --------
+    erf
+    erfc
+    scipy.stats.norm
+    ndtr
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import log_ndtr, ndtr
+
+    The benefit of ``log_ndtr(x)`` over the naive implementation
+    ``np.log(ndtr(x))`` is most evident with moderate to large positive
+    values of ``x``:
+
+    >>> x = np.array([6, 7, 9, 12, 15, 25])
+    >>> log_ndtr(x)
+    array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,
+           -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])
+
+    The results of the naive calculation for the moderate ``x`` values
+    have only 5 or 6 correct significant digits. For values of ``x``
+    greater than approximately 8.3, the naive expression returns 0:
+
+    >>> np.log(ndtr(x))
+    array([-9.86587701e-10, -1.27986510e-12,  0.00000000e+00,
+            0.00000000e+00,  0.00000000e+00,  0.00000000e+00])
+    """)
+
+add_newdoc("ndtri",
+    """
+    ndtri(y, out=None)
+
+    Inverse of `ndtr` vs x
+
+    Returns the argument x for which the area under the standard normal
+    probability density function (integrated from minus infinity to `x`)
+    is equal to y.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value of x such that ``ndtr(x) == p``.
+
+    See Also
+    --------
+    ndtr : Standard normal cumulative probability distribution
+    ndtri_exp : Inverse of log_ndtr
+
+    Examples
+    --------
+    `ndtri` is the percentile function of the standard normal distribution.
+    This means it returns the inverse of the cumulative density `ndtr`. First,
+    let us compute a cumulative density value.
+
+    >>> import numpy as np
+    >>> from scipy.special import ndtri, ndtr
+    >>> cdf_val = ndtr(2)
+    >>> cdf_val
+    0.9772498680518208
+
+    Verify that `ndtri` yields the original value for `x` up to floating point
+    errors.
+
+    >>> ndtri(cdf_val)
+    2.0000000000000004
+
+    Plot the function. For that purpose, we provide a NumPy array as argument.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0.01, 1, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ndtri(x))
+    >>> ax.set_title("Standard normal percentile function")
+    >>> plt.show()
+    """)
+
+add_newdoc("pdtr",
+    r"""
+    pdtr(k, m, out=None)
+
+    Poisson cumulative distribution function.
+
+    Defined as the probability that a Poisson-distributed random
+    variable with event rate :math:`m` is less than or equal to
+    :math:`k`. More concretely, this works out to be [1]_
+
+    .. math::
+
+       \exp(-m) \sum_{j = 0}^{\lfloor{k}\rfloor} \frac{m^j}{j!}.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Poisson cumulative distribution function
+
+    See Also
+    --------
+    pdtrc : Poisson survival function
+    pdtrik : inverse of `pdtr` with respect to `k`
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Poisson_distribution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is a cumulative distribution function, so it converges to 1
+    monotonically as `k` goes to infinity.
+
+    >>> sc.pdtr([1, 10, 100, np.inf], 1)
+    array([0.73575888, 0.99999999, 1.        , 1.        ])
+
+    It is discontinuous at integers and constant between integers.
+
+    >>> sc.pdtr([1, 1.5, 1.9, 2], 1)
+    array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])
+
+    """)
+
+add_newdoc("pdtrc",
+    """
+    pdtrc(k, m, out=None)
+
+    Poisson survival function
+
+    Returns the sum of the terms from k+1 to infinity of the Poisson
+    distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(
+    k+1, m). Arguments must both be non-negative doubles.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Poisson survival function
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrik : inverse of `pdtr` with respect to `k`
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is a survival function, so it decreases to 0
+    monotonically as `k` goes to infinity.
+
+    >>> k = np.array([1, 10, 100, np.inf])
+    >>> sc.pdtrc(k, 1)
+    array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])
+
+    It can be expressed in terms of the lower incomplete gamma
+    function `gammainc`.
+
+    >>> sc.gammainc(k + 1, 1)
+    array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])
+
+    """)
+
+add_newdoc("pdtri",
+    """
+    pdtri(k, y, out=None)
+
+    Inverse to `pdtr` vs m
+
+    Returns the Poisson variable `m` such that the sum from 0 to `k` of
+    the Poisson density is equal to the given probability `y`:
+    calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative
+    integer and `y` between 0 and 1.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    y : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the shape parameter `m` such that ``pdtr(k, m) = p``
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrc : Poisson survival function
+    pdtrik : inverse of `pdtr` with respect to `k`
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    Compute the CDF for several values of `m`:
+
+    >>> m = [0.5, 1, 1.5]
+    >>> p = sc.pdtr(1, m)
+    >>> p
+    array([0.90979599, 0.73575888, 0.5578254 ])
+
+    Compute the inverse. We recover the values of `m`, as expected:
+
+    >>> sc.pdtri(1, p)
+    array([0.5, 1. , 1.5])
+
+    """)
+
+add_newdoc("pdtrik",
+    """
+    pdtrik(p, m, out=None)
+
+    Inverse to `pdtr` vs `k`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The number of occurrences `k` such that ``pdtr(k, m) = p``
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrc : Poisson survival function
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    Compute the CDF for several values of `k`:
+
+    >>> k = [1, 2, 3]
+    >>> p = sc.pdtr(k, 2)
+    >>> p
+    array([0.40600585, 0.67667642, 0.85712346])
+
+    Compute the inverse. We recover the values of `k`, as expected:
+
+    >>> sc.pdtrik(p, 2)
+    array([1., 2., 3.])
+
+    """)
+
+add_newdoc("poch",
+    r"""
+    poch(z, m, out=None)
+
+    Pochhammer symbol.
+
+    The Pochhammer symbol (rising factorial) is defined as
+
+    .. math::
+
+        (z)_m = \frac{\Gamma(z + m)}{\Gamma(z)}
+
+    For positive integer `m` it reads
+
+    .. math::
+
+        (z)_m = z (z + 1) ... (z + m - 1)
+
+    See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    z, m : array_like
+        Real-valued arguments.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the function.
+
+    References
+    ----------
+    .. [dlmf] Nist, Digital Library of Mathematical Functions
+        https://dlmf.nist.gov/5.2#iii
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It is 1 when m is 0.
+
+    >>> sc.poch([1, 2, 3, 4], 0)
+    array([1., 1., 1., 1.])
+
+    For z equal to 1 it reduces to the factorial function.
+
+    >>> sc.poch(1, 5)
+    120.0
+    >>> 1 * 2 * 3 * 4 * 5
+    120
+
+    It can be expressed in terms of the gamma function.
+
+    >>> z, m = 3.7, 2.1
+    >>> sc.poch(z, m)
+    20.529581933776953
+    >>> sc.gamma(z + m) / sc.gamma(z)
+    20.52958193377696
+
+    """)
+
+add_newdoc("powm1", """
+    powm1(x, y, out=None)
+
+    Computes ``x**y - 1``.
+
+    This function is useful when `y` is near 0, or when `x` is near 1.
+
+    The function is implemented for real types only (unlike ``numpy.power``,
+    which accepts complex inputs).
+
+    Parameters
+    ----------
+    x : array_like
+        The base. Must be a real type (i.e. integer or float, not complex).
+    y : array_like
+        The exponent. Must be a real type (i.e. integer or float, not complex).
+
+    Returns
+    -------
+    array_like
+        Result of the calculation
+
+    Notes
+    -----
+    .. versionadded:: 1.10.0
+
+    The underlying code is implemented for single precision and double
+    precision floats only.  Unlike `numpy.power`, integer inputs to
+    `powm1` are converted to floating point, and complex inputs are
+    not accepted.
+
+    Note the following edge cases:
+
+    * ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``
+      and ``nan``.
+    * ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``
+      and ``inf``.
+
+    This function wraps the ``powm1`` routine from the
+    Boost Math C++ library [1]_.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import powm1
+
+    >>> x = np.array([1.2, 10.0, 0.9999999975])
+    >>> y = np.array([1e-9, 1e-11, 0.1875])
+    >>> powm1(x, y)
+    array([ 1.82321557e-10,  2.30258509e-11, -4.68749998e-10])
+
+    It can be verified that the relative errors in those results
+    are less than 2.5e-16.
+
+    Compare that to the result of ``x**y - 1``, where the
+    relative errors are all larger than 8e-8:
+
+    >>> x**y - 1
+    array([ 1.82321491e-10,  2.30258035e-11, -4.68750039e-10])
+
+    """)
+
+
+add_newdoc("pseudo_huber",
+    r"""
+    pseudo_huber(delta, r, out=None)
+
+    Pseudo-Huber loss function.
+
+    .. math:: \mathrm{pseudo\_huber}(\delta, r) =
+              \delta^2 \left( \sqrt{ 1 + \left( \frac{r}{\delta} \right)^2 } - 1 \right)
+
+    Parameters
+    ----------
+    delta : array_like
+        Input array, indicating the soft quadratic vs. linear loss changepoint.
+    r : array_like
+        Input array, possibly representing residuals.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The computed Pseudo-Huber loss function values.
+
+    See Also
+    --------
+    huber: Similar function which this function approximates
+
+    Notes
+    -----
+    Like `huber`, `pseudo_huber` often serves as a robust loss function
+    in statistics or machine learning to reduce the influence of outliers.
+    Unlike `huber`, `pseudo_huber` is smooth.
+
+    Typically, `r` represents residuals, the difference
+    between a model prediction and data. Then, for :math:`|r|\leq\delta`,
+    `pseudo_huber` resembles the squared error and for :math:`|r|>\delta` the
+    absolute error. This way, the Pseudo-Huber loss often achieves
+    a fast convergence in model fitting for small residuals like the squared
+    error loss function and still reduces the influence of outliers
+    (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is
+    the cutoff between squared and absolute error regimes, it has
+    to be tuned carefully for each problem. `pseudo_huber` is also
+    convex, making it suitable for gradient based optimization. [1]_ [2]_
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Hartley, Zisserman, "Multiple View Geometry in Computer Vision".
+           2003. Cambridge University Press. p. 619
+    .. [2] Charbonnier et al. "Deterministic edge-preserving regularization
+           in computed imaging". 1997. IEEE Trans. Image Processing.
+           6 (2): 298 - 311.
+
+    Examples
+    --------
+    Import all necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.special import pseudo_huber, huber
+    >>> import matplotlib.pyplot as plt
+
+    Calculate the function for ``delta=1`` at ``r=2``.
+
+    >>> pseudo_huber(1., 2.)
+    1.2360679774997898
+
+    Calculate the function at ``r=2`` for different `delta` by providing
+    a list or NumPy array for `delta`.
+
+    >>> pseudo_huber([1., 2., 4.], 3.)
+    array([2.16227766, 3.21110255, 4.        ])
+
+    Calculate the function for ``delta=1`` at several points by providing
+    a list or NumPy array for `r`.
+
+    >>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))
+    array([0.47213595, 1.        , 3.21110255, 4.94427191])
+
+    The function can be calculated for different `delta` and `r` by
+    providing arrays for both with compatible shapes for broadcasting.
+
+    >>> r = np.array([1., 2.5, 8., 10.])
+    >>> deltas = np.array([[1.], [5.], [9.]])
+    >>> print(r.shape, deltas.shape)
+    (4,) (3, 1)
+
+    >>> pseudo_huber(deltas, r)
+    array([[ 0.41421356,  1.6925824 ,  7.06225775,  9.04987562],
+           [ 0.49509757,  2.95084972, 22.16990566, 30.90169944],
+           [ 0.49846624,  3.06693762, 27.37435121, 40.08261642]])
+
+    Plot the function for different `delta`.
+
+    >>> x = np.linspace(-4, 4, 500)
+    >>> deltas = [1, 2, 3]
+    >>> linestyles = ["dashed", "dotted", "dashdot"]
+    >>> fig, ax = plt.subplots()
+    >>> combined_plot_parameters = list(zip(deltas, linestyles))
+    >>> for delta, style in combined_plot_parameters:
+    ...     ax.plot(x, pseudo_huber(delta, x), label=rf"$\delta={delta}$",
+    ...             ls=style)
+    >>> ax.legend(loc="upper center")
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title(r"Pseudo-Huber loss function $h_{\delta}(x)$")
+    >>> ax.set_xlim(-4, 4)
+    >>> ax.set_ylim(0, 8)
+    >>> plt.show()
+
+    Finally, illustrate the difference between `huber` and `pseudo_huber` by
+    plotting them and their gradients with respect to `r`. The plot shows
+    that `pseudo_huber` is continuously differentiable while `huber` is not
+    at the points :math:`\pm\delta`.
+
+    >>> def huber_grad(delta, x):
+    ...     grad = np.copy(x)
+    ...     linear_area = np.argwhere(np.abs(x) > delta)
+    ...     grad[linear_area]=delta*np.sign(x[linear_area])
+    ...     return grad
+    >>> def pseudo_huber_grad(delta, x):
+    ...     return x* (1+(x/delta)**2)**(-0.5)
+    >>> x=np.linspace(-3, 3, 500)
+    >>> delta = 1.
+    >>> fig, ax = plt.subplots(figsize=(7, 7))
+    >>> ax.plot(x, huber(delta, x), label="Huber", ls="dashed")
+    >>> ax.plot(x, huber_grad(delta, x), label="Huber Gradient", ls="dashdot")
+    >>> ax.plot(x, pseudo_huber(delta, x), label="Pseudo-Huber", ls="dotted")
+    >>> ax.plot(x, pseudo_huber_grad(delta, x), label="Pseudo-Huber Gradient",
+    ...         ls="solid")
+    >>> ax.legend(loc="upper center")
+    >>> plt.show()
+    """)
+
+add_newdoc("rel_entr",
+    r"""
+    rel_entr(x, y, out=None)
+
+    Elementwise function for computing relative entropy.
+
+    .. math::
+
+        \mathrm{rel\_entr}(x, y) =
+            \begin{cases}
+                x \log(x / y) & x > 0, y > 0 \\
+                0 & x = 0, y \ge 0 \\
+                \infty & \text{otherwise}
+            \end{cases}
+
+    Parameters
+    ----------
+    x, y : array_like
+        Input arrays
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Relative entropy of the inputs
+
+    See Also
+    --------
+    entr, kl_div, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is jointly convex in x and y.
+
+    The origin of this function is in convex programming; see
+    [1]_. Given two discrete probability distributions :math:`p_1,
+    \ldots, p_n` and :math:`q_1, \ldots, q_n`, the definition of relative
+    entropy in the context of *information theory* is
+
+    .. math::
+
+        \sum_{i = 1}^n \mathrm{rel\_entr}(p_i, q_i).
+
+    To compute the latter quantity, use `scipy.stats.entropy`.
+
+    See [2]_ for details.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+    .. [2] Kullback-Leibler divergence,
+           https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence
+
+    """)
+
+add_newdoc("round",
+    """
+    round(x, out=None)
+
+    Round to the nearest integer.
+
+    Returns the nearest integer to `x`.  If `x` ends in 0.5 exactly,
+    the nearest even integer is chosen.
+
+    Parameters
+    ----------
+    x : array_like
+        Real valued input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        The nearest integers to the elements of `x`. The result is of
+        floating type, not integer type.
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It rounds to even.
+
+    >>> sc.round([0.5, 1.5])
+    array([0., 2.])
+
+    """)
+
+add_newdoc("shichi",
+    r"""
+    shichi(x, out=None)
+
+    Hyperbolic sine and cosine integrals.
+
+    The hyperbolic sine integral is
+
+    .. math::
+
+      \int_0^x \frac{\sinh{t}}{t}dt
+
+    and the hyperbolic cosine integral is
+
+    .. math::
+
+      \gamma + \log(x) + \int_0^x \frac{\cosh{t} - 1}{t} dt
+
+    where :math:`\gamma` is Euler's constant and :math:`\log` is the
+    principal branch of the logarithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex points at which to compute the hyperbolic sine
+        and cosine integrals.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function results
+
+    Returns
+    -------
+    si : scalar or ndarray
+        Hyperbolic sine integral at ``x``
+    ci : scalar or ndarray
+        Hyperbolic cosine integral at ``x``
+
+    See Also
+    --------
+    sici : Sine and cosine integrals.
+    exp1 : Exponential integral E1.
+    expi : Exponential integral Ei.
+
+    Notes
+    -----
+    For real arguments with ``x < 0``, ``chi`` is the real part of the
+    hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x
+    + 0j)`` differ by a factor of ``1j*pi``.
+
+    For real arguments the function is computed by calling Cephes'
+    [2]_ *shichi* routine. For complex arguments the algorithm is based
+    on Mpmath's [3]_ *shi* and *chi* routines.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+           (See Section 5.2.)
+    .. [2] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [3] Fredrik Johansson and others.
+           "mpmath: a Python library for arbitrary-precision floating-point
+           arithmetic" (Version 0.19) http://mpmath.org/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import shichi, sici
+
+    `shichi` accepts real or complex input:
+
+    >>> shichi(0.5)
+    (0.5069967498196671, -0.05277684495649357)
+    >>> shichi(0.5 + 2.5j)
+    ((0.11772029666668238+1.831091777729851j),
+     (0.29912435887648825+1.7395351121166562j))
+
+    The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are
+    related to the sine and cosine integrals Si(z) and Ci(z) by
+
+    * Shi(z) = -i*Si(i*z)
+    * Chi(z) = Ci(-i*z) + i*pi/2
+
+    >>> z = 0.25 + 5j
+    >>> shi, chi = shichi(z)
+    >>> shi, -1j*sici(1j*z)[0]            # Should be the same.
+    ((-0.04834719325101729+1.5469354086921228j),
+     (-0.04834719325101729+1.5469354086921228j))
+    >>> chi, sici(-1j*z)[1] + 1j*np.pi/2  # Should be the same.
+    ((-0.19568708973868087+1.556276312103824j),
+     (-0.19568708973868087+1.556276312103824j))
+
+    Plot the functions evaluated on the real axis:
+
+    >>> xp = np.geomspace(1e-8, 4.0, 250)
+    >>> x = np.concatenate((-xp[::-1], xp))
+    >>> shi, chi = shichi(x)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, shi, label='Shi(x)')
+    >>> ax.plot(x, chi, '--', label='Chi(x)')
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('Hyperbolic Sine and Cosine Integrals')
+    >>> ax.legend(shadow=True, framealpha=1, loc='lower right')
+    >>> ax.grid(True)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("sici",
+    r"""
+    sici(x, out=None)
+
+    Sine and cosine integrals.
+
+    The sine integral is
+
+    .. math::
+
+      \int_0^x \frac{\sin{t}}{t}dt
+
+    and the cosine integral is
+
+    .. math::
+
+      \gamma + \log(x) + \int_0^x \frac{\cos{t} - 1}{t}dt
+
+    where :math:`\gamma` is Euler's constant and :math:`\log` is the
+    principal branch of the logarithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex points at which to compute the sine and cosine
+        integrals.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function results
+
+    Returns
+    -------
+    si : scalar or ndarray
+        Sine integral at ``x``
+    ci : scalar or ndarray
+        Cosine integral at ``x``
+
+    See Also
+    --------
+    shichi : Hyperbolic sine and cosine integrals.
+    exp1 : Exponential integral E1.
+    expi : Exponential integral Ei.
+
+    Notes
+    -----
+    For real arguments with ``x < 0``, ``ci`` is the real part of the
+    cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``
+    differ by a factor of ``1j*pi``.
+
+    For real arguments the function is computed by calling Cephes'
+    [2]_ *sici* routine. For complex arguments the algorithm is based
+    on Mpmath's [3]_ *si* and *ci* routines.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+           (See Section 5.2.)
+    .. [2] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [3] Fredrik Johansson and others.
+           "mpmath: a Python library for arbitrary-precision floating-point
+           arithmetic" (Version 0.19) http://mpmath.org/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import sici, exp1
+
+    `sici` accepts real or complex input:
+
+    >>> sici(2.5)
+    (1.7785201734438267, 0.2858711963653835)
+    >>> sici(2.5 + 3j)
+    ((4.505735874563953+0.06863305018999577j),
+    (0.0793644206906966-2.935510262937543j))
+
+    For z in the right half plane, the sine and cosine integrals are
+    related to the exponential integral E1 (implemented in SciPy as
+    `scipy.special.exp1`) by
+
+    * Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2
+    * Ci(z) = -(E1(i*z) + E1(-i*z))/2
+
+    See [1]_ (equations 5.2.21 and 5.2.23).
+
+    We can verify these relations:
+
+    >>> z = 2 - 3j
+    >>> sici(z)
+    ((4.54751388956229-1.3991965806460565j),
+    (1.408292501520851+2.9836177420296055j))
+
+    >>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2  # Same as sine integral
+    (4.54751388956229-1.3991965806460565j)
+
+    >>> -(exp1(1j*z) + exp1(-1j*z))/2            # Same as cosine integral
+    (1.408292501520851+2.9836177420296055j)
+
+    Plot the functions evaluated on the real axis; the dotted horizontal
+    lines are at pi/2 and -pi/2:
+
+    >>> x = np.linspace(-16, 16, 150)
+    >>> si, ci = sici(x)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, si, label='Si(x)')
+    >>> ax.plot(x, ci, '--', label='Ci(x)')
+    >>> ax.legend(shadow=True, framealpha=1, loc='upper left')
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('Sine and Cosine Integrals')
+    >>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')
+    >>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')
+    >>> ax.grid(True)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("smirnov",
+    r"""
+    smirnov(n, d, out=None)
+
+    Kolmogorov-Smirnov complementary cumulative distribution function
+
+    Returns the exact Kolmogorov-Smirnov complementary cumulative
+    distribution function,(aka the Survival Function) of Dn+ (or Dn-)
+    for a one-sided test of equality between an empirical and a
+    theoretical distribution. It is equal to the probability that the
+    maximum difference between a theoretical distribution and an empirical
+    one based on `n` samples is greater than d.
+
+    Parameters
+    ----------
+    n : int
+      Number of samples
+    d : float array_like
+      Deviation between the Empirical CDF (ECDF) and the target CDF.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))
+
+    See Also
+    --------
+    smirnovi : The Inverse Survival Function for the distribution
+    scipy.stats.ksone : Provides the functionality as a continuous distribution
+    kolmogorov, kolmogi : Functions for the two-sided distribution
+
+    Notes
+    -----
+    `smirnov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.ksone` distribution.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import smirnov
+    >>> from scipy.stats import norm
+
+    Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a
+    sample of size 5.
+
+    >>> smirnov(5, [0, 0.5, 1.0])
+    array([ 1.   ,  0.056,  0.   ])
+
+    Compare a sample of size 5 against N(0, 1), the standard normal
+    distribution with mean 0 and standard deviation 1.
+
+    `x` is the sample.
+
+    >>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])
+
+    >>> target = norm(0, 1)
+    >>> cdfs = target.cdf(x)
+    >>> cdfs
+    array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])
+
+    Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).
+
+    >>> n = len(x)
+    >>> ecdfs = np.arange(n+1, dtype=float)/n
+    >>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],
+    ...                        ecdfs[1:] - cdfs])
+    >>> with np.printoptions(precision=3):
+    ...    print(cols)
+    [[-1.392  0.2    0.082  0.082  0.118]
+     [-0.135  0.4    0.446  0.246 -0.046]
+     [ 0.114  0.6    0.545  0.145  0.055]
+     [ 0.19   0.8    0.575 -0.025  0.225]
+     [ 1.82   1.     0.966  0.166  0.034]]
+    >>> gaps = cols[:, -2:]
+    >>> Dnpm = np.max(gaps, axis=0)
+    >>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')
+    Dn-=0.246306, Dn+=0.224655
+    >>> probs = smirnov(n, Dnpm)
+    >>> print(f'For a sample of size {n} drawn from N(0, 1):',
+    ...       f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',
+    ...       f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',
+    ...       sep='\n')
+    For a sample of size 5 drawn from N(0, 1):
+     Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711
+     Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245
+
+    Plot the empirical CDF and the standard normal CDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.step(np.concatenate(([-2.5], x, [2.5])),
+    ...          np.concatenate((ecdfs, [1])),
+    ...          where='post', label='Empirical CDF')
+    >>> xx = np.linspace(-2.5, 2.5, 100)
+    >>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')
+
+    Add vertical lines marking Dn+ and Dn-.
+
+    >>> iminus, iplus = np.argmax(gaps, axis=0)
+    >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',
+    ...            alpha=0.5, lw=4)
+    >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',
+    ...            alpha=0.5, lw=4)
+
+    >>> plt.grid(True)
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.show()
+    """)
+
+add_newdoc("smirnovi",
+    """
+    smirnovi(n, p, out=None)
+
+    Inverse to `smirnov`
+
+    Returns `d` such that ``smirnov(n, d) == p``, the critical value
+    corresponding to `p`.
+
+    Parameters
+    ----------
+    n : int
+      Number of samples
+    p : float array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of smirnovi(n, p), the critical values.
+
+    See Also
+    --------
+    smirnov : The Survival Function (SF) for the distribution
+    scipy.stats.ksone : Provides the functionality as a continuous distribution
+    kolmogorov, kolmogi : Functions for the two-sided distribution
+    scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n
+
+    Notes
+    -----
+    `smirnov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.ksone` distribution.
+
+    Examples
+    --------
+    >>> from scipy.special import smirnovi, smirnov
+
+    >>> n = 24
+    >>> deviations = [0.1, 0.2, 0.3]
+
+    Use `smirnov` to compute the complementary CDF of the Smirnov
+    distribution for the given number of samples and deviations.
+
+    >>> p = smirnov(n, deviations)
+    >>> p
+    array([0.58105083, 0.12826832, 0.01032231])
+
+    The inverse function ``smirnovi(n, p)`` returns ``deviations``.
+
+    >>> smirnovi(n, p)
+    array([0.1, 0.2, 0.3])
+
+    """)
+
+add_newdoc("_smirnovc",
+    """
+    _smirnovc(n, d)
+     Internal function, do not use.
+    """)
+
+add_newdoc("_smirnovci",
+    """
+     Internal function, do not use.
+    """)
+
+add_newdoc("_smirnovp",
+    """
+    _smirnovp(n, p)
+     Internal function, do not use.
+    """)
+
+add_newdoc("spence",
+    r"""
+    spence(z, out=None)
+
+    Spence's function, also known as the dilogarithm.
+
+    It is defined to be
+
+    .. math::
+      \int_1^z \frac{\log(t)}{1 - t}dt
+
+    for complex :math:`z`, where the contour of integration is taken
+    to avoid the branch cut of the logarithm. Spence's function is
+    analytic everywhere except the negative real axis where it has a
+    branch cut.
+
+    Parameters
+    ----------
+    z : array_like
+        Points at which to evaluate Spence's function
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    s : scalar or ndarray
+        Computed values of Spence's function
+
+    Notes
+    -----
+    There is a different convention which defines Spence's function by
+    the integral
+
+    .. math::
+      -\int_0^z \frac{\log(1 - t)}{t}dt;
+
+    this is our ``spence(1 - z)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import spence
+    >>> import matplotlib.pyplot as plt
+
+    The function is defined for complex inputs:
+
+    >>> spence([1-1j, 1.5+2j, 3j, -10-5j])
+    array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,
+           -0.59422064-2.49129918j, -1.14044398+6.80075924j])
+
+    For complex inputs on the branch cut, which is the negative real axis,
+    the function returns the limit for ``z`` with positive imaginary part.
+    For example, in the following, note the sign change of the imaginary
+    part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:
+
+    >>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])
+    array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,
+           2.32018041+3.45139229j])
+
+    The function returns ``nan`` for real inputs on the branch cut:
+
+    >>> spence(-1.5)
+    nan
+
+    Verify some particular values: ``spence(0) = pi**2/6``,
+    ``spence(1) = 0`` and ``spence(2) = -pi**2/12``.
+
+    >>> spence([0, 1, 2])
+    array([ 1.64493407,  0.        , -0.82246703])
+    >>> np.pi**2/6, -np.pi**2/12
+    (1.6449340668482264, -0.8224670334241132)
+
+    Verify the identity::
+
+        spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)
+
+    >>> z = 3 + 4j
+    >>> spence(z) + spence(1 - z)
+    (-2.6523186143876067+1.8853470951513935j)
+    >>> np.pi**2/6 - np.log(z)*np.log(1 - z)
+    (-2.652318614387606+1.885347095151394j)
+
+    Plot the function for positive real input.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0, 6, 400)
+    >>> ax.plot(x, spence(x))
+    >>> ax.grid()
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('spence(x)')
+    >>> plt.show()
+    """)
+
+add_newdoc(
+    "stdtr",
+    r"""
+    stdtr(df, t, out=None)
+
+    Student t distribution cumulative distribution function
+
+    Returns the integral:
+
+    .. math::
+        \frac{\Gamma((df+1)/2)}{\sqrt{\pi df} \Gamma(df/2)}
+        \int_{-\infty}^t (1+x^2/df)^{-(df+1)/2}\, dx
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom
+    t : array_like
+        Upper bound of the integral
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Student t CDF at t
+
+    See Also
+    --------
+    stdtridf : inverse of stdtr with respect to `df`
+    stdtrit : inverse of stdtr with respect to `t`
+    scipy.stats.t : student t distribution
+
+    Notes
+    -----
+    The student t distribution is also available as `scipy.stats.t`.
+    Calling `stdtr` directly can improve performance compared to the
+    ``cdf`` method of `scipy.stats.t` (see last example below).
+
+    Examples
+    --------
+    Calculate the function for ``df=3`` at ``t=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import stdtr
+    >>> import matplotlib.pyplot as plt
+    >>> stdtr(3, 1)
+    0.8044988905221148
+
+    Plot the function for three different degrees of freedom.
+
+    >>> x = np.linspace(-10, 10, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> parameters = [(1, "solid"), (3, "dashed"), (10, "dotted")]
+    >>> for (df, linestyle) in parameters:
+    ...     ax.plot(x, stdtr(df, x), ls=linestyle, label=f"$df={df}$")
+    >>> ax.legend()
+    >>> ax.set_title("Student t distribution cumulative distribution function")
+    >>> plt.show()
+
+    The function can be computed for several degrees of freedom at the same
+    time by providing a NumPy array or list for `df`:
+
+    >>> stdtr([1, 2, 3], 1)
+    array([0.75      , 0.78867513, 0.80449889])
+
+    It is possible to calculate the function at several points for several
+    different degrees of freedom simultaneously by providing arrays for `df`
+    and `t` with shapes compatible for broadcasting. Compute `stdtr` at
+    4 points for 3 degrees of freedom resulting in an array of shape 3x4.
+
+    >>> dfs = np.array([[1], [2], [3]])
+    >>> t = np.array([2, 4, 6, 8])
+    >>> dfs.shape, t.shape
+    ((3, 1), (4,))
+
+    >>> stdtr(dfs, t)
+    array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],
+           [0.90824829, 0.97140452, 0.98666426, 0.99236596],
+           [0.93033702, 0.98599577, 0.99536364, 0.99796171]])
+
+    The t distribution is also available as `scipy.stats.t`. Calling `stdtr`
+    directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.t`. To get the same results, one must use the following
+    parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.
+
+    >>> from scipy.stats import t
+    >>> df, x = 3, 1
+    >>> stdtr_result = stdtr(df, x)  # this can be faster than below
+    >>> stats_result = t(df).cdf(x)
+    >>> stats_result == stdtr_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("stdtridf",
+    """
+    stdtridf(p, t, out=None)
+
+    Inverse of `stdtr` vs df
+
+    Returns the argument df such that stdtr(df, t) is equal to `p`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    t : array_like
+        Upper bound of the integral
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        Value of `df` such that ``stdtr(df, t) == p``
+
+    See Also
+    --------
+    stdtr : Student t CDF
+    stdtrit : inverse of stdtr with respect to `t`
+    scipy.stats.t : Student t distribution
+
+    Examples
+    --------
+    Compute the student t cumulative distribution function for one
+    parameter set.
+
+    >>> from scipy.special import stdtr, stdtridf
+    >>> df, x = 5, 2
+    >>> cdf_value = stdtr(df, x)
+    >>> cdf_value
+    0.9490302605850709
+
+    Verify that `stdtridf` recovers the original value for `df` given
+    the CDF value and `x`.
+
+    >>> stdtridf(cdf_value, x)
+    5.0
+    """)
+
+add_newdoc("stdtrit",
+    """
+    stdtrit(df, p, out=None)
+
+    The `p`-th quantile of the student t distribution.
+
+    This function is the inverse of the student t distribution cumulative
+    distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.
+
+    Returns the argument `t` such that stdtr(df, t) is equal to `p`.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom
+    p : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t : scalar or ndarray
+        Value of `t` such that ``stdtr(df, t) == p``
+
+    See Also
+    --------
+    stdtr : Student t CDF
+    stdtridf : inverse of stdtr with respect to `df`
+    scipy.stats.t : Student t distribution
+
+    Notes
+    -----
+    The student t distribution is also available as `scipy.stats.t`. Calling
+    `stdtrit` directly can improve performance compared to the ``ppf``
+    method of `scipy.stats.t` (see last example below).
+
+    Examples
+    --------
+    `stdtrit` represents the inverse of the student t distribution CDF which
+    is available as `stdtr`. Here, we calculate the CDF for ``df`` at
+    ``x=1``. `stdtrit` then returns ``1`` up to floating point errors
+    given the same value for `df` and the computed CDF value.
+
+    >>> import numpy as np
+    >>> from scipy.special import stdtr, stdtrit
+    >>> import matplotlib.pyplot as plt
+    >>> df = 3
+    >>> x = 1
+    >>> cdf_value = stdtr(df, x)
+    >>> stdtrit(df, cdf_value)
+    0.9999999994418539
+
+    Plot the function for three different degrees of freedom.
+
+    >>> x = np.linspace(0, 1, 1000)
+    >>> parameters = [(1, "solid"), (2, "dashed"), (5, "dotted")]
+    >>> fig, ax = plt.subplots()
+    >>> for (df, linestyle) in parameters:
+    ...     ax.plot(x, stdtrit(df, x), ls=linestyle, label=f"$df={df}$")
+    >>> ax.legend()
+    >>> ax.set_ylim(-10, 10)
+    >>> ax.set_title("Student t distribution quantile function")
+    >>> plt.show()
+
+    The function can be computed for several degrees of freedom at the same
+    time by providing a NumPy array or list for `df`:
+
+    >>> stdtrit([1, 2, 3], 0.7)
+    array([0.72654253, 0.6172134 , 0.58438973])
+
+    It is possible to calculate the function at several points for several
+    different degrees of freedom simultaneously by providing arrays for `df`
+    and `p` with shapes compatible for broadcasting. Compute `stdtrit` at
+    4 points for 3 degrees of freedom resulting in an array of shape 3x4.
+
+    >>> dfs = np.array([[1], [2], [3]])
+    >>> p = np.array([0.2, 0.4, 0.7, 0.8])
+    >>> dfs.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> stdtrit(dfs, p)
+    array([[-1.37638192, -0.3249197 ,  0.72654253,  1.37638192],
+           [-1.06066017, -0.28867513,  0.6172134 ,  1.06066017],
+           [-0.97847231, -0.27667066,  0.58438973,  0.97847231]])
+
+    The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`
+    directly can be much faster than calling the ``ppf`` method of
+    `scipy.stats.t`. To get the same results, one must use the following
+    parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.
+
+    >>> from scipy.stats import t
+    >>> df, x = 3, 0.5
+    >>> stdtrit_result = stdtrit(df, x)  # this can be faster than below
+    >>> stats_result = t(df).ppf(x)
+    >>> stats_result == stdtrit_result  # test that results are equal
+    True
+    """)
+
+add_newdoc(
+    "tklmbda",
+    r"""
+    tklmbda(x, lmbda, out=None)
+
+    Cumulative distribution function of the Tukey lambda distribution.
+
+    Parameters
+    ----------
+    x, lmbda : array_like
+        Parameters
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        Value of the Tukey lambda CDF
+
+    See Also
+    --------
+    scipy.stats.tukeylambda : Tukey lambda distribution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import tklmbda, expit
+
+    Compute the cumulative distribution function (CDF) of the Tukey lambda
+    distribution at several ``x`` values for `lmbda` = -1.5.
+
+    >>> x = np.linspace(-2, 2, 9)
+    >>> x
+    array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])
+    >>> tklmbda(x, -1.5)
+    array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5       ,
+           0.54370263, 0.58471195, 0.6213446 , 0.65311266])
+
+    When `lmbda` is 0, the function is the logistic sigmoid function,
+    which is implemented in `scipy.special` as `expit`.
+
+    >>> tklmbda(x, 0)
+    array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,
+           0.62245933, 0.73105858, 0.81757448, 0.88079708])
+    >>> expit(x)
+    array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,
+           0.62245933, 0.73105858, 0.81757448, 0.88079708])
+
+    When `lmbda` is 1, the Tukey lambda distribution is uniform on the
+    interval [-1, 1], so the CDF increases linearly.
+
+    >>> t = np.linspace(-1, 1, 9)
+    >>> tklmbda(t, 1)
+    array([0.   , 0.125, 0.25 , 0.375, 0.5  , 0.625, 0.75 , 0.875, 1.   ])
+
+    In the following, we generate plots for several values of `lmbda`.
+
+    The first figure shows graphs for `lmbda` <= 0.
+
+    >>> styles = ['-', '-.', '--', ':']
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-12, 12, 500)
+    >>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):
+    ...     y = tklmbda(x, lmbda)
+    ...     ax.plot(x, y, styles[k], label=rf'$\lambda$ = {lmbda:-4.1f}')
+
+    >>> ax.set_title(r'tklmbda(x, $\lambda$)')
+    >>> ax.set_label('x')
+    >>> ax.legend(framealpha=1, shadow=True)
+    >>> ax.grid(True)
+
+    The second figure shows graphs for `lmbda` > 0.  The dots in the
+    graphs show the bounds of the support of the distribution.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-4.2, 4.2, 500)
+    >>> lmbdas = [0.25, 0.5, 1.0, 1.5]
+    >>> for k, lmbda in enumerate(lmbdas):
+    ...     y = tklmbda(x, lmbda)
+    ...     ax.plot(x, y, styles[k], label=fr'$\lambda$ = {lmbda}')
+
+    >>> ax.set_prop_cycle(None)
+    >>> for lmbda in lmbdas:
+    ...     ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)
+
+    >>> ax.set_title(r'tklmbda(x, $\lambda$)')
+    >>> ax.set_xlabel('x')
+    >>> ax.legend(framealpha=1, shadow=True)
+    >>> ax.grid(True)
+
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    The CDF of the Tukey lambda distribution is also implemented as the
+    ``cdf`` method of `scipy.stats.tukeylambda`.  In the following,
+    ``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the
+    same values:
+
+    >>> from scipy.stats import tukeylambda
+    >>> x = np.linspace(-2, 2, 9)
+
+    >>> tukeylambda.cdf(x, -0.5)
+    array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,
+           0.58671839, 0.66458323, 0.72906142, 0.78004843])
+
+    >>> tklmbda(x, -0.5)
+    array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,
+           0.58671839, 0.66458323, 0.72906142, 0.78004843])
+
+    The implementation in ``tukeylambda`` also provides location and scale
+    parameters, and other methods such as ``pdf()`` (the probability
+    density function) and ``ppf()`` (the inverse of the CDF), so for
+    working with the Tukey lambda distribution, ``tukeylambda`` is more
+    generally useful.  The primary advantage of ``tklmbda`` is that it is
+    significantly faster than ``tukeylambda.cdf``.
+    """)
+
+add_newdoc("wofz",
+    """
+    wofz(z, out=None)
+
+    Faddeeva function
+
+    Returns the value of the Faddeeva function for complex argument::
+
+        exp(-z**2) * erfc(-i*z)
+
+    Parameters
+    ----------
+    z : array_like
+        complex argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Faddeeva function
+
+    See Also
+    --------
+    dawsn, erf, erfc, erfcx, erfi
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-3, 3)
+    >>> z = special.wofz(x)
+
+    >>> plt.plot(x, z.real, label='wofz(x).real')
+    >>> plt.plot(x, z.imag, label='wofz(x).imag')
+    >>> plt.xlabel('$x$')
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.grid(alpha=0.25)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("xlogy",
+    """
+    xlogy(x, y, out=None)
+
+    Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Multiplier
+    y : array_like
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    z : scalar or ndarray
+        Computed x*log(y)
+
+    Notes
+    -----
+    The log function used in the computation is the natural log.
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    We can use this function to calculate the binary logistic loss also
+    known as the binary cross entropy. This loss function is used for
+    binary classification problems and is defined as:
+
+    .. math::
+        L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))
+
+    We can define the parameters `x` and `y` as y and y_pred respectively.
+    y is the array of the actual labels which over here can be either 0 or 1.
+    y_pred is the array of the predicted probabilities with respect to
+    the positive class (1).
+
+    >>> import numpy as np
+    >>> from scipy.special import xlogy
+    >>> y = np.array([0, 1, 0, 1, 1, 0])
+    >>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])
+    >>> n = len(y)
+    >>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()
+    >>> loss /= n
+    >>> loss
+    0.29597052165495025
+
+    A lower loss is usually better as it indicates that the predictions are
+    similar to the actual labels. In this example since our predicted
+    probabilities are close to the actual labels, we get an overall loss
+    that is reasonably low and appropriate.
+
+    """)
+
+add_newdoc("xlog1py",
+    """
+    xlog1py(x, y, out=None)
+
+    Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Multiplier
+    y : array_like
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    z : scalar or ndarray
+        Computed x*log1p(y)
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    This example shows how the function can be used to calculate the log of
+    the probability mass function for a geometric discrete random variable.
+    The probability mass function of the geometric distribution is defined
+    as follows:
+
+    .. math:: f(k) = (1-p)^{k-1} p
+
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure
+    and :math:`k` is the number of trials to get the first success.
+
+    >>> import numpy as np
+    >>> from scipy.special import xlog1py
+    >>> p = 0.5
+    >>> k = 100
+    >>> _pmf = np.power(1 - p, k - 1) * p
+    >>> _pmf
+    7.888609052210118e-31
+
+    If we take k as a relatively large number the value of the probability
+    mass function can become very low. In such cases taking the log of the
+    pmf would be more suitable as the log function can change the values
+    to a scale that is more appropriate to work with.
+
+    >>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)
+    >>> _log_pmf
+    -69.31471805599453
+
+    We can confirm that we get a value close to the original pmf value by
+    taking the exponential of the log pmf.
+
+    >>> _orig_pmf = np.exp(_log_pmf)
+    >>> np.isclose(_pmf, _orig_pmf)
+    True
+
+    """)
+
+add_newdoc("yn",
+    r"""
+    yn(n, x, out=None)
+
+    Bessel function of the second kind of integer order and real argument.
+
+    Parameters
+    ----------
+    n : array_like
+        Order (integer).
+    x : array_like
+        Argument (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the Bessel function, :math:`Y_n(x)`.
+
+    See Also
+    --------
+    yv : For real order and real or complex argument.
+    y0: faster implementation of this function for order 0
+    y1: faster implementation of this function for order 1
+
+    Notes
+    -----
+    Wrapper for the Cephes [1]_ routine `yn`.
+
+    The function is evaluated by forward recurrence on `n`, starting with
+    values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,
+    the routine for `y0` or `y1` is called directly.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import yn
+    >>> yn(0, 1.)
+    0.08825696421567697
+
+    Evaluate the function at one point for different orders.
+
+    >>> yn(0, 1.), yn(1, 1.), yn(2, 1.)
+    (0.08825696421567697, -0.7812128213002888, -1.6506826068162546)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> yn([0, 1, 2], 1.)
+    array([ 0.08825696, -0.78121282, -1.65068261])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 3., 8.])
+    >>> yn(0, points)
+    array([-0.44451873,  0.37685001,  0.22352149])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> yn(orders, points)
+    array([[-0.44451873,  0.37685001,  0.22352149],
+           [-1.47147239,  0.32467442, -0.15806046]])
+
+    Plot the functions of order 0 to 3 from 0 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')
+    >>> ax.set_ylim(-3, 1)
+    >>> ax.legend()
+    >>> plt.show()
+    """)
+
+add_newdoc("yv",
+    r"""
+    yv(v, z, out=None)
+
+    Bessel function of the second kind of real order and complex argument.
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the Bessel function of the second kind, :math:`Y_v(x)`.
+
+    See Also
+    --------
+    yve : :math:`Y_v` with leading exponential behavior stripped off.
+    y0: faster implementation of this function for order 0
+    y1: faster implementation of this function for order 1
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the
+    AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel
+    Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`,
+
+    .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}).
+
+    For negative `v` values the formula,
+
+    .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v)
+
+    is used, where :math:`J_v(z)` is the Bessel function of the first kind,
+    computed using the AMOS routine `zbesj`.  Note that the second term is
+    exactly zero for integer `v`; to improve accuracy the second term is
+    explicitly omitted for `v` values such that `v = floor(v)`.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import yv
+    >>> yv(0, 1.)
+    0.088256964215677
+
+    Evaluate the function at one point for different orders.
+
+    >>> yv(0, 1.), yv(1, 1.), yv(1.5, 1.)
+    (0.088256964215677, -0.7812128213002889, -1.102495575160179)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> yv([0, 1, 1.5], 1.)
+    array([ 0.08825696, -0.78121282, -1.10249558])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 3., 8.])
+    >>> yv(0, points)
+    array([-0.44451873,  0.37685001,  0.22352149])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> yv(orders, points)
+    array([[-0.44451873,  0.37685001,  0.22352149],
+           [-1.47147239,  0.32467442, -0.15806046]])
+
+    Plot the functions of order 0 to 3 from 0 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, yv(i, x), label=f'$Y_{i!r}$')
+    >>> ax.set_ylim(-3, 1)
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("yve",
+    r"""
+    yve(v, z, out=None)
+
+    Exponentially scaled Bessel function of the second kind of real order.
+
+    Returns the exponentially scaled Bessel function of the second
+    kind of real order `v` at complex `z`::
+
+        yve(v, z) = yv(v, z) * exp(-abs(z.imag))
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the exponentially scaled Bessel function.
+
+    See Also
+    --------
+    yv: Unscaled Bessel function of the second kind of real order.
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the
+    AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel
+    Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`,
+
+    .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}).
+
+    For negative `v` values the formula,
+
+    .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v)
+
+    is used, where :math:`J_v(z)` is the Bessel function of the first kind,
+    computed using the AMOS routine `zbesj`.  Note that the second term is
+    exactly zero for integer `v`; to improve accuracy the second term is
+    explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Exponentially scaled Bessel functions are useful for large `z`:
+    for these, the unscaled Bessel functions can easily under-or overflow.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compare the output of `yv` and `yve` for large complex arguments for `z`
+    by computing their values for order ``v=1`` at ``z=1000j``. We see that
+    `yv` returns nan but `yve` returns a finite number:
+
+    >>> import numpy as np
+    >>> from scipy.special import yv, yve
+    >>> v = 1
+    >>> z = 1000j
+    >>> yv(v, z), yve(v, z)
+    ((nan+nanj), (-0.012610930256928629+7.721967686709076e-19j))
+
+    For real arguments for `z`, `yve` returns the same as `yv` up to
+    floating point errors.
+
+    >>> v, z = 1, 1000
+    >>> yv(v, z), yve(v, z)
+    (-0.02478433129235178, -0.02478433129235179)
+
+    The function can be evaluated for several orders at the same time by
+    providing a list or NumPy array for `v`:
+
+    >>> yve([1, 2, 3], 1j)
+    array([-0.20791042+0.14096627j,  0.38053618-0.04993878j,
+           0.00815531-1.66311097j])
+
+    In the same way, the function can be evaluated at several points in one
+    call by providing a list or NumPy array for `z`:
+
+    >>> yve(1, np.array([1j, 2j, 3j]))
+    array([-0.20791042+0.14096627j, -0.21526929+0.01205044j,
+           -0.19682671+0.00127278j])
+
+    It is also possible to evaluate several orders at several points
+    at the same time by providing arrays for `v` and `z` with
+    broadcasting compatible shapes. Compute `yve` for two different orders
+    `v` and three points `z` resulting in a 2x3 array.
+
+    >>> v = np.array([[1], [2]])
+    >>> z = np.array([3j, 4j, 5j])
+    >>> v.shape, z.shape
+    ((2, 1), (3,))
+
+    >>> yve(v, z)
+    array([[-1.96826713e-01+1.27277544e-03j, -1.78750840e-01+1.45558819e-04j,
+            -1.63972267e-01+1.73494110e-05j],
+           [1.94960056e-03-1.11782545e-01j,  2.02902325e-04-1.17626501e-01j,
+            2.27727687e-05-1.17951906e-01j]])
+    """)
+
+add_newdoc("_struve_asymp_large_z",
+    """
+    _struve_asymp_large_z(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using asymptotic expansion
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_struve_power_series",
+    """
+    _struve_power_series(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using power series
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_struve_bessel_series",
+    """
+    _struve_bessel_series(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using Bessel function series
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_spherical_jn",
+    """
+    Internal function, use `spherical_jn` instead.
+    """)
+
+add_newdoc("_spherical_jn_d",
+    """
+    Internal function, use `spherical_jn` instead.
+    """)
+
+add_newdoc("_spherical_yn",
+    """
+    Internal function, use `spherical_yn` instead.
+    """)
+
+add_newdoc("_spherical_yn_d",
+    """
+    Internal function, use `spherical_yn` instead.
+    """)
+
+add_newdoc("_spherical_in",
+    """
+    Internal function, use `spherical_in` instead.
+    """)
+
+add_newdoc("_spherical_in_d",
+    """
+    Internal function, use `spherical_in` instead.
+    """)
+
+add_newdoc("_spherical_kn",
+    """
+    Internal function, use `spherical_kn` instead.
+    """)
+
+add_newdoc("_spherical_kn_d",
+    """
+    Internal function, use `spherical_kn` instead.
+    """)
+
+add_newdoc("owens_t",
+    """
+    owens_t(h, a, out=None)
+
+    Owen's T Function.
+
+    The function T(h, a) gives the probability of the event
+    (X > h and 0 < Y < a * X) where X and Y are independent
+    standard normal random variables.
+
+    Parameters
+    ----------
+    h: array_like
+        Input value.
+    a: array_like
+        Input value.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t: scalar or ndarray
+        Probability of the event (X > h and 0 < Y < a * X),
+        where X and Y are independent standard normal random variables.
+
+    References
+    ----------
+    .. [1] M. Patefield and D. Tandy, "Fast and accurate calculation of
+           Owen's T Function", Statistical Software vol. 5, pp. 1-25, 2000.
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> a = 3.5
+    >>> h = 0.78
+    >>> special.owens_t(h, a)
+    0.10877216734852274
+    """)
+
+add_newdoc("_factorial",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("ndtri_exp",
+    r"""
+    ndtri_exp(y, out=None)
+
+    Inverse of `log_ndtr` vs x. Allows for greater precision than
+    `ndtri` composed with `numpy.exp` for very small values of y and for
+    y close to 0.
+
+    Parameters
+    ----------
+    y : array_like of float
+        Function argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Inverse of the log CDF of the standard normal distribution, evaluated
+        at y.
+
+    See Also
+    --------
+    log_ndtr : log of the standard normal cumulative distribution function
+    ndtr : standard normal cumulative distribution function
+    ndtri : standard normal percentile function
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    `ndtri_exp` agrees with the naive implementation when the latter does
+    not suffer from underflow.
+
+    >>> sc.ndtri_exp(-1)
+    -0.33747496376420244
+    >>> sc.ndtri(np.exp(-1))
+    -0.33747496376420244
+
+    For extreme values of y, the naive approach fails
+
+    >>> sc.ndtri(np.exp(-800))
+    -inf
+    >>> sc.ndtri(np.exp(-1e-20))
+    inf
+
+    whereas `ndtri_exp` is still able to compute the result to high precision.
+
+    >>> sc.ndtri_exp(-800)
+    -39.88469483825668
+    >>> sc.ndtri_exp(-1e-20)
+    9.262340089798409
+    """)
+
+
+add_newdoc("_stirling2_inexact",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc(
+    "_beta_pdf",
+    r"""
+    _beta_pdf(x, a, b)
+
+    Probability density function of beta distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    a, b : array_like
+           Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_beta_ppf",
+    r"""
+    _beta_ppf(x, a, b)
+
+    Percent point function of beta distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    a, b : array_like
+           Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_invgauss_ppf",
+    """
+    _invgauss_ppf(x, mu)
+
+    Percent point function of inverse gaussian distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    mu : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_invgauss_isf",
+    """
+    _invgauss_isf(x, mu, s)
+
+    Inverse survival function of inverse gaussian distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    mu : array_like
+        Positive, real-valued parameters
+    s : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_cauchy_ppf",
+    """
+    _cauchy_ppf(p, loc, scale)
+
+    Percent point function (i.e. quantile) of the Cauchy distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probabilities
+    loc : array_like
+        Location parameter of the distribution.
+    scale : array_like
+        Scale parameter of the distribution.
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_cauchy_isf",
+    """
+    _cauchy_isf(p, loc, scale)
+
+    Inverse survival function of the Cauchy distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probabilities
+    loc : array_like
+        Location parameter of the distribution.
+    scale : array_like
+        Scale parameter of the distribution.
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_pdf",
+    """
+    _ncx2_pdf(x, k, l)
+
+    Probability density function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_cdf",
+    """
+    _ncx2_cdf(x, k, l)
+
+    Cumulative density function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_ppf",
+    """
+    _ncx2_ppf(x, k, l)
+
+    Percent point function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_sf",
+    """
+    _ncx2_sf(x, k, l)
+
+    Survival function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_isf",
+    """
+    _ncx2_isf(x, k, l)
+
+    Inverse survival function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_pdf",
+    """
+    _ncf_pdf(x, v1, v2, l)
+
+    Probability density function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_cdf",
+    """
+    _ncf_cdf(x, v1, v2, l)
+
+    Cumulative density function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_ppf",
+    """
+    _ncf_ppf(x, v1, v2, l)
+
+    Percent point function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_sf",
+    """
+    _ncf_sf(x, v1, v2, l)
+
+    Survival function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_isf",
+    """
+    _ncf_isf(x, v1, v2, l)
+
+    Inverse survival function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_mean",
+    """
+    _ncf_mean(v1, v2, l)
+
+    Mean of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_variance",
+    """
+    _ncf_variance(v1, v2, l)
+
+    Variance of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_skewness",
+    """
+    _ncf_skewness(v1, v2, l)
+
+    Skewness of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_kurtosis_excess",
+    """
+    _ncf_kurtosis_excess(v1, v2, l)
+
+    Kurtosis excess of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_cdf",
+    """
+    _nct_cdf(x, v, l)
+
+    Cumulative density function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_pdf",
+    """
+    _nct_pdf(x, v, l)
+
+    Probability density function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+
+add_newdoc(
+    "_nct_ppf",
+    """
+    _nct_ppf(x, v, l)
+
+    Percent point function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_sf",
+    """
+    _nct_sf(x, v, l)
+
+    Survival function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_isf",
+    """
+    _nct_isf(x, v, l)
+
+    Inverse survival function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_mean",
+    """
+    _nct_mean(v, l)
+
+    Mean of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_variance",
+    """
+    _nct_variance(v, l)
+
+    Variance of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_skewness",
+    """
+    _nct_skewness(v, l)
+
+    Skewness of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_kurtosis_excess",
+    """
+    _nct_kurtosis_excess(v, l)
+
+    Kurtosis excess of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_cdf",
+    """
+    _skewnorm_cdf(x, l, sc, sh)
+
+    Cumulative density function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_ppf",
+    """
+    _skewnorm_ppf(x, l, sc, sh)
+
+    Percent point function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_isf",
+    """
+    _skewnorm_isf(x, l, sc, sh)
+
+    Inverse survival function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_pmf",
+    """
+    _binom_pmf(x, n, p)
+
+    Probability mass function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_cdf",
+    """
+    _binom_cdf(x, n, p)
+
+    Cumulative density function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_ppf",
+    """
+    _binom_ppf(x, n, p)
+
+    Percent point function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_sf",
+    """
+    _binom_sf(x, n, p)
+
+    Survival function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_isf",
+    """
+    _binom_isf(x, n, p)
+
+    Inverse survival function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_pmf",
+    """
+    _nbinom_pmf(x, r, p)
+
+    Probability mass function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_cdf",
+    """
+    _nbinom_cdf(x, r, p)
+
+    Cumulative density function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_ppf",
+    """
+    _nbinom_ppf(x, r, p)
+
+    Percent point function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_sf",
+    """
+    _nbinom_sf(x, r, p)
+
+    Survival function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_isf",
+    """
+    _nbinom_isf(x, r, p)
+
+    Inverse survival function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_mean",
+    """
+    _nbinom_mean(r, p)
+
+    Mean of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_variance",
+    """
+    _nbinom_variance(r, p)
+
+    Variance of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_skewness",
+    """
+    _nbinom_skewness(r, p)
+
+    Skewness of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_kurtosis_excess",
+    """
+    _nbinom_kurtosis_excess(r, p)
+
+    Kurtosis excess of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_pmf",
+    """
+    _hypergeom_pmf(x, r, N, M)
+
+    Probability mass function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_cdf",
+    """
+    _hypergeom_cdf(x, r, N, M)
+
+    Cumulative density function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_hypergeom_sf",
+    """
+    _hypergeom_sf(x, r, N, M)
+
+    Survival function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_hypergeom_mean",
+    """
+    _hypergeom_mean(r, N, M)
+
+    Mean of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_variance",
+    """
+    _hypergeom_variance(r, N, M)
+
+    Mean of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_skewness",
+    """
+    _hypergeom_skewness(r, N, M)
+
+    Skewness of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_basic.py b/venv/lib/python3.10/site-packages/scipy/special/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..76b13b309eed0c036dd226ff96f0e020f296e032
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_basic.py
@@ -0,0 +1,3579 @@
+#
+# Author:  Travis Oliphant, 2002
+#
+
+import numpy as np
+import math
+import warnings
+from collections import defaultdict
+from heapq import heapify, heappop
+from numpy import (pi, asarray, floor, isscalar, sqrt, where,
+                   sin, place, issubdtype, extract, inexact, nan, zeros, sinc)
+
+from . import _ufuncs
+from ._ufuncs import (mathieu_a, mathieu_b, iv, jv, gamma, rgamma,
+                      psi, hankel1, hankel2, yv, kv, poch, binom,
+                      _stirling2_inexact)
+
+from ._gufuncs import _lqn, _lqmn, _rctj, _rcty
+from ._input_validation import _nonneg_int_or_fail
+from . import _specfun
+from ._comb import _comb_int
+from ._multiufuncs import (assoc_legendre_p_all,
+                           legendre_p_all)
+from scipy._lib.deprecation import _deprecated
+
+
+__all__ = [
+    'ai_zeros',
+    'assoc_laguerre',
+    'bei_zeros',
+    'beip_zeros',
+    'ber_zeros',
+    'bernoulli',
+    'berp_zeros',
+    'bi_zeros',
+    'clpmn',
+    'comb',
+    'digamma',
+    'diric',
+    'erf_zeros',
+    'euler',
+    'factorial',
+    'factorial2',
+    'factorialk',
+    'fresnel_zeros',
+    'fresnelc_zeros',
+    'fresnels_zeros',
+    'h1vp',
+    'h2vp',
+    'ivp',
+    'jn_zeros',
+    'jnjnp_zeros',
+    'jnp_zeros',
+    'jnyn_zeros',
+    'jvp',
+    'kei_zeros',
+    'keip_zeros',
+    'kelvin_zeros',
+    'ker_zeros',
+    'kerp_zeros',
+    'kvp',
+    'lmbda',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'lqn',
+    'mathieu_even_coef',
+    'mathieu_odd_coef',
+    'obl_cv_seq',
+    'pbdn_seq',
+    'pbdv_seq',
+    'pbvv_seq',
+    'perm',
+    'polygamma',
+    'pro_cv_seq',
+    'riccati_jn',
+    'riccati_yn',
+    'sinc',
+    'softplus',
+    'stirling2',
+    'y0_zeros',
+    'y1_zeros',
+    'y1p_zeros',
+    'yn_zeros',
+    'ynp_zeros',
+    'yvp',
+    'zeta'
+]
+
+
+__DEPRECATION_MSG_1_15 = (
+    "`scipy.special.{}` is deprecated as of SciPy 1.15.0 and will be "
+    "removed in SciPy 1.17.0. Please use `scipy.special.{}` instead."
+)
+
+# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int64).max
+_FACTORIALK_LIMITS_64BITS = {1: 20, 2: 33, 3: 44, 4: 54, 5: 65,
+                             6: 74, 7: 84, 8: 93, 9: 101}
+# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int32).max
+_FACTORIALK_LIMITS_32BITS = {1: 12, 2: 19, 3: 25, 4: 31, 5: 37,
+                             6: 43, 7: 47, 8: 51, 9: 56}
+
+
+def diric(x, n):
+    """Periodic sinc function, also called the Dirichlet function.
+
+    The Dirichlet function is defined as::
+
+        diric(x, n) = sin(x * n/2) / (n * sin(x / 2)),
+
+    where `n` is a positive integer.
+
+    Parameters
+    ----------
+    x : array_like
+        Input data
+    n : int
+        Integer defining the periodicity.
+
+    Returns
+    -------
+    diric : ndarray
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
+    >>> plt.figure(figsize=(8, 8));
+    >>> for idx, n in enumerate([2, 3, 4, 9]):
+    ...     plt.subplot(2, 2, idx+1)
+    ...     plt.plot(x, special.diric(x, n))
+    ...     plt.title('diric, n={}'.format(n))
+    >>> plt.show()
+
+    The following example demonstrates that `diric` gives the magnitudes
+    (modulo the sign and scaling) of the Fourier coefficients of a
+    rectangular pulse.
+
+    Suppress output of values that are effectively 0:
+
+    >>> np.set_printoptions(suppress=True)
+
+    Create a signal `x` of length `m` with `k` ones:
+
+    >>> m = 8
+    >>> k = 3
+    >>> x = np.zeros(m)
+    >>> x[:k] = 1
+
+    Use the FFT to compute the Fourier transform of `x`, and
+    inspect the magnitudes of the coefficients:
+
+    >>> np.abs(np.fft.fft(x))
+    array([ 3.        ,  2.41421356,  1.        ,  0.41421356,  1.        ,
+            0.41421356,  1.        ,  2.41421356])
+
+    Now find the same values (up to sign) using `diric`. We multiply
+    by `k` to account for the different scaling conventions of
+    `numpy.fft.fft` and `diric`:
+
+    >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
+    >>> k * special.diric(theta, k)
+    array([ 3.        ,  2.41421356,  1.        , -0.41421356, -1.        ,
+           -0.41421356,  1.        ,  2.41421356])
+    """
+    x, n = asarray(x), asarray(n)
+    n = asarray(n + (x-x))
+    x = asarray(x + (n-n))
+    if issubdtype(x.dtype, inexact):
+        ytype = x.dtype
+    else:
+        ytype = float
+    y = zeros(x.shape, ytype)
+
+    # empirical minval for 32, 64 or 128 bit float computations
+    # where sin(x/2) < minval, result is fixed at +1 or -1
+    if np.finfo(ytype).eps < 1e-18:
+        minval = 1e-11
+    elif np.finfo(ytype).eps < 1e-15:
+        minval = 1e-7
+    else:
+        minval = 1e-3
+
+    mask1 = (n <= 0) | (n != floor(n))
+    place(y, mask1, nan)
+
+    x = x / 2
+    denom = sin(x)
+    mask2 = (1-mask1) & (abs(denom) < minval)
+    xsub = extract(mask2, x)
+    nsub = extract(mask2, n)
+    zsub = xsub / pi
+    place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
+
+    mask = (1-mask1) & (1-mask2)
+    xsub = extract(mask, x)
+    nsub = extract(mask, n)
+    dsub = extract(mask, denom)
+    place(y, mask, sin(nsub*xsub)/(nsub*dsub))
+    return y
+
+
+def jnjnp_zeros(nt):
+    """Compute zeros of integer-order Bessel functions Jn and Jn'.
+
+    Results are arranged in order of the magnitudes of the zeros.
+
+    Parameters
+    ----------
+    nt : int
+        Number (<=1200) of zeros to compute
+
+    Returns
+    -------
+    zo[l-1] : ndarray
+        Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
+    n[l-1] : ndarray
+        Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
+    m[l-1] : ndarray
+        Serial number of the zeros of Jn(x) or Jn'(x) associated
+        with lth zero. Of length `nt`.
+    t[l-1] : ndarray
+        0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
+        length `nt`.
+
+    See Also
+    --------
+    jn_zeros, jnp_zeros : to get separated arrays of zeros.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
+        raise ValueError("Number must be integer <= 1200.")
+    nt = int(nt)
+    n, m, t, zo = _specfun.jdzo(nt)
+    return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
+
+
+def jnyn_zeros(n, nt):
+    """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
+
+    Returns 4 arrays of length `nt`, corresponding to the first `nt`
+    zeros of Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively. The zeros
+    are returned in ascending order.
+
+    Parameters
+    ----------
+    n : int
+        Order of the Bessel functions
+    nt : int
+        Number (<=1200) of zeros to compute
+
+    Returns
+    -------
+    Jn : ndarray
+        First `nt` zeros of Jn
+    Jnp : ndarray
+        First `nt` zeros of Jn'
+    Yn : ndarray
+        First `nt` zeros of Yn
+    Ynp : ndarray
+        First `nt` zeros of Yn'
+
+    See Also
+    --------
+    jn_zeros, jnp_zeros, yn_zeros, ynp_zeros
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first three roots of :math:`J_1`, :math:`J_1'`,
+    :math:`Y_1` and :math:`Y_1'`.
+
+    >>> from scipy.special import jnyn_zeros
+    >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
+    >>> jn_roots, yn_roots
+    (array([ 3.83170597,  7.01558667, 10.17346814]),
+     array([2.19714133, 5.42968104, 8.59600587]))
+
+    Plot :math:`J_1`, :math:`J_1'`, :math:`Y_1`, :math:`Y_1'` and their roots.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jnyn_zeros, jvp, jn, yvp, yn
+    >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
+    >>> fig, ax = plt.subplots()
+    >>> xmax= 11
+    >>> x = np.linspace(0, xmax)
+    >>> x[0] += 1e-15
+    >>> ax.plot(x, jn(1, x), label=r"$J_1$", c='r')
+    >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$", c='b')
+    >>> ax.plot(x, yn(1, x), label=r"$Y_1$", c='y')
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$", c='c')
+    >>> zeros = np.zeros((3, ))
+    >>> ax.scatter(jn_roots, zeros, s=30, c='r', zorder=5,
+    ...            label=r"$J_1$ roots")
+    >>> ax.scatter(jnp_roots, zeros, s=30, c='b', zorder=5,
+    ...            label=r"$J_1'$ roots")
+    >>> ax.scatter(yn_roots, zeros, s=30, c='y', zorder=5,
+    ...            label=r"$Y_1$ roots")
+    >>> ax.scatter(ynp_roots, zeros, s=30, c='c', zorder=5,
+    ...            label=r"$Y_1'$ roots")
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.6, 0.6)
+    >>> ax.set_xlim(0, xmax)
+    >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
+    >>> plt.tight_layout()
+    >>> plt.show()
+    """
+    if not (isscalar(nt) and isscalar(n)):
+        raise ValueError("Arguments must be scalars.")
+    if (floor(n) != n) or (floor(nt) != nt):
+        raise ValueError("Arguments must be integers.")
+    if (nt <= 0):
+        raise ValueError("nt > 0")
+    return _specfun.jyzo(abs(n), nt)
+
+
+def jn_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel functions Jn.
+
+    Compute `nt` zeros of the Bessel functions :math:`J_n(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order. Note that this interval excludes the zero at :math:`x = 0`
+    that exists for :math:`n > 0`.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    jv: Real-order Bessel functions of the first kind
+    jnp_zeros: Zeros of :math:`Jn'`
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four positive roots of :math:`J_3`.
+
+    >>> from scipy.special import jn_zeros
+    >>> jn_zeros(3, 4)
+    array([ 6.3801619 ,  9.76102313, 13.01520072, 16.22346616])
+
+    Plot :math:`J_3` and its first four positive roots. Note
+    that the root located at 0 is not returned by `jn_zeros`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jn, jn_zeros
+    >>> j3_roots = jn_zeros(3, 4)
+    >>> xmax = 18
+    >>> xmin = -1
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jn(3, x), label=r'$J_3$')
+    >>> ax.scatter(j3_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"$J_3$_Zeros", zorder=5)
+    >>> ax.scatter(0, 0, s=30, c='k',
+    ...            label=r"Root at 0", zorder=5)
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[0]
+
+
+def jnp_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function derivatives Jn'.
+
+    Compute `nt` zeros of the functions :math:`J_n'(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order. Note that this interval excludes the zero at :math:`x = 0`
+    that exists for :math:`n > 1`.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    jvp: Derivatives of integer-order Bessel functions of the first kind
+    jv: Float-order Bessel functions of the first kind
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`J_2'`.
+
+    >>> from scipy.special import jnp_zeros
+    >>> jnp_zeros(2, 4)
+    array([ 3.05423693,  6.70613319,  9.96946782, 13.17037086])
+
+    As `jnp_zeros` yields the roots of :math:`J_n'`, it can be used to
+    compute the locations of the peaks of :math:`J_n`. Plot
+    :math:`J_2`, :math:`J_2'` and the locations of the roots of :math:`J_2'`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jn, jnp_zeros, jvp
+    >>> j2_roots = jnp_zeros(2, 4)
+    >>> xmax = 15
+    >>> x = np.linspace(0, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jn(2, x), label=r'$J_2$')
+    >>> ax.plot(x, jvp(2, x, 1), label=r"$J_2'$")
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.scatter(j2_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $J_2'$", zorder=5)
+    >>> ax.set_ylim(-0.4, 0.8)
+    >>> ax.set_xlim(0, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[1]
+
+
+def yn_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function Yn(x).
+
+    Compute `nt` zeros of the functions :math:`Y_n(x)` on the interval
+    :math:`(0, \infty)`. The zeros are returned in ascending order.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    yn: Bessel function of the second kind for integer order
+    yv: Bessel function of the second kind for real order
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`Y_2`.
+
+    >>> from scipy.special import yn_zeros
+    >>> yn_zeros(2, 4)
+    array([ 3.38424177,  6.79380751, 10.02347798, 13.20998671])
+
+    Plot :math:`Y_2` and its first four roots.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import yn, yn_zeros
+    >>> xmin = 2
+    >>> xmax = 15
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, yn(2, x), label=r'$Y_2$')
+    >>> ax.scatter(yn_zeros(2, 4), np.zeros((4, )), s=30, c='r',
+    ...            label='Roots', zorder=5)
+    >>> ax.set_ylim(-0.4, 0.4)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[2]
+
+
+def ynp_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function derivatives Yn'(x).
+
+    Compute `nt` zeros of the functions :math:`Y_n'(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel derivative function.
+
+
+    See Also
+    --------
+    yvp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of the first derivative of the
+    Bessel function of second kind for order 0 :math:`Y_0'`.
+
+    >>> from scipy.special import ynp_zeros
+    >>> ynp_zeros(0, 4)
+    array([ 2.19714133,  5.42968104,  8.59600587, 11.74915483])
+
+    Plot :math:`Y_0`, :math:`Y_0'` and confirm visually that the roots of
+    :math:`Y_0'` are located at local extrema of :math:`Y_0`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import yn, ynp_zeros, yvp
+    >>> zeros = ynp_zeros(0, 4)
+    >>> xmax = 13
+    >>> x = np.linspace(0, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, yn(0, x), label=r'$Y_0$')
+    >>> ax.plot(x, yvp(0, x, 1), label=r"$Y_0'$")
+    >>> ax.scatter(zeros, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $Y_0'$", zorder=5)
+    >>> for root in zeros:
+    ...     y0_extremum =  yn(0, root)
+    ...     lower = min(0, y0_extremum)
+    ...     upper = max(0, y0_extremum)
+    ...     ax.vlines(root, lower, upper, color='r')
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.6, 0.6)
+    >>> ax.set_xlim(0, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[3]
+
+
+def y0_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
+
+    The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z0n : ndarray
+        Location of nth zero of Y0(z)
+    y0pz0n : ndarray
+        Value of derivative Y0'(z0) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first 4 real roots and the derivatives at the roots of
+    :math:`Y_0`:
+
+    >>> import numpy as np
+    >>> from scipy.special import y0_zeros
+    >>> zeros, grads = y0_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Roots: {zeros}")
+    ...     print(f"Gradients: {grads}")
+    Roots: [ 0.89358+0.j  3.95768+0.j  7.08605+0.j 10.22235+0.j]
+    Gradients: [-0.87942+0.j  0.40254+0.j -0.3001 +0.j  0.2497 +0.j]
+
+    Plot the real part of :math:`Y_0` and the first four computed roots.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y0
+    >>> xmin = 0
+    >>> xmax = 11
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, y0(x), label=r'$Y_0$')
+    >>> zeros, grads = y0_zeros(4)
+    >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
+    ...            label=r'$Y_0$_zeros', zorder=5)
+    >>> ax.set_ylim(-0.5, 0.6)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend(ncol=2)
+    >>> plt.show()
+
+    Compute the first 4 complex roots and the derivatives at the roots of
+    :math:`Y_0` by setting ``complex=True``:
+
+    >>> y0_zeros(4, True)
+    (array([ -2.40301663+0.53988231j,  -5.5198767 +0.54718001j,
+             -8.6536724 +0.54841207j, -11.79151203+0.54881912j]),
+     array([ 0.10074769-0.88196771j, -0.02924642+0.5871695j ,
+             0.01490806-0.46945875j, -0.00937368+0.40230454j]))
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 0
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def y1_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
+
+    The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z1n : ndarray
+        Location of nth zero of Y1(z)
+    y1pz1n : ndarray
+        Value of derivative Y1'(z1) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first 4 real roots and the derivatives at the roots of
+    :math:`Y_1`:
+
+    >>> import numpy as np
+    >>> from scipy.special import y1_zeros
+    >>> zeros, grads = y1_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Roots: {zeros}")
+    ...     print(f"Gradients: {grads}")
+    Roots: [ 2.19714+0.j  5.42968+0.j  8.59601+0.j 11.74915+0.j]
+    Gradients: [ 0.52079+0.j -0.34032+0.j  0.27146+0.j -0.23246+0.j]
+
+    Extract the real parts:
+
+    >>> realzeros = zeros.real
+    >>> realzeros
+    array([ 2.19714133,  5.42968104,  8.59600587, 11.74915483])
+
+    Plot :math:`Y_1` and the first four computed roots.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y1
+    >>> xmin = 0
+    >>> xmax = 13
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> zeros, grads = y1_zeros(4)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, y1(x), label=r'$Y_1$')
+    >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
+    ...            label=r'$Y_1$_zeros', zorder=5)
+    >>> ax.set_ylim(-0.5, 0.5)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+
+    Compute the first 4 complex roots and the derivatives at the roots of
+    :math:`Y_1` by setting ``complex=True``:
+
+    >>> y1_zeros(4, True)
+    (array([ -0.50274327+0.78624371j,  -3.83353519+0.56235654j,
+             -7.01590368+0.55339305j, -10.17357383+0.55127339j]),
+     array([-0.45952768+1.31710194j,  0.04830191-0.69251288j,
+            -0.02012695+0.51864253j,  0.011614  -0.43203296j]))
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 1
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def y1p_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
+
+    The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z1pn : ndarray
+        Location of nth zero of Y1'(z)
+    y1z1pn : ndarray
+        Value of derivative Y1(z1) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`Y_1'` and the values of
+    :math:`Y_1` at these roots.
+
+    >>> import numpy as np
+    >>> from scipy.special import y1p_zeros
+    >>> y1grad_roots, y1_values = y1p_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Y1' Roots: {y1grad_roots.real}")
+    ...     print(f"Y1 values: {y1_values.real}")
+    Y1' Roots: [ 3.68302  6.9415  10.1234  13.28576]
+    Y1 values: [ 0.41673 -0.30317  0.25091 -0.21897]
+
+    `y1p_zeros` can be used to calculate the extremal points of :math:`Y_1`
+    directly. Here we plot :math:`Y_1` and the first four extrema.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y1, yvp
+    >>> y1_roots, y1_values_at_roots = y1p_zeros(4)
+    >>> real_roots = y1_roots.real
+    >>> xmax = 15
+    >>> x = np.linspace(0, xmax, 500)
+    >>> x[0] += 1e-15
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y1(x), label=r'$Y_1$')
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
+    >>> ax.scatter(real_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $Y_1'$", zorder=5)
+    >>> ax.scatter(real_roots, y1_values_at_roots.real, s=30, c='k',
+    ...            label=r"Extrema of $Y_1$", zorder=5)
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.5, 0.5)
+    >>> ax.set_xlim(0, xmax)
+    >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
+    >>> plt.tight_layout()
+    >>> plt.show()
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 2
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def _bessel_diff_formula(v, z, n, L, phase):
+    # from AMS55.
+    # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
+    # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
+    # For K, you can pull out the exp((v-k)*pi*i) into the caller
+    v = asarray(v)
+    p = 1.0
+    s = L(v-n, z)
+    for i in range(1, n+1):
+        p = phase * (p * (n-i+1)) / i   # = choose(k, i)
+        s += p*L(v-n + i*2, z)
+    return s / (2.**n)
+
+
+def jvp(v, z, n=1):
+    """Compute derivatives of Bessel functions of the first kind.
+
+    Compute the nth derivative of the Bessel function `Jv` with
+    respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like or float
+        Order of Bessel function
+    z : complex
+        Argument at which to evaluate the derivative; can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Bessel function `jv` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Bessel function.
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+
+    Compute the Bessel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import jvp
+    >>> jvp(0, 1, 0), jvp(0, 1, 1), jvp(0, 1, 2)
+    (0.7651976865579666, -0.44005058574493355, -0.3251471008130331)
+
+    Compute the first derivative of the Bessel function of the first
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> jvp([0, 1, 2], 1, 1)
+    array([-0.44005059,  0.3251471 ,  0.21024362])
+
+    Compute the first derivative of the Bessel function of the first
+    kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0., 1.5, 3.])
+    >>> jvp(0, points, 1)
+    array([-0.        , -0.55793651, -0.33905896])
+
+    Plot the Bessel function of the first kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-10, 10, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jvp(1, x, 0), label=r"$J_1$")
+    >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$")
+    >>> ax.plot(x, jvp(1, x, 2), label=r"$J_1''$")
+    >>> ax.plot(x, jvp(1, x, 3), label=r"$J_1'''$")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return jv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, jv, -1)
+
+
+def yvp(v, z, n=1):
+    """Compute derivatives of Bessel functions of the second kind.
+
+    Compute the nth derivative of the Bessel function `Yv` with
+    respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel function
+    z : complex
+        Argument at which to evaluate the derivative
+    n : int, default 1
+        Order of derivative. For 0 returns the BEssel function `yv`
+
+    Returns
+    -------
+    scalar or ndarray
+        nth derivative of the Bessel function.
+
+    See Also
+    --------
+    yv : Bessel functions of the second kind
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Bessel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import yvp
+    >>> yvp(0, 1, 0), yvp(0, 1, 1), yvp(0, 1, 2)
+    (0.088256964215677, 0.7812128213002889, -0.8694697855159659)
+
+    Compute the first derivative of the Bessel function of the second
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> yvp([0, 1, 2], 1, 1)
+    array([0.78121282, 0.86946979, 2.52015239])
+
+    Compute the first derivative of the Bessel function of the
+    second kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> yvp(0, points, 1)
+    array([ 1.47147239,  0.41230863, -0.32467442])
+
+    Plot the Bessel function of the second kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> x[0] += 1e-15
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, yvp(1, x, 0), label=r"$Y_1$")
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
+    >>> ax.plot(x, yvp(1, x, 2), label=r"$Y_1''$")
+    >>> ax.plot(x, yvp(1, x, 3), label=r"$Y_1'''$")
+    >>> ax.set_ylim(-10, 10)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return yv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, yv, -1)
+
+
+def kvp(v, z, n=1):
+    """Compute derivatives of real-order modified Bessel function Kv(z)
+
+    Kv(z) is the modified Bessel function of the second kind.
+    Derivative is calculated with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel function
+    z : array_like of complex
+        Argument at which to evaluate the derivative
+    n : int, default 1
+        Order of derivative. For 0 returns the Bessel function `kv` itself.
+
+    Returns
+    -------
+    out : ndarray
+        The results
+
+    See Also
+    --------
+    kv
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.29.5 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 6.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.29.E5
+
+    Examples
+    --------
+    Compute the modified bessel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import kvp
+    >>> kvp(0, 1, 0), kvp(0, 1, 1), kvp(0, 1, 2)
+    (0.42102443824070834, -0.6019072301972346, 1.0229316684379428)
+
+    Compute the first derivative of the modified Bessel function of the second
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> kvp([0, 1, 2], 1, 1)
+    array([-0.60190723, -1.02293167, -3.85158503])
+
+    Compute the first derivative of the modified Bessel function of the
+    second kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> kvp(0, points, 1)
+    array([-1.65644112, -0.2773878 , -0.04015643])
+
+    Plot the modified bessel function of the second kind and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, kvp(1, x, 0), label=r"$K_1$")
+    >>> ax.plot(x, kvp(1, x, 1), label=r"$K_1'$")
+    >>> ax.plot(x, kvp(1, x, 2), label=r"$K_1''$")
+    >>> ax.plot(x, kvp(1, x, 3), label=r"$K_1'''$")
+    >>> ax.set_ylim(-2.5, 2.5)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return kv(v, z)
+    else:
+        return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
+
+
+def ivp(v, z, n=1):
+    """Compute derivatives of modified Bessel functions of the first kind.
+
+    Compute the nth derivative of the modified Bessel function `Iv`
+    with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like or float
+        Order of Bessel function
+    z : array_like
+        Argument at which to evaluate the derivative; can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0, returns the Bessel function `iv` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        nth derivative of the modified Bessel function.
+
+    See Also
+    --------
+    iv
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.29.5 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 6.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.29.E5
+
+    Examples
+    --------
+    Compute the modified Bessel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import ivp
+    >>> ivp(0, 1, 0), ivp(0, 1, 1), ivp(0, 1, 2)
+    (1.2660658777520084, 0.565159103992485, 0.7009067737595233)
+
+    Compute the first derivative of the modified Bessel function of the first
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> ivp([0, 1, 2], 1, 1)
+    array([0.5651591 , 0.70090677, 0.29366376])
+
+    Compute the first derivative of the modified Bessel function of the
+    first kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0., 1.5, 3.])
+    >>> ivp(0, points, 1)
+    array([0.        , 0.98166643, 3.95337022])
+
+    Plot the modified Bessel function of the first kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-5, 5, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ivp(1, x, 0), label=r"$I_1$")
+    >>> ax.plot(x, ivp(1, x, 1), label=r"$I_1'$")
+    >>> ax.plot(x, ivp(1, x, 2), label=r"$I_1''$")
+    >>> ax.plot(x, ivp(1, x, 3), label=r"$I_1'''$")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return iv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, iv, 1)
+
+
+def h1vp(v, z, n=1):
+    """Compute derivatives of Hankel function H1v(z) with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like
+        Order of Hankel function
+    z : array_like
+        Argument at which to evaluate the derivative. Can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Hankel function `h1v` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Hankel function.
+
+    See Also
+    --------
+    hankel1
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Hankel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import h1vp
+    >>> h1vp(0, 1, 0), h1vp(0, 1, 1), h1vp(0, 1, 2)
+    ((0.7651976865579664+0.088256964215677j),
+     (-0.44005058574493355+0.7812128213002889j),
+     (-0.3251471008130329-0.8694697855159659j))
+
+    Compute the first derivative of the Hankel function of the first kind
+    for several orders at 1 by providing an array for `v`.
+
+    >>> h1vp([0, 1, 2], 1, 1)
+    array([-0.44005059+0.78121282j,  0.3251471 +0.86946979j,
+           0.21024362+2.52015239j])
+
+    Compute the first derivative of the Hankel function of the first kind
+    of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> h1vp(0, points, 1)
+    array([-0.24226846+1.47147239j, -0.55793651+0.41230863j,
+           -0.33905896-0.32467442j])
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return hankel1(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, hankel1, -1)
+
+
+def h2vp(v, z, n=1):
+    """Compute derivatives of Hankel function H2v(z) with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like
+        Order of Hankel function
+    z : array_like
+        Argument at which to evaluate the derivative. Can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Hankel function `h2v` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Hankel function.
+
+    See Also
+    --------
+    hankel2
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Hankel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import h2vp
+    >>> h2vp(0, 1, 0), h2vp(0, 1, 1), h2vp(0, 1, 2)
+    ((0.7651976865579664-0.088256964215677j),
+     (-0.44005058574493355-0.7812128213002889j),
+     (-0.3251471008130329+0.8694697855159659j))
+
+    Compute the first derivative of the Hankel function of the second kind
+    for several orders at 1 by providing an array for `v`.
+
+    >>> h2vp([0, 1, 2], 1, 1)
+    array([-0.44005059-0.78121282j,  0.3251471 -0.86946979j,
+           0.21024362-2.52015239j])
+
+    Compute the first derivative of the Hankel function of the second kind
+    of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> h2vp(0, points, 1)
+    array([-0.24226846-1.47147239j, -0.55793651-0.41230863j,
+           -0.33905896+0.32467442j])
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return hankel2(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, hankel2, -1)
+
+
+def riccati_jn(n, x):
+    r"""Compute Ricatti-Bessel function of the first kind and its derivative.
+
+    The Ricatti-Bessel function of the first kind is defined as :math:`x
+    j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
+    kind of order :math:`n`.
+
+    This function computes the value and first derivative of the
+    Ricatti-Bessel function for all orders up to and including `n`.
+
+    Parameters
+    ----------
+    n : int
+        Maximum order of function to compute
+    x : float
+        Argument at which to evaluate
+
+    Returns
+    -------
+    jn : ndarray
+        Value of j0(x), ..., jn(x)
+    jnp : ndarray
+        First derivative j0'(x), ..., jn'(x)
+
+    Notes
+    -----
+    The computation is carried out via backward recurrence, using the
+    relation DLMF 10.51.1 [2]_.
+
+    Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
+    Jin [1]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.51.E1
+
+    """
+    if not (isscalar(n) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n == 0):
+        n1 = 1
+    else:
+        n1 = n
+
+    jn = np.empty((n1 + 1,), dtype=np.float64)
+    jnp = np.empty_like(jn)
+
+    _rctj(x, out=(jn, jnp))
+    return jn[:(n+1)], jnp[:(n+1)]
+
+
+def riccati_yn(n, x):
+    """Compute Ricatti-Bessel function of the second kind and its derivative.
+
+    The Ricatti-Bessel function of the second kind is defined here as :math:`+x
+    y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
+    kind of order :math:`n`. *Note that this is in contrast to a common convention
+    that includes a minus sign in the definition.*
+
+    This function computes the value and first derivative of the function for
+    all orders up to and including `n`.
+
+    Parameters
+    ----------
+    n : int
+        Maximum order of function to compute
+    x : float
+        Argument at which to evaluate
+
+    Returns
+    -------
+    yn : ndarray
+        Value of y0(x), ..., yn(x)
+    ynp : ndarray
+        First derivative y0'(x), ..., yn'(x)
+
+    Notes
+    -----
+    The computation is carried out via ascending recurrence, using the
+    relation DLMF 10.51.1 [2]_.
+
+    Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
+    Jin [1]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.51.E1
+
+    """
+    if not (isscalar(n) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n == 0):
+        n1 = 1
+    else:
+        n1 = n
+
+    yn = np.empty((n1 + 1,), dtype=np.float64)
+    ynp = np.empty_like(yn)
+    _rcty(x, out=(yn, ynp))
+
+    return yn[:(n+1)], ynp[:(n+1)]
+
+
+def erf_zeros(nt):
+    """Compute the first nt zero in the first quadrant, ordered by absolute value.
+
+    Zeros in the other quadrants can be obtained by using the symmetries
+    erf(-z) = erf(z) and erf(conj(z)) = conj(erf(z)).
+
+
+    Parameters
+    ----------
+    nt : int
+        The number of zeros to compute
+
+    Returns
+    -------
+    The locations of the zeros of erf : ndarray (complex)
+        Complex values at which zeros of erf(z)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> special.erf_zeros(1)
+    array([1.45061616+1.880943j])
+
+    Check that erf is (close to) zero for the value returned by erf_zeros
+
+    >>> special.erf(special.erf_zeros(1))
+    array([4.95159469e-14-1.16407394e-16j])
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.cerzo(nt)
+
+
+def fresnelc_zeros(nt):
+    """Compute nt complex zeros of cosine Fresnel integral C(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    fresnelc_zeros: ndarray
+        Zeros of the cosine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(1, nt)
+
+
+def fresnels_zeros(nt):
+    """Compute nt complex zeros of sine Fresnel integral S(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    fresnels_zeros: ndarray
+        Zeros of the sine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(2, nt)
+
+
+def fresnel_zeros(nt):
+    """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    zeros_sine: ndarray
+        Zeros of the sine Fresnel integral
+    zeros_cosine : ndarray
+        Zeros of the cosine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(2, nt), _specfun.fcszo(1, nt)
+
+
+def assoc_laguerre(x, n, k=0.0):
+    """Compute the generalized (associated) Laguerre polynomial of degree n and order k.
+
+    The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``,
+    with weighting function ``exp(-x) * x**k`` with ``k > -1``.
+
+    Parameters
+    ----------
+    x : float or ndarray
+        Points where to evaluate the Laguerre polynomial
+    n : int
+        Degree of the Laguerre polynomial
+    k : int
+        Order of the Laguerre polynomial
+
+    Returns
+    -------
+    assoc_laguerre: float or ndarray
+        Associated laguerre polynomial values
+
+    Notes
+    -----
+    `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
+    reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
+
+    """
+    return _ufuncs.eval_genlaguerre(n, k, x)
+
+
+digamma = psi
+
+
+def polygamma(n, x):
+    r"""Polygamma functions.
+
+    Defined as :math:`\psi^{(n)}(x)` where :math:`\psi` is the
+    `digamma` function. See [dlmf]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        The order of the derivative of the digamma function; must be
+        integral
+    x : array_like
+        Real valued input
+
+    Returns
+    -------
+    ndarray
+        Function results
+
+    See Also
+    --------
+    digamma
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/5.15
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> x = [2, 3, 25.5]
+    >>> special.polygamma(1, x)
+    array([ 0.64493407,  0.39493407,  0.03999467])
+    >>> special.polygamma(0, x) == special.psi(x)
+    array([ True,  True,  True], dtype=bool)
+
+    """
+    n, x = asarray(n), asarray(x)
+    fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
+    return where(n == 0, psi(x), fac2)
+
+
+def mathieu_even_coef(m, q):
+    r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+    The Fourier series of the even solutions of the Mathieu differential
+    equation are of the form
+
+    .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
+
+    .. math:: \mathrm{ce}_{2n+1}(z, q) =
+              \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
+
+    This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
+    input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
+    m=2n+1.
+
+    Parameters
+    ----------
+    m : int
+        Order of Mathieu functions.  Must be non-negative.
+    q : float (>=0)
+        Parameter of Mathieu functions.  Must be non-negative.
+
+    Returns
+    -------
+    Ak : ndarray
+        Even or odd Fourier coefficients, corresponding to even or odd m.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/28.4#i
+
+    """
+    if not (isscalar(m) and isscalar(q)):
+        raise ValueError("m and q must be scalars.")
+    if (q < 0):
+        raise ValueError("q >=0")
+    if (m != floor(m)) or (m < 0):
+        raise ValueError("m must be an integer >=0.")
+
+    if (q <= 1):
+        qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
+    else:
+        qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
+    km = int(qm + 0.5*m)
+    if km > 251:
+        warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2)
+    kd = 1
+    m = int(floor(m))
+    if m % 2:
+        kd = 2
+
+    a = mathieu_a(m, q)
+    fc = _specfun.fcoef(kd, m, q, a)
+    return fc[:km]
+
+
+def mathieu_odd_coef(m, q):
+    r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+    The Fourier series of the odd solutions of the Mathieu differential
+    equation are of the form
+
+    .. math:: \mathrm{se}_{2n+1}(z, q) =
+              \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
+
+    .. math:: \mathrm{se}_{2n+2}(z, q) =
+              \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
+
+    This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
+    input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
+    input m=2n+1.
+
+    Parameters
+    ----------
+    m : int
+        Order of Mathieu functions.  Must be non-negative.
+    q : float (>=0)
+        Parameter of Mathieu functions.  Must be non-negative.
+
+    Returns
+    -------
+    Bk : ndarray
+        Even or odd Fourier coefficients, corresponding to even or odd m.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(q)):
+        raise ValueError("m and q must be scalars.")
+    if (q < 0):
+        raise ValueError("q >=0")
+    if (m != floor(m)) or (m <= 0):
+        raise ValueError("m must be an integer > 0")
+
+    if (q <= 1):
+        qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
+    else:
+        qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
+    km = int(qm + 0.5*m)
+    if km > 251:
+        warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2)
+    kd = 4
+    m = int(floor(m))
+    if m % 2:
+        kd = 3
+
+    b = mathieu_b(m, q)
+    fc = _specfun.fcoef(kd, m, q, b)
+    return fc[:km]
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("lpmn", "assoc_legendre_p_all"))
+def lpmn(m, n, z):
+    """Sequence of associated Legendre functions of the first kind.
+
+    Computes the associated Legendre function of the first kind of order m and
+    degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
+    ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    This function takes a real argument ``z``. For complex arguments ``z``
+    use clpmn instead.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please `scipy.special.assoc_legendre_p_all` instead.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like
+        Input value.
+
+    Returns
+    -------
+    Pmn_z : (m+1, n+1) array
+       Values for all orders 0..m and degrees 0..n
+    Pmn_d_z : (m+1, n+1) array
+       Derivatives for all orders 0..m and degrees 0..n
+
+    See Also
+    --------
+    clpmn: associated Legendre functions of the first kind for complex z
+
+    Notes
+    -----
+    In the interval (-1, 1), Ferrer's function of the first kind is
+    returned. The phase convention used for the intervals (1, inf)
+    and (-inf, -1) is such that the result is always real.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/14.3
+
+    """
+
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+
+    if (abs(m) > n):
+        raise ValueError("m must be <= n.")
+
+    if np.iscomplexobj(z):
+        raise ValueError("Argument must be real. Use clpmn instead.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+
+    branch_cut = np.where(np.abs(z) <= 1, 2, 3)
+
+    p, pd = assoc_legendre_p_all(n, abs(m), z, branch_cut=branch_cut, diff_n=1)
+    p = np.swapaxes(p, 0, 1)
+    pd = np.swapaxes(pd, 0, 1)
+
+    if (m >= 0):
+        p = p[:(m + 1)]
+        pd = pd[:(m + 1)]
+    else:
+        p = np.insert(p[:(m - 1):-1], 0, p[0], axis=0)
+        pd = np.insert(pd[:(m - 1):-1], 0, pd[0], axis=0)
+
+    return p, pd
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("clpmn", "assoc_legendre_p_all"))
+def clpmn(m, n, z, type=3):
+    """Associated Legendre function of the first kind for complex arguments.
+
+    Computes the associated Legendre function of the first kind of order m and
+    degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
+    ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please use `scipy.special.assoc_legendre_p_all` instead.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like, float or complex
+        Input value.
+    type : int, optional
+       takes values 2 or 3
+       2: cut on the real axis ``|x| > 1``
+       3: cut on the real axis ``-1 < x < 1`` (default)
+
+    Returns
+    -------
+    Pmn_z : (m+1, n+1) array
+       Values for all orders ``0..m`` and degrees ``0..n``
+    Pmn_d_z : (m+1, n+1) array
+       Derivatives for all orders ``0..m`` and degrees ``0..n``
+
+    See Also
+    --------
+    lpmn: associated Legendre functions of the first kind for real z
+
+    Notes
+    -----
+    By default, i.e. for ``type=3``, phase conventions are chosen according
+    to [1]_ such that the function is analytic. The cut lies on the interval
+    (-1, 1). Approaching the cut from above or below in general yields a phase
+    factor with respect to Ferrer's function of the first kind
+    (cf. `lpmn`).
+
+    For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
+    on the interval (-1, 1) in the complex plane yields Ferrer's function
+    of the first kind.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/14.21
+
+    """
+
+    if (abs(m) > n):
+        raise ValueError("m must be <= n.")
+
+    if not (type == 2 or type == 3):
+        raise ValueError("type must be either 2 or 3.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+
+    if not np.iscomplexobj(z):
+        z = np.asarray(z, dtype=complex)
+
+    out, out_jac = assoc_legendre_p_all(n, abs(m), z, branch_cut=type, diff_n=1)
+    out = np.swapaxes(out, 0, 1)
+    out_jac = np.swapaxes(out_jac, 0, 1)
+
+    if (m >= 0):
+        out = out[:(m + 1)]
+        out_jac = out_jac[:(m + 1)]
+    else:
+        out = np.insert(out[:(m - 1):-1], 0, out[0], axis=0)
+        out_jac = np.insert(out_jac[:(m - 1):-1], 0, out_jac[0], axis=0)
+
+    return out, out_jac
+
+
+def lqmn(m, n, z):
+    """Sequence of associated Legendre functions of the second kind.
+
+    Computes the associated Legendre function of the second kind of order m and
+    degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
+    ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like, complex
+        Input value.
+
+    Returns
+    -------
+    Qmn_z : (m+1, n+1) array
+       Values for all orders 0..m and degrees 0..n
+    Qmn_d_z : (m+1, n+1) array
+       Derivatives for all orders 0..m and degrees 0..n
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(m) or (m < 0):
+        raise ValueError("m must be a non-negative integer.")
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+    # Ensure neither m nor n == 0
+    mm = max(1, m)
+    nn = max(1, n)
+
+    z = np.asarray(z)
+    if (not np.issubdtype(z.dtype, np.inexact)):
+        z = z.astype(np.float64)
+
+    if np.iscomplexobj(z):
+        q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.complex128)
+    else:
+        q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.float64)
+    qd = np.empty_like(q)
+    if (z.ndim == 0):
+        _lqmn(z, out=(q, qd))
+    else:
+        # new axes must be last for the ufunc
+        _lqmn(z,
+              out=(np.moveaxis(q, (0, 1), (-2, -1)),
+                   np.moveaxis(qd, (0, 1), (-2, -1))))
+
+    return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
+
+
+def bernoulli(n):
+    """Bernoulli numbers B0..Bn (inclusive).
+
+    Parameters
+    ----------
+    n : int
+        Indicated the number of terms in the Bernoulli series to generate.
+
+    Returns
+    -------
+    ndarray
+        The Bernoulli numbers ``[B(0), B(1), ..., B(n)]``.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] "Bernoulli number", Wikipedia, https://en.wikipedia.org/wiki/Bernoulli_number
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import bernoulli, zeta
+    >>> bernoulli(4)
+    array([ 1.        , -0.5       ,  0.16666667,  0.        , -0.03333333])
+
+    The Wikipedia article ([2]_) points out the relationship between the
+    Bernoulli numbers and the zeta function, ``B_n^+ = -n * zeta(1 - n)``
+    for ``n > 0``:
+
+    >>> n = np.arange(1, 5)
+    >>> -n * zeta(1 - n)
+    array([ 0.5       ,  0.16666667, -0.        , -0.03333333])
+
+    Note that, in the notation used in the wikipedia article,
+    `bernoulli` computes ``B_n^-`` (i.e. it used the convention that
+    ``B_1`` is -1/2).  The relation given above is for ``B_n^+``, so the
+    sign of 0.5 does not match the output of ``bernoulli(4)``.
+
+    """
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    n = int(n)
+    if (n < 2):
+        n1 = 2
+    else:
+        n1 = n
+    return _specfun.bernob(int(n1))[:(n+1)]
+
+
+def euler(n):
+    """Euler numbers E(0), E(1), ..., E(n).
+
+    The Euler numbers [1]_ are also known as the secant numbers.
+
+    Because ``euler(n)`` returns floating point values, it does not give
+    exact values for large `n`.  The first inexact value is E(22).
+
+    Parameters
+    ----------
+    n : int
+        The highest index of the Euler number to be returned.
+
+    Returns
+    -------
+    ndarray
+        The Euler numbers [E(0), E(1), ..., E(n)].
+        The odd Euler numbers, which are all zero, are included.
+
+    References
+    ----------
+    .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences,
+           https://oeis.org/A122045
+    .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import euler
+    >>> euler(6)
+    array([  1.,   0.,  -1.,   0.,   5.,   0., -61.])
+
+    >>> euler(13).astype(np.int64)
+    array([      1,       0,      -1,       0,       5,       0,     -61,
+                 0,    1385,       0,  -50521,       0, 2702765,       0])
+
+    >>> euler(22)[-1]  # Exact value of E(22) is -69348874393137901.
+    -69348874393137976.0
+
+    """
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    n = int(n)
+    if (n < 2):
+        n1 = 2
+    else:
+        n1 = n
+    return _specfun.eulerb(n1)[:(n+1)]
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("lpn", "legendre_p_all"))
+def lpn(n, z):
+    """Legendre function of the first kind.
+
+    Compute sequence of Legendre functions of the first kind (polynomials),
+    Pn(z) and derivatives for all degrees from 0 to n (inclusive).
+
+    See also special.legendre for polynomial class.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please use `scipy.special.legendre_p_all` instead.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    """
+
+    return legendre_p_all(n, z, diff_n=1)
+
+
+def lqn(n, z):
+    """Legendre function of the second kind.
+
+    Compute sequence of Legendre functions of the second kind, Qn(z) and
+    derivatives for all degrees from 0 to n (inclusive).
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+
+    z = np.asarray(z)
+    if (not np.issubdtype(z.dtype, np.inexact)):
+        z = z.astype(float)
+
+    if np.iscomplexobj(z):
+        qn = np.empty((n1 + 1,) + z.shape, dtype=np.complex128)
+    else:
+        qn = np.empty((n1 + 1,) + z.shape, dtype=np.float64)
+    qd = np.empty_like(qn)
+    if (z.ndim == 0):
+        _lqn(z, out=(qn, qd))
+    else:
+          # new axes must be last for the ufunc
+        _lqn(z,
+             out=(np.moveaxis(qn, 0, -1),
+                  np.moveaxis(qd, 0, -1)))
+
+    return qn[:(n+1)], qd[:(n+1)]
+
+
+def ai_zeros(nt):
+    """
+    Compute `nt` zeros and values of the Airy function Ai and its derivative.
+
+    Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
+    first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
+    the corresponding values Ai(a');
+    and the corresponding values Ai'(a).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    a : ndarray
+        First `nt` zeros of Ai(x)
+    ap : ndarray
+        First `nt` zeros of Ai'(x)
+    ai : ndarray
+        Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
+    aip : ndarray
+        Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> a, ap, ai, aip = special.ai_zeros(3)
+    >>> a
+    array([-2.33810741, -4.08794944, -5.52055983])
+    >>> ap
+    array([-1.01879297, -3.24819758, -4.82009921])
+    >>> ai
+    array([ 0.53565666, -0.41901548,  0.38040647])
+    >>> aip
+    array([ 0.70121082, -0.80311137,  0.86520403])
+
+    """
+    kf = 1
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be a positive integer scalar.")
+    return _specfun.airyzo(nt, kf)
+
+
+def bi_zeros(nt):
+    """
+    Compute `nt` zeros and values of the Airy function Bi and its derivative.
+
+    Computes the first `nt` zeros, b, of the Airy function Bi(x);
+    first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
+    the corresponding values Bi(b');
+    and the corresponding values Bi'(b).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    b : ndarray
+        First `nt` zeros of Bi(x)
+    bp : ndarray
+        First `nt` zeros of Bi'(x)
+    bi : ndarray
+        Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
+    bip : ndarray
+        Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> b, bp, bi, bip = special.bi_zeros(3)
+    >>> b
+    array([-1.17371322, -3.2710933 , -4.83073784])
+    >>> bp
+    array([-2.29443968, -4.07315509, -5.51239573])
+    >>> bi
+    array([-0.45494438,  0.39652284, -0.36796916])
+    >>> bip
+    array([ 0.60195789, -0.76031014,  0.83699101])
+
+    """
+    kf = 2
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be a positive integer scalar.")
+    return _specfun.airyzo(nt, kf)
+
+
+def lmbda(v, x):
+    r"""Jahnke-Emden Lambda function, Lambdav(x).
+
+    This function is defined as [2]_,
+
+    .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
+
+    where :math:`\Gamma` is the gamma function and :math:`J_v` is the
+    Bessel function of the first kind.
+
+    Parameters
+    ----------
+    v : float
+        Order of the Lambda function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    vl : ndarray
+        Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dl : ndarray
+        Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
+           Curves" (4th ed.), Dover, 1945
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    if (v < 0):
+        raise ValueError("argument must be > 0.")
+    n = int(v)
+    v0 = v - n
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    if (v != floor(v)):
+        vm, vl, dl = _specfun.lamv(v1, x)
+    else:
+        vm, vl, dl = _specfun.lamn(v1, x)
+    return vl[:(n+1)], dl[:(n+1)]
+
+
+def pbdv_seq(v, x):
+    """Parabolic cylinder functions Dv(x) and derivatives.
+
+    Parameters
+    ----------
+    v : float
+        Order of the parabolic cylinder function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dp : ndarray
+        Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = int(v)
+    v0 = v-n
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    dv, dp, pdf, pdd = _specfun.pbdv(v1, x)
+    return dv[:n1+1], dp[:n1+1]
+
+
+def pbvv_seq(v, x):
+    """Parabolic cylinder functions Vv(x) and derivatives.
+
+    Parameters
+    ----------
+    v : float
+        Order of the parabolic cylinder function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dp : ndarray
+        Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = int(v)
+    v0 = v-n
+    if (n <= 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    dv, dp, pdf, pdd = _specfun.pbvv(v1, x)
+    return dv[:n1+1], dp[:n1+1]
+
+
+def pbdn_seq(n, z):
+    """Parabolic cylinder functions Dn(z) and derivatives.
+
+    Parameters
+    ----------
+    n : int
+        Order of the parabolic cylinder function
+    z : complex
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of D_i(z), for i=0, ..., i=n.
+    dp : ndarray
+        Derivatives D_i'(z), for i=0, ..., i=n.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(n) and isscalar(z)):
+        raise ValueError("arguments must be scalars.")
+    if (floor(n) != n):
+        raise ValueError("n must be an integer.")
+    if (abs(n) <= 1):
+        n1 = 1
+    else:
+        n1 = n
+    cpb, cpd = _specfun.cpbdn(n1, z)
+    return cpb[:n1+1], cpd[:n1+1]
+
+
+def ber_zeros(nt):
+    """Compute nt zeros of the Kelvin function ber.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    ber
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 1)
+
+
+def bei_zeros(nt):
+    """Compute nt zeros of the Kelvin function bei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    bei
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 2)
+
+
+def ker_zeros(nt):
+    """Compute nt zeros of the Kelvin function ker.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    ker
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 3)
+
+
+def kei_zeros(nt):
+    """Compute nt zeros of the Kelvin function kei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    kei
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 4)
+
+
+def berp_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function ber.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    ber, berp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+
+    Examples
+    --------
+    Compute the first 5 zeros of the derivative of the Kelvin function.
+
+    >>> from scipy.special import berp_zeros
+    >>> berp_zeros(5)
+    array([ 6.03871081, 10.51364251, 14.96844542, 19.41757493, 23.86430432])
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 5)
+
+
+def beip_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function bei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    bei, beip
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 6)
+
+
+def kerp_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function ker.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    ker, kerp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 7)
+
+
+def keip_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function kei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    kei, keip
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 8)
+
+
+def kelvin_zeros(nt):
+    """Compute nt zeros of all Kelvin functions.
+
+    Returned in a length-8 tuple of arrays of length nt.  The tuple contains
+    the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return (_specfun.klvnzo(nt, 1),
+            _specfun.klvnzo(nt, 2),
+            _specfun.klvnzo(nt, 3),
+            _specfun.klvnzo(nt, 4),
+            _specfun.klvnzo(nt, 5),
+            _specfun.klvnzo(nt, 6),
+            _specfun.klvnzo(nt, 7),
+            _specfun.klvnzo(nt, 8))
+
+
+def pro_cv_seq(m, n, c):
+    """Characteristic values for prolate spheroidal wave functions.
+
+    Compute a sequence of characteristic values for the prolate
+    spheroidal wave functions for mode m and n'=m..n and spheroidal
+    parameter c.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(n) and isscalar(c)):
+        raise ValueError("Arguments must be scalars.")
+    if (n != floor(n)) or (m != floor(m)):
+        raise ValueError("Modes must be integers.")
+    if (n-m > 199):
+        raise ValueError("Difference between n and m is too large.")
+    maxL = n-m+1
+    return _specfun.segv(m, n, c, 1)[1][:maxL]
+
+
+def obl_cv_seq(m, n, c):
+    """Characteristic values for oblate spheroidal wave functions.
+
+    Compute a sequence of characteristic values for the oblate
+    spheroidal wave functions for mode m and n'=m..n and spheroidal
+    parameter c.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(n) and isscalar(c)):
+        raise ValueError("Arguments must be scalars.")
+    if (n != floor(n)) or (m != floor(m)):
+        raise ValueError("Modes must be integers.")
+    if (n-m > 199):
+        raise ValueError("Difference between n and m is too large.")
+    maxL = n-m+1
+    return _specfun.segv(m, n, c, -1)[1][:maxL]
+
+
+def comb(N, k, *, exact=False, repetition=False):
+    """The number of combinations of N things taken k at a time.
+
+    This is often expressed as "N choose k".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    k : int, ndarray
+        Number of elements taken.
+    exact : bool, optional
+        For integers, if `exact` is False, then floating point precision is
+        used, otherwise the result is computed exactly.
+
+        .. deprecated:: 1.14.0
+            ``exact=True`` is deprecated for non-integer `N` and `k` and will raise an
+            error in SciPy 1.16.0
+    repetition : bool, optional
+        If `repetition` is True, then the number of combinations with
+        repetition is computed.
+
+    Returns
+    -------
+    val : int, float, ndarray
+        The total number of combinations.
+
+    See Also
+    --------
+    binom : Binomial coefficient considered as a function of two real
+            variables.
+
+    Notes
+    -----
+    - Array arguments accepted only for exact=False case.
+    - If N < 0, or k < 0, then 0 is returned.
+    - If k > N and repetition=False, then 0 is returned.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import comb
+    >>> k = np.array([3, 4])
+    >>> n = np.array([10, 10])
+    >>> comb(n, k, exact=False)
+    array([ 120.,  210.])
+    >>> comb(10, 3, exact=True)
+    120
+    >>> comb(10, 3, exact=True, repetition=True)
+    220
+
+    """
+    if repetition:
+        return comb(N + k - 1, k, exact=exact)
+    if exact:
+        if int(N) == N and int(k) == k:
+            # _comb_int casts inputs to integers, which is safe & intended here
+            return _comb_int(N, k)
+        # otherwise, we disregard `exact=True`; it makes no sense for
+        # non-integral arguments
+        msg = ("`exact=True` is deprecated for non-integer `N` and `k` and will raise "
+               "an error in SciPy 1.16.0")
+        warnings.warn(msg, DeprecationWarning, stacklevel=2)
+        return comb(N, k)
+    else:
+        k, N = asarray(k), asarray(N)
+        cond = (k <= N) & (N >= 0) & (k >= 0)
+        vals = binom(N, k)
+        if isinstance(vals, np.ndarray):
+            vals[~cond] = 0
+        elif not cond:
+            vals = np.float64(0)
+        return vals
+
+
+def perm(N, k, exact=False):
+    """Permutations of N things taken k at a time, i.e., k-permutations of N.
+
+    It's also known as "partial permutations".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    k : int, ndarray
+        Number of elements taken.
+    exact : bool, optional
+        If ``True``, calculate the answer exactly using long integer arithmetic (`N`
+        and `k` must be scalar integers). If ``False``, a floating point approximation
+        is calculated (more rapidly) using `poch`. Default is ``False``.
+
+    Returns
+    -------
+    val : int, ndarray
+        The number of k-permutations of N.
+
+    Notes
+    -----
+    - Array arguments accepted only for exact=False case.
+    - If k > N, N < 0, or k < 0, then a 0 is returned.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import perm
+    >>> k = np.array([3, 4])
+    >>> n = np.array([10, 10])
+    >>> perm(n, k)
+    array([  720.,  5040.])
+    >>> perm(10, 3, exact=True)
+    720
+
+    """
+    if exact:
+        N = np.squeeze(N)[()]  # for backward compatibility (accepted size 1 arrays)
+        k = np.squeeze(k)[()]
+        if not (isscalar(N) and isscalar(k)):
+            raise ValueError("`N` and `k` must scalar integers be with `exact=True`.")
+
+        floor_N, floor_k = int(N), int(k)
+        non_integral = not (floor_N == N and floor_k == k)
+        if (k > N) or (N < 0) or (k < 0):
+            if non_integral:
+                msg = ("Non-integer `N` and `k` with `exact=True` is deprecated and "
+                       "will raise an error in SciPy 1.16.0.")
+                warnings.warn(msg, DeprecationWarning, stacklevel=2)
+            return 0
+        if non_integral:
+            raise ValueError("Non-integer `N` and `k` with `exact=True` is not "
+                             "supported.")
+        val = 1
+        for i in range(floor_N - floor_k + 1, floor_N + 1):
+            val *= i
+        return val
+    else:
+        k, N = asarray(k), asarray(N)
+        cond = (k <= N) & (N >= 0) & (k >= 0)
+        vals = poch(N - k + 1, k)
+        if isinstance(vals, np.ndarray):
+            vals[~cond] = 0
+        elif not cond:
+            vals = np.float64(0)
+        return vals
+
+
+# https://stackoverflow.com/a/16327037
+def _range_prod(lo, hi, k=1):
+    """
+    Product of a range of numbers spaced k apart (from hi).
+
+    For k=1, this returns the product of
+    lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi
+    = hi! / (lo-1)!
+
+    For k>1, it correspond to taking only every k'th number when
+    counting down from hi - e.g. 18!!!! = _range_prod(1, 18, 4).
+
+    Breaks into smaller products first for speed:
+    _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9))
+    """
+    if lo == 1 and k == 1:
+        return math.factorial(hi)
+
+    if lo + k < hi:
+        mid = (hi + lo) // 2
+        if k > 1:
+            # make sure mid is a multiple of k away from hi
+            mid = mid - ((mid - hi) % k)
+        return _range_prod(lo, mid, k) * _range_prod(mid + k, hi, k)
+    elif lo + k == hi:
+        return lo * hi
+    else:
+        return hi
+
+
+def _factorialx_array_exact(n, k=1):
+    """
+    Exact computation of factorial for an array.
+
+    The factorials are computed in incremental fashion, by taking
+    the sorted unique values of n and multiplying the intervening
+    numbers between the different unique values.
+
+    In other words, the factorial for the largest input is only
+    computed once, with each other result computed in the process.
+
+    k > 1 corresponds to the multifactorial.
+    """
+    un = np.unique(n)
+    # numpy changed nan-sorting behaviour with 1.21, see numpy/numpy#18070;
+    # to unify the behaviour, we remove the nan's here; the respective
+    # values will be set separately at the end
+    un = un[~np.isnan(un)]
+
+    # Convert to object array if np.int64 can't handle size
+    if np.isnan(n).any():
+        dt = float
+    elif k in _FACTORIALK_LIMITS_64BITS.keys():
+        if un[-1] > _FACTORIALK_LIMITS_64BITS[k]:
+            # e.g. k=1: 21! > np.iinfo(np.int64).max
+            dt = object
+        elif un[-1] > _FACTORIALK_LIMITS_32BITS[k]:
+            # e.g. k=3: 26!!! > np.iinfo(np.int32).max
+            dt = np.int64
+        else:
+            dt = np.dtype("long")
+    else:
+        # for k >= 10, we always use object
+        dt = object
+
+    out = np.empty_like(n, dtype=dt)
+
+    # Handle invalid/trivial values
+    un = un[un > 1]
+    out[n < 2] = 1
+    out[n < 0] = 0
+
+    # Calculate products of each range of numbers
+    # we can only multiply incrementally if the values are k apart;
+    # therefore we partition `un` into "lanes", i.e. its residues modulo k
+    for lane in range(0, k):
+        ul = un[(un % k) == lane] if k > 1 else un
+        if ul.size:
+            # after np.unique, un resp. ul are sorted, ul[0] is the smallest;
+            # cast to python ints to avoid overflow with np.int-types
+            val = _range_prod(1, int(ul[0]), k=k)
+            out[n == ul[0]] = val
+            for i in range(len(ul) - 1):
+                # by the filtering above, we have ensured that prev & current
+                # are a multiple of k apart
+                prev = ul[i]
+                current = ul[i + 1]
+                # we already multiplied all factors until prev; continue
+                # building the full factorial from the following (`prev + 1`);
+                # use int() for the same reason as above
+                val *= _range_prod(int(prev + 1), int(current), k=k)
+                out[n == current] = val
+
+    if np.isnan(n).any():
+        out = out.astype(np.float64)
+        out[np.isnan(n)] = np.nan
+    return out
+
+
+def _factorialx_array_approx(n, k, extend):
+    """
+    Calculate approximation to multifactorial for array n and integer k.
+
+    Ensure that values aren't calculated unnecessarily.
+    """
+    if extend == "complex":
+        return _factorialx_approx_core(n, k=k, extend=extend)
+
+    # at this point we are guaranteed that extend='zero' and that k>0 is an integer
+    result = zeros(n.shape)
+    # keep nans as nans
+    place(result, np.isnan(n), np.nan)
+    # only compute where n >= 0 (excludes nans), everything else is 0
+    cond = (n >= 0)
+    n_to_compute = extract(cond, n)
+    place(result, cond, _factorialx_approx_core(n_to_compute, k=k, extend=extend))
+    return result
+
+
+def _gamma1p(vals):
+    """
+    returns gamma(n+1), though with NaN at -1 instead of inf, c.f. #21827
+    """
+    res = gamma(vals + 1)
+    # replace infinities at -1 (from gamma function at 0) with nan
+    # gamma only returns inf for real inputs; can ignore complex case
+    if isinstance(res, np.ndarray):
+        if not _is_subdtype(vals.dtype, "c"):
+            res[vals == -1] = np.nan
+    elif np.isinf(res) and vals == -1:
+        res = np.float64("nan")
+    return res
+
+
+def _factorialx_approx_core(n, k, extend):
+    """
+    Core approximation to multifactorial for array n and integer k.
+    """
+    if k == 1:
+        # shortcut for k=1; same for both extensions, because we assume the
+        # handling of extend == 'zero' happens in _factorialx_array_approx
+        result = _gamma1p(n)
+        if isinstance(n, np.ndarray):
+            # gamma does not maintain 0-dim arrays; fix it
+            result = np.array(result)
+        return result
+
+    if extend == "complex":
+        # see https://numpy.org/doc/stable/reference/generated/numpy.power.html
+        p_dtype = complex if (_is_subdtype(type(k), "c") or k < 0) else None
+        with warnings.catch_warnings():
+            # do not warn about 0 * inf, nan / nan etc.; the results are correct
+            warnings.simplefilter("ignore", RuntimeWarning)
+            # don't use `(n-1)/k` in np.power; underflows if 0 is of a uintX type
+            result = np.power(k, n / k, dtype=p_dtype) * _gamma1p(n / k)
+            result *= rgamma(1 / k + 1) / np.power(k, 1 / k, dtype=p_dtype)
+        if isinstance(n, np.ndarray):
+            # ensure we keep array-ness for 0-dim inputs; already n/k above loses it
+            result = np.array(result)
+        return result
+
+    # at this point we are guaranteed that extend='zero' and that k>0 is an integer
+    n_mod_k = n % k
+    # scalar case separately, unified handling would be inefficient for arrays;
+    # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below
+    if not isinstance(n, np.ndarray):
+        return (
+            np.power(k, (n - n_mod_k) / k)
+            * gamma(n / k + 1) / gamma(n_mod_k / k + 1)
+            * max(n_mod_k, 1)
+        )
+
+    # factor that's independent of the residue class (see factorialk docstring)
+    result = np.power(k, n / k) * gamma(n / k + 1)
+    # factor dependent on residue r (for `r=0` it's 1, so we skip `r=0`
+    # below and thus also avoid evaluating `max(r, 1)`)
+    def corr(k, r): return np.power(k, -r / k) / gamma(r / k + 1) * r
+    for r in np.unique(n_mod_k):
+        if r == 0:
+            continue
+        # cast to int because uint types break on `-r`
+        result[n_mod_k == r] *= corr(k, int(r))
+    return result
+
+
+def _is_subdtype(dtype, dtypes):
+    """
+    Shorthand for calculating whether dtype is subtype of some dtypes.
+
+    Also allows specifying a list instead of just a single dtype.
+
+    Additionaly, the most important supertypes from
+        https://numpy.org/doc/stable/reference/arrays.scalars.html
+    can optionally be specified using abbreviations as follows:
+        "i": np.integer
+        "f": np.floating
+        "c": np.complexfloating
+        "n": np.number (contains the other three)
+    """
+    dtypes = dtypes if isinstance(dtypes, list) else [dtypes]
+    # map single character abbreviations, if they are in dtypes
+    mapping = {
+        "i": np.integer,
+        "f": np.floating,
+        "c": np.complexfloating,
+        "n": np.number
+    }
+    dtypes = [mapping.get(x, x) for x in dtypes]
+    return any(np.issubdtype(dtype, dt) for dt in dtypes)
+
+
+def _factorialx_wrapper(fname, n, k, exact, extend):
+    """
+    Shared implementation for factorial, factorial2 & factorialk.
+    """
+    if extend not in ("zero", "complex"):
+        raise ValueError(
+            f"argument `extend` must be either 'zero' or 'complex', received: {extend}"
+        )
+    if exact and extend == "complex":
+        raise ValueError("Incompatible options: `exact=True` and `extend='complex'`")
+
+    msg_unsup = (
+        "Unsupported data type for {vname} in {fname}: {dtype}\n"
+    )
+    if fname == "factorial":
+        msg_unsup += (
+            "Permitted data types are integers and floating point numbers, "
+            "as well as complex numbers if `extend='complex' is passed."
+        )
+    else:
+        msg_unsup += (
+            "Permitted data types are integers, as well as floating point "
+            "numbers and complex numbers if `extend='complex' is passed."
+        )
+    msg_exact_not_possible = (
+        "`exact=True` only supports integers, cannot use data type {dtype}"
+    )
+    msg_needs_complex = (
+        "In order to use non-integer arguments, you must opt into this by passing "
+        "`extend='complex'`. Note that this changes the result for all negative "
+        "arguments (which by default return 0)."
+    )
+
+    if fname == "factorial2":
+        msg_needs_complex += (" Additionally, it will rescale the values of the double"
+                              " factorial at even integers by a factor of sqrt(2/pi).")
+    elif fname == "factorialk":
+        msg_needs_complex += (" Additionally, it will perturb the values of the"
+                              " multifactorial at most positive integers `n`.")
+        # check type of k
+        if not _is_subdtype(type(k), ["i", "f", "c"]):
+            raise ValueError(msg_unsup.format(vname="`k`", fname=fname, dtype=type(k)))
+        elif _is_subdtype(type(k), ["f", "c"]) and extend != "complex":
+            raise ValueError(msg_needs_complex)
+        # check value of k
+        if extend == "zero" and k < 1:
+            msg = f"For `extend='zero'`, k must be a positive integer, received: {k}"
+            raise ValueError(msg)
+        elif k == 0:
+            raise ValueError("Parameter k cannot be zero!")
+
+    # factorial allows floats also for extend="zero"
+    types_requiring_complex = "c" if fname == "factorial" else ["f", "c"]
+
+    # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below
+    if np.ndim(n) == 0 and not isinstance(n, np.ndarray):
+        # scalar cases
+        if not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=type(n)))
+        elif _is_subdtype(type(n), types_requiring_complex) and extend != "complex":
+            raise ValueError(msg_needs_complex)
+        elif n is None or np.isnan(n):
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            return np.complex128("nan+nanj") if complexify else np.float64("nan")
+        elif extend == "zero" and n < 0:
+            return 0 if exact else np.float64(0)
+        elif n in {0, 1}:
+            return 1 if exact else np.float64(1)
+        elif exact and _is_subdtype(type(n), "i"):
+            # calculate with integers
+            return _range_prod(1, n, k=k)
+        elif exact:
+            # only relevant for factorial
+            raise ValueError(msg_exact_not_possible.format(dtype=type(n)))
+        # approximation
+        return _factorialx_approx_core(n, k=k, extend=extend)
+
+    # arrays & array-likes
+    n = asarray(n)
+
+    if not _is_subdtype(n.dtype, ["i", "f", "c"]):
+        raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=n.dtype))
+    elif _is_subdtype(n.dtype, types_requiring_complex) and extend != "complex":
+        raise ValueError(msg_needs_complex)
+    elif exact and _is_subdtype(n.dtype, ["f"]):
+        # only relevant for factorial
+        raise ValueError(msg_exact_not_possible.format(dtype=n.dtype))
+
+    if n.size == 0:
+        # return empty arrays unchanged
+        return n
+    elif exact:
+        # calculate with integers
+        return _factorialx_array_exact(n, k=k)
+    # approximation
+    return _factorialx_array_approx(n, k=k, extend=extend)
+
+
+def factorial(n, exact=False, extend="zero"):
+    """
+    The factorial of a number or array of numbers.
+
+    The factorial of non-negative integer `n` is the product of all
+    positive integers less than or equal to `n`::
+
+        n! = n * (n - 1) * (n - 2) * ... * 1
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for ``n!``. Complex values require ``extend='complex'``.
+        By default, the return value for ``n < 0`` is 0.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise approximate using the gamma function
+        (faster, but yields floats instead of integers).
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0``
+        are handled - by default they are 0, but it is possible to opt into the
+        complex extension of the factorial (see below).
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Factorial of ``n``, as integer, float or complex (depending on ``exact``
+        and ``extend``). Array inputs are returned as arrays.
+
+    Notes
+    -----
+    For arrays with ``exact=True``, the factorial is computed only once, for
+    the largest input, with each other result computed in the process.
+    The output dtype is increased to ``int64`` or ``object`` if necessary.
+
+    With ``exact=False`` the factorial is approximated using the gamma
+    function (which is also the definition of the complex extension):
+
+    .. math:: n! = \\Gamma(n+1)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import factorial
+    >>> arr = np.array([3, 4, 5])
+    >>> factorial(arr, exact=False)
+    array([   6.,   24.,  120.])
+    >>> factorial(arr, exact=True)
+    array([  6,  24, 120])
+    >>> factorial(5, exact=True)
+    120
+
+    """
+    return _factorialx_wrapper("factorial", n, k=1, exact=exact, extend=extend)
+
+
+def factorial2(n, exact=False, extend="zero"):
+    """Double factorial.
+
+    This is the factorial with every second value skipped.  E.g., ``7!! = 7 * 5
+    * 3 * 1``.  It can be approximated numerically as::
+
+      n!! = 2 ** (n / 2) * gamma(n / 2 + 1) * sqrt(2 / pi)  n odd
+          = 2 ** (n / 2) * gamma(n / 2 + 1)                 n even
+          = 2 ** (n / 2) * (n / 2)!                         n even
+
+    The formula for odd ``n`` is the basis for the complex extension.
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for ``n!!``. Non-integer values require ``extend='complex'``.
+        By default, the return value for ``n < 0`` is 0.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise use above approximation (faster,
+        but yields floats instead of integers).
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0``
+        are handled - by default they are 0, but it is possible to opt into the
+        complex extension of the double factorial. This also enables passing
+        complex values to ``n``.
+
+        .. warning::
+
+           Using the ``'complex'`` extension also changes the values of the
+           double factorial for even integers, reducing them by a factor of
+           ``sqrt(2/pi) ~= 0.79``, see [1].
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Double factorial of ``n``, as integer, float or complex (depending on
+        ``exact`` and ``extend``). Array inputs are returned as arrays.
+
+    Examples
+    --------
+    >>> from scipy.special import factorial2
+    >>> factorial2(7, exact=False)
+    array(105.00000000000001)
+    >>> factorial2(7, exact=True)
+    105
+
+    References
+    ----------
+    .. [1] Complex extension to double factorial
+            https://en.wikipedia.org/wiki/Double_factorial#Complex_arguments
+    """
+    return _factorialx_wrapper("factorial2", n, k=2, exact=exact, extend=extend)
+
+
+def factorialk(n, k, exact=False, extend="zero"):
+    """Multifactorial of n of order k, n(!!...!).
+
+    This is the multifactorial of n skipping k values.  For example,
+
+      factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
+
+    In particular, for any integer ``n``, we have
+
+      factorialk(n, 1) = factorial(n)
+
+      factorialk(n, 2) = factorial2(n)
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for multifactorial. Non-integer values require
+        ``extend='complex'``. By default, the return value for ``n < 0`` is 0.
+    n : int or float or complex (or array_like thereof)
+        Order of multifactorial. Non-integer values require ``extend='complex'``.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise use an approximation (faster,
+        but yields floats instead of integers)
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0`` are
+        handled - by default they are 0, but it is possible to opt into the complex
+        extension of the multifactorial. This enables passing complex values,
+        not only to ``n`` but also to ``k``.
+
+        .. warning::
+
+           Using the ``'complex'`` extension also changes the values of the
+           multifactorial at integers ``n != 1 (mod k)`` by a factor depending
+           on both ``k`` and ``n % k``, see below or [1].
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Multifactorial (order ``k``) of ``n``, as integer, float or complex (depending
+        on ``exact`` and ``extend``). Array inputs are returned as arrays.
+
+    Examples
+    --------
+    >>> from scipy.special import factorialk
+    >>> factorialk(5, k=1, exact=True)
+    120
+    >>> factorialk(5, k=3, exact=True)
+    10
+    >>> factorialk([5, 7, 9], k=3, exact=True)
+    array([ 10,  28, 162])
+    >>> factorialk([5, 7, 9], k=3, exact=False)
+    array([ 10.,  28., 162.])
+
+    Notes
+    -----
+    While less straight-forward than for the double-factorial, it's possible to
+    calculate a general approximation formula of n!(k) by studying ``n`` for a given
+    remainder ``r < k`` (thus ``n = m * k + r``, resp. ``r = n % k``), which can be
+    put together into something valid for all integer values ``n >= 0`` & ``k > 0``::
+
+      n!(k) = k ** ((n - r)/k) * gamma(n/k + 1) / gamma(r/k + 1) * max(r, 1)
+
+    This is the basis of the approximation when ``exact=False``.
+
+    In principle, any fixed choice of ``r`` (ignoring its relation ``r = n%k``
+    to ``n``) would provide a suitable analytic continuation from integer ``n``
+    to complex ``z`` (not only satisfying the functional equation but also
+    being logarithmically convex, c.f. Bohr-Mollerup theorem) -- in fact, the
+    choice of ``r`` above only changes the function by a constant factor. The
+    final constraint that determines the canonical continuation is ``f(1) = 1``,
+    which forces ``r = 1`` (see also [1]).::
+
+      z!(k) = k ** ((z - 1)/k) * gamma(z/k + 1) / gamma(1/k + 1)
+
+    References
+    ----------
+    .. [1] Complex extension to multifactorial
+            https://en.wikipedia.org/wiki/Double_factorial#Alternative_extension_of_the_multifactorial
+    """
+    return _factorialx_wrapper("factorialk", n, k=k, exact=exact, extend=extend)
+
+
+def stirling2(N, K, *, exact=False):
+    r"""Generate Stirling number(s) of the second kind.
+
+    Stirling numbers of the second kind count the number of ways to
+    partition a set with N elements into K non-empty subsets.
+
+    The values this function returns are calculated using a dynamic
+    program which avoids redundant computation across the subproblems
+    in the solution. For array-like input, this implementation also
+    avoids redundant computation across the different Stirling number
+    calculations.
+
+    The numbers are sometimes denoted
+
+    .. math::
+
+        {N \brace{K}}
+
+    see [1]_ for details. This is often expressed-verbally-as
+    "N subset K".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    K : int, ndarray
+        Number of non-empty subsets taken.
+    exact : bool, optional
+        Uses dynamic programming (DP) with floating point
+        numbers for smaller arrays and uses a second order approximation due to
+        Temme for larger entries  of `N` and `K` that allows trading speed for
+        accuracy. See [2]_ for a description. Temme approximation is used for
+        values ``n>50``. The max error from the DP has max relative error
+        ``4.5*10^-16`` for ``n<=50`` and the max error from the Temme approximation
+        has max relative error ``5*10^-5`` for ``51 <= n < 70`` and
+        ``9*10^-6`` for ``70 <= n < 101``. Note that these max relative errors will
+        decrease further as `n` increases.
+
+    Returns
+    -------
+    val : int, float, ndarray
+        The number of partitions.
+
+    See Also
+    --------
+    comb : The number of combinations of N things taken k at a time.
+
+    Notes
+    -----
+    - If N < 0, or K < 0, then 0 is returned.
+    - If K > N, then 0 is returned.
+
+    The output type will always be `int` or ndarray of `object`.
+    The input must contain either numpy or python integers otherwise a
+    TypeError is raised.
+
+    References
+    ----------
+    .. [1] R. L. Graham, D. E. Knuth and O. Patashnik, "Concrete
+        Mathematics: A Foundation for Computer Science," Addison-Wesley
+        Publishing Company, Boston, 1989. Chapter 6, page 258.
+
+    .. [2] Temme, Nico M. "Asymptotic estimates of Stirling numbers."
+        Studies in Applied Mathematics 89.3 (1993): 233-243.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import stirling2
+    >>> k = np.array([3, -1, 3])
+    >>> n = np.array([10, 10, 9])
+    >>> stirling2(n, k)
+    array([9330.0, 0.0, 3025.0])
+
+    """
+    output_is_scalar = np.isscalar(N) and np.isscalar(K)
+    # make a min-heap of unique (n,k) pairs
+    N, K = asarray(N), asarray(K)
+    if not np.issubdtype(N.dtype, np.integer):
+        raise TypeError("Argument `N` must contain only integers")
+    if not np.issubdtype(K.dtype, np.integer):
+        raise TypeError("Argument `K` must contain only integers")
+    if not exact:
+        # NOTE: here we allow np.uint via casting to double types prior to
+        # passing to private ufunc dispatcher. All dispatched functions
+        # take double type for (n,k) arguments and return double.
+        return _stirling2_inexact(N.astype(float), K.astype(float))
+    nk_pairs = list(
+        set([(n.take(0), k.take(0))
+             for n, k in np.nditer([N, K], ['refs_ok'])])
+    )
+    heapify(nk_pairs)
+    # base mapping for small values
+    snsk_vals = defaultdict(int)
+    for pair in [(0, 0), (1, 1), (2, 1), (2, 2)]:
+        snsk_vals[pair] = 1
+    # for each pair in the min-heap, calculate the value, store for later
+    n_old, n_row = 2, [0, 1, 1]
+    while nk_pairs:
+        n, k = heappop(nk_pairs)
+        if n < 2 or k > n or k <= 0:
+            continue
+        elif k == n or k == 1:
+            snsk_vals[(n, k)] = 1
+            continue
+        elif n != n_old:
+            num_iters = n - n_old
+            while num_iters > 0:
+                n_row.append(1)
+                # traverse from back to remove second row
+                for j in range(len(n_row)-2, 1, -1):
+                    n_row[j] = n_row[j]*j + n_row[j-1]
+                num_iters -= 1
+            snsk_vals[(n, k)] = n_row[k]
+        else:
+            snsk_vals[(n, k)] = n_row[k]
+        n_old, n_row = n, n_row
+    out_types = [object, object, object] if exact else [float, float, float]
+    # for each pair in the map, fetch the value, and populate the array
+    it = np.nditer(
+        [N, K, None],
+        ['buffered', 'refs_ok'],
+        [['readonly'], ['readonly'], ['writeonly', 'allocate']],
+        op_dtypes=out_types,
+    )
+    with it:
+        while not it.finished:
+            it[2] = snsk_vals[(int(it[0]), int(it[1]))]
+            it.iternext()
+        output = it.operands[2]
+        # If N and K were both scalars, convert output to scalar.
+        if output_is_scalar:
+            output = output.take(0)
+    return output
+
+
+def zeta(x, q=None, out=None):
+    r"""
+    Riemann or Hurwitz zeta function.
+
+    Parameters
+    ----------
+    x : array_like of float or complex.
+        Input data
+    q : array_like of float, optional
+        Input data, must be real.  Defaults to Riemann zeta. When `q` is
+        ``None``, complex inputs `x` are supported. If `q` is not ``None``,
+        then currently only real inputs `x` with ``x >= 1`` are supported,
+        even when ``q = 1.0`` (corresponding to the Riemann zeta function).
+
+    out : ndarray, optional
+        Output array for the computed values.
+
+    Returns
+    -------
+    out : array_like
+        Values of zeta(x).
+
+    See Also
+    --------
+    zetac
+
+    Notes
+    -----
+    The two-argument version is the Hurwitz zeta function
+
+    .. math::
+
+        \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x};
+
+    see [dlmf]_ for details. The Riemann zeta function corresponds to
+    the case when ``q = 1``.
+
+    For complex inputs with ``q = None``, points with
+    ``abs(z.imag) > 1e9`` and ``0 <= abs(z.real) < 2.5`` are currently not
+    supported due to slow convergence causing excessive runtime.
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/25.11#i
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import zeta, polygamma, factorial
+
+    Some specific values:
+
+    >>> zeta(2), np.pi**2/6
+    (1.6449340668482266, 1.6449340668482264)
+
+    >>> zeta(4), np.pi**4/90
+    (1.0823232337111381, 1.082323233711138)
+
+    First nontrivial zero:
+
+    >>> zeta(0.5 + 14.134725141734695j)
+    0 + 0j
+
+    Relation to the `polygamma` function:
+
+    >>> m = 3
+    >>> x = 1.25
+    >>> polygamma(m, x)
+    array(2.782144009188397)
+    >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x)
+    2.7821440091883969
+
+    """
+    if q is None:
+        return _ufuncs._riemann_zeta(x, out)
+    else:
+        return _ufuncs._zeta(x, q, out)
+
+
+def softplus(x, **kwargs):
+    r"""
+    Compute the softplus function element-wise.
+
+    The softplus function is defined as: ``softplus(x) = log(1 + exp(x))``.
+    It is a smooth approximation of the rectifier function (ReLU).
+
+    Parameters
+    ----------
+    x : array_like
+        Input value.
+    **kwargs
+        For other keyword-only arguments, see the
+        `ufunc docs `_.
+
+    Returns
+    -------
+    softplus : ndarray
+        Logarithm of ``exp(0) + exp(x)``.
+
+    Examples
+    --------
+    >>> from scipy import special
+
+    >>> special.softplus(0)
+    0.6931471805599453
+
+    >>> special.softplus([-1, 0, 1])
+    array([0.31326169, 0.69314718, 1.31326169])
+    """
+    return np.logaddexp(0, x, **kwargs)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e0598ff2d395e08055065c94341de42ce84c5651
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py b/venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b1ce34aa58054be13edfd5d87f2059e8a0d9224
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py
@@ -0,0 +1,214 @@
+import numpy as np
+
+from ._ufuncs import _ellip_harm
+from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm
+
+
+def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
+    r"""
+    Ellipsoidal harmonic functions E^p_n(l)
+
+    These are also known as Lame functions of the first kind, and are
+    solutions to the Lame equation:
+
+    .. math:: (s^2 - h^2)(s^2 - k^2)E''(s)
+              + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
+
+    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
+    returned) corresponding to the solutions.
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree
+    s : float
+        Coordinate
+    p : int
+        Order, can range between [1,2n+1]
+    signm : {1, -1}, optional
+        Sign of prefactor of functions. Can be +/-1. See Notes.
+    signn : {1, -1}, optional
+        Sign of prefactor of functions. Can be +/-1. See Notes.
+
+    Returns
+    -------
+    E : float
+        the harmonic :math:`E^p_n(s)`
+
+    See Also
+    --------
+    ellip_harm_2, ellip_normal
+
+    Notes
+    -----
+    The geometric interpretation of the ellipsoidal functions is
+    explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
+    sign of prefactors for functions according to their type::
+
+        K : +1
+        L : signm
+        M : signn
+        N : signm*signn
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Digital Library of Mathematical Functions 29.12
+       https://dlmf.nist.gov/29.12
+    .. [2] Bardhan and Knepley, "Computational science and
+       re-discovery: open-source implementations of
+       ellipsoidal harmonics for problems in potential theory",
+       Comput. Sci. Disc. 5, 014006 (2012)
+       :doi:`10.1088/1749-4699/5/1/014006`.
+    .. [3] David J.and Dechambre P, "Computation of Ellipsoidal
+       Gravity Field Harmonics for small solar system bodies"
+       pp. 30-36, 2000
+    .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
+       pp. 418, 2012
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_harm
+    >>> w = ellip_harm(5,8,1,1,2.5)
+    >>> w
+    2.5
+
+    Check that the functions indeed are solutions to the Lame equation:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> def eigenvalue(f, df, ddf):
+    ...     r = (((s**2 - h**2) * (s**2 - k**2) * ddf
+    ...           + s * (2*s**2 - h**2 - k**2) * df
+    ...           - n * (n + 1)*s**2*f) / f)
+    ...     return -r.mean(), r.std()
+    >>> s = np.linspace(0.1, 10, 200)
+    >>> k, h, n, p = 8.0, 2.2, 3, 2
+    >>> E = ellip_harm(h**2, k**2, n, p, s)
+    >>> E_spl = UnivariateSpline(s, E)
+    >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
+    >>> a, a_err
+    (583.44366156701483, 6.4580890640310646e-11)
+
+    """  # noqa: E501
+    return _ellip_harm(h2, k2, n, p, s, signm, signn)
+
+
+_ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d')
+
+
+def ellip_harm_2(h2, k2, n, p, s):
+    r"""
+    Ellipsoidal harmonic functions F^p_n(l)
+
+    These are also known as Lame functions of the second kind, and are
+    solutions to the Lame equation:
+
+    .. math:: (s^2 - h^2)(s^2 - k^2)F''(s)
+              + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0
+
+    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
+    returned) corresponding to the solutions.
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree.
+    p : int
+        Order, can range between [1,2n+1].
+    s : float
+        Coordinate
+
+    Returns
+    -------
+    F : float
+        The harmonic :math:`F^p_n(s)`
+
+    See Also
+    --------
+    ellip_harm, ellip_normal
+
+    Notes
+    -----
+    Lame functions of the second kind are related to the functions of the first kind:
+
+    .. math::
+
+       F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}
+       \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}
+
+    .. versionadded:: 0.15.0
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_harm_2
+    >>> w = ellip_harm_2(5,8,2,1,10)
+    >>> w
+    0.00108056853382
+
+    """
+    with np.errstate(all='ignore'):
+        return _ellip_harm_2_vec(h2, k2, n, p, s)
+
+
+def _ellip_normal_vec(h2, k2, n, p):
+    return _ellipsoid_norm(h2, k2, n, p)
+
+
+_ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d')
+
+
+def ellip_normal(h2, k2, n, p):
+    r"""
+    Ellipsoidal harmonic normalization constants gamma^p_n
+
+    The normalization constant is defined as
+
+    .. math::
+
+       \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy
+       \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)}
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree.
+    p : int
+        Order, can range between [1,2n+1].
+
+    Returns
+    -------
+    gamma : float
+        The normalization constant :math:`\gamma^p_n`
+
+    See Also
+    --------
+    ellip_harm, ellip_harm_2
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_normal
+    >>> w = ellip_normal(5,8,3,7)
+    >>> w
+    1723.38796997
+
+    """
+    with np.errstate(all='ignore'):
+        return _ellip_normal_vec(h2, k2, n, p)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_input_validation.py b/venv/lib/python3.10/site-packages/scipy/special/_input_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5b7fe36df87617bf91655623ee0076c37a4d08a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_input_validation.py
@@ -0,0 +1,17 @@
+import math
+import operator
+
+def _nonneg_int_or_fail(n, var_name, strict=True):
+    try:
+        if strict:
+            # Raises an exception if float
+            n = operator.index(n)
+        elif n == math.floor(n):
+            n = int(n)
+        else:
+            raise ValueError()
+        if n < 0:
+            raise ValueError()
+    except (ValueError, TypeError) as err:
+        raise err.__class__(f"{var_name} must be a non-negative integer") from err
+    return n
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_lambertw.py b/venv/lib/python3.10/site-packages/scipy/special/_lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..f758c7c21fdddc0ec1b84727d90c6de7f34a094e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_lambertw.py
@@ -0,0 +1,149 @@
+from ._ufuncs import _lambertw
+
+import numpy as np
+
+
+def lambertw(z, k=0, tol=1e-8):
+    r"""
+    lambertw(z, k=0, tol=1e-8)
+
+    Lambert W function.
+
+    The Lambert W function `W(z)` is defined as the inverse function
+    of ``w * exp(w)``. In other words, the value of ``W(z)`` is
+    such that ``z = W(z) * exp(W(z))`` for any complex number
+    ``z``.
+
+    The Lambert W function is a multivalued function with infinitely
+    many branches. Each branch gives a separate solution of the
+    equation ``z = w exp(w)``. Here, the branches are indexed by the
+    integer `k`.
+
+    Parameters
+    ----------
+    z : array_like
+        Input argument.
+    k : int, optional
+        Branch index.
+    tol : float, optional
+        Evaluation tolerance.
+
+    Returns
+    -------
+    w : array
+        `w` will have the same shape as `z`.
+
+    See Also
+    --------
+    wrightomega : the Wright Omega function
+
+    Notes
+    -----
+    All branches are supported by `lambertw`:
+
+    * ``lambertw(z)`` gives the principal solution (branch 0)
+    * ``lambertw(z, k)`` gives the solution on branch `k`
+
+    The Lambert W function has two partially real branches: the
+    principal branch (`k = 0`) is real for real ``z > -1/e``, and the
+    ``k = -1`` branch is real for ``-1/e < z < 0``. All branches except
+    ``k = 0`` have a logarithmic singularity at ``z = 0``.
+
+    **Possible issues**
+
+    The evaluation can become inaccurate very close to the branch point
+    at ``-1/e``. In some corner cases, `lambertw` might currently
+    fail to converge, or can end up on the wrong branch.
+
+    **Algorithm**
+
+    Halley's iteration is used to invert ``w * exp(w)``, using a first-order
+    asymptotic approximation (O(log(w)) or `O(w)`) as the initial estimate.
+
+    The definition, implementation and choice of branches is based on [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
+    .. [2] Corless et al, "On the Lambert W function", Adv. Comp. Math. 5
+       (1996) 329-359.
+       https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
+
+    Examples
+    --------
+    The Lambert W function is the inverse of ``w exp(w)``:
+
+    >>> import numpy as np
+    >>> from scipy.special import lambertw
+    >>> w = lambertw(1)
+    >>> w
+    (0.56714329040978384+0j)
+    >>> w * np.exp(w)
+    (1.0+0j)
+
+    Any branch gives a valid inverse:
+
+    >>> w = lambertw(1, k=3)
+    >>> w
+    (-2.8535817554090377+17.113535539412148j)
+    >>> w*np.exp(w)
+    (1.0000000000000002+1.609823385706477e-15j)
+
+    **Applications to equation-solving**
+
+    The Lambert W function may be used to solve various kinds of
+    equations.  We give two examples here.
+
+    First, the function can be used to solve implicit equations of the
+    form
+
+        :math:`x = a + b e^{c x}`
+
+    for :math:`x`.  We assume :math:`c` is not zero.  After a little
+    algebra, the equation may be written
+
+        :math:`z e^z = -b c e^{a c}`
+
+    where :math:`z = c (a - x)`.  :math:`z` may then be expressed using
+    the Lambert W function
+
+        :math:`z = W(-b c e^{a c})`
+
+    giving
+
+        :math:`x = a - W(-b c e^{a c})/c`
+
+    For example,
+
+    >>> a = 3
+    >>> b = 2
+    >>> c = -0.5
+
+    The solution to :math:`x = a + b e^{c x}` is:
+
+    >>> x = a - lambertw(-b*c*np.exp(a*c))/c
+    >>> x
+    (3.3707498368978794+0j)
+
+    Verify that it solves the equation:
+
+    >>> a + b*np.exp(c*x)
+    (3.37074983689788+0j)
+
+    The Lambert W function may also be used find the value of the infinite
+    power tower :math:`z^{z^{z^{\ldots}}}`:
+
+    >>> def tower(z, n):
+    ...     if n == 0:
+    ...         return z
+    ...     return z ** tower(z, n-1)
+    ...
+    >>> tower(0.5, 100)
+    0.641185744504986
+    >>> -lambertw(-np.log(0.5)) / np.log(0.5)
+    (0.64118574450498589+0j)
+    """
+    # TODO: special expert should inspect this
+    # interception; better place to do it?
+    k = np.asarray(k, dtype=np.dtype("long"))
+    return _lambertw(z, k, tol)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py b/venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b0da953464e8d92925ebdaba79ce062c38fc7e5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py
@@ -0,0 +1,417 @@
+import math
+import numpy as np
+from scipy._lib._util import _asarray_validated
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_broadcast_promote,
+    xp_copy,
+    xp_float_to_complex,
+    is_complex,
+)
+from scipy._lib import array_api_extra as xpx
+
+__all__ = ["logsumexp", "softmax", "log_softmax"]
+
+
+def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
+    """Compute the log of the sum of exponentials of input elements.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : None or int or tuple of ints, optional
+        Axis or axes over which the sum is taken. By default `axis` is None,
+        and all elements are summed.
+
+        .. versionadded:: 0.11.0
+    b : array-like, optional
+        Scaling factor for exp(`a`) must be of the same shape as `a` or
+        broadcastable to `a`. These values may be negative in order to
+        implement subtraction.
+
+        .. versionadded:: 0.12.0
+    keepdims : bool, optional
+        If this is set to True, the axes which are reduced are left in the
+        result as dimensions with size one. With this option, the result
+        will broadcast correctly against the original array.
+
+        .. versionadded:: 0.15.0
+    return_sign : bool, optional
+        If this is set to True, the result will be a pair containing sign
+        information; if False, results that are negative will be returned
+        as NaN. Default is False (no sign information).
+
+        .. versionadded:: 0.16.0
+
+    Returns
+    -------
+    res : ndarray
+        The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically
+        more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``
+        is returned. If ``return_sign`` is True, ``res`` contains the log of
+        the absolute value of the argument.
+    sgn : ndarray
+        If ``return_sign`` is True, this will be an array of floating-point
+        numbers matching res containing +1, 0, -1 (for real-valued inputs)
+        or a complex phase (for complex inputs). This gives the sign of the
+        argument of the logarithm in ``res``.
+        If ``return_sign`` is False, only one result is returned.
+
+    See Also
+    --------
+    numpy.logaddexp, numpy.logaddexp2
+
+    Notes
+    -----
+    NumPy has a logaddexp function which is very similar to `logsumexp`, but
+    only handles two arguments. `logaddexp.reduce` is similar to this
+    function, but may be less stable.
+
+    The logarithm is a multivalued function: for each :math:`x` there is an
+    infinite number of :math:`z` such that :math:`exp(z) = x`. The convention
+    is to return the :math:`z` whose imaginary part lies in :math:`(-pi, pi]`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import logsumexp
+    >>> a = np.arange(10)
+    >>> logsumexp(a)
+    9.4586297444267107
+    >>> np.log(np.sum(np.exp(a)))
+    9.4586297444267107
+
+    With weights
+
+    >>> a = np.arange(10)
+    >>> b = np.arange(10, 0, -1)
+    >>> logsumexp(a, b=b)
+    9.9170178533034665
+    >>> np.log(np.sum(b*np.exp(a)))
+    9.9170178533034647
+
+    Returning a sign flag
+
+    >>> logsumexp([1,2],b=[1,-1],return_sign=True)
+    (1.5413248546129181, -1.0)
+
+    Notice that `logsumexp` does not directly support masked arrays. To use it
+    on a masked array, convert the mask into zero weights:
+
+    >>> a = np.ma.array([np.log(2), 2, np.log(3)],
+    ...                  mask=[False, True, False])
+    >>> b = (~a.mask).astype(int)
+    >>> logsumexp(a.data, b=b), np.log(5)
+    1.6094379124341005, 1.6094379124341005
+
+    """
+    xp = array_namespace(a, b)
+    a, b = xp_broadcast_promote(a, b, ensure_writeable=True, force_floating=True, xp=xp)
+    a = xpx.atleast_nd(a, ndim=1, xp=xp)
+    b = xpx.atleast_nd(b, ndim=1, xp=xp) if b is not None else b
+    axis = tuple(range(a.ndim)) if axis is None else axis
+
+    if xp_size(a) != 0:
+        with np.errstate(divide='ignore', invalid='ignore'):  # log of zero is OK
+            out, sgn = _logsumexp(a, b, axis=axis, return_sign=return_sign, xp=xp)
+    else:
+        shape = np.asarray(a.shape)  # NumPy is convenient for shape manipulation
+        shape[axis] = 1
+        out = xp.full(tuple(shape), -xp.inf, dtype=a.dtype)
+        sgn = xp.sign(out)
+
+    if xp.isdtype(out.dtype, 'complex floating'):
+        if return_sign:
+            real = xp.real(sgn)
+            imag = xp_float_to_complex(_wrap_radians(xp.imag(sgn), xp))
+            sgn = real + imag*1j
+        else:
+            real = xp.real(out)
+            imag = xp_float_to_complex(_wrap_radians(xp.imag(out), xp))
+            out = real + imag*1j
+
+    # Deal with shape details - reducing dimensions and convert 0-D to scalar for NumPy
+    out = xp.squeeze(out, axis=axis) if not keepdims else out
+    sgn = xp.squeeze(sgn, axis=axis) if (sgn is not None and not keepdims) else sgn
+    out = out[()] if out.ndim == 0 else out
+    sgn = sgn[()] if (sgn is not None and sgn.ndim == 0) else sgn
+
+    return (out, sgn) if return_sign else out
+
+
+def _wrap_radians(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    # Wrap radians to (-pi, pi] interval
+    out = -((-x + math.pi) % (2 * math.pi) - math.pi)
+    # preserve relative precision
+    no_wrap = xp.abs(x) < xp.pi
+    out[no_wrap] = x[no_wrap]
+    return out
+
+
+def _elements_and_indices_with_max_real(a, axis=-1, xp=None):
+    # This is an array-API compatible `max` function that works something
+    # like `np.max` for complex input. The important part is that it finds
+    # the element with maximum real part. When there are multiple complex values
+    # with this real part, it doesn't matter which we choose.
+    # We could use `argmax` on real component, but array API doesn't yet have
+    # `take_along_axis`, and even if it did, we would have problems with axis tuples.
+    # Feel free to rewrite! It's ugly, but it's not the purpose of the PR, and
+    # it gets the job done.
+    xp = array_namespace(a) if xp is None else xp
+
+    if xp.isdtype(a.dtype, "complex floating"):
+        # select all elements with max real part.
+        real_a = xp.real(a)
+        max = xp.max(real_a, axis=axis, keepdims=True)
+        mask = real_a == max
+
+        # Of those, choose one arbitrarily. This is a reasonably
+        # simple, array-API compatible way of doing so that doesn't
+        # have a problem with `axis` being a tuple or None.
+        i = xp.reshape(xp.arange(xp_size(a)), a.shape)
+        i[~mask] = -1
+        max_i = xp.max(i, axis=axis, keepdims=True)
+        mask = i == max_i
+        a = xp_copy(a)
+        a[~mask] = 0
+        max = xp.sum(a, axis=axis, dtype=a.dtype, keepdims=True)
+    else:
+        max = xp.max(a, axis=axis, keepdims=True)
+        mask = a == max
+
+    return xp.asarray(max), xp.asarray(mask)
+
+
+def _sign(x, xp):
+    return x / xp.where(x == 0, xp.asarray(1, dtype=x.dtype), xp.abs(x))
+
+
+def _logsumexp(a, b, axis, return_sign, xp):
+
+    # This has been around for about a decade, so let's consider it a feature:
+    # Even if element of `a` is infinite or NaN, it adds nothing to the sum if
+    # the corresponding weight is zero.
+    if b is not None:
+        a[b == 0] = -xp.inf
+
+    # Find element with maximum real part, since this is what affects the magnitude
+    # of the exponential. Possible enhancement: include log of `b` magnitude in `a`.
+    a_max, i_max = _elements_and_indices_with_max_real(a, axis=axis, xp=xp)
+
+    # for precision, these terms are separated out of the main sum.
+    a[i_max] = -xp.inf
+    i_max_dt = xp.astype(i_max, a.dtype)
+    # This is an inefficient way of getting `m` because it is the sum of a sparse
+    # array; however, this is the simplest way I can think of to get the right shape.
+    m = (xp.sum(i_max_dt, axis=axis, keepdims=True, dtype=a.dtype) if b is None
+         else xp.sum(b * i_max_dt, axis=axis, keepdims=True, dtype=a.dtype))
+
+    # Arithmetic between infinities will introduce NaNs.
+    # `+ a_max` at the end naturally corrects for removing them here.
+    shift = xp.where(xp.isfinite(a_max), a_max, xp.asarray(0, dtype=a_max.dtype))
+
+    # Shift, exponentiate, scale, and sum
+    exp = b * xp.exp(a - shift) if b is not None else xp.exp(a - shift)
+    s = xp.sum(exp, axis=axis, keepdims=True, dtype=exp.dtype)
+    s = xp.where(s == 0, s, s/m)
+
+    # Separate sign/magnitude information
+    # Originally, this was only performed if `return_sign=True`.
+    # However, this is also needed if any elements of `m < 0` or `s < -1`.
+    # An improvement would be to perform the calculations only on these entries.
+
+    # Use the numpy>=2.0 convention for sign.
+    # When all array libraries agree, this can become sng = xp.sign(s).
+    sgn = _sign(s + 1, xp=xp) * _sign(m, xp=xp)
+
+    if xp.isdtype(s.dtype, "real floating"):
+        # The log functions need positive arguments
+        s = xp.where(s < -1, -s - 2, s)
+        m = xp.abs(m)
+    else:
+        # `a_max` can have a sign component for complex input
+        sgn = sgn * xp.exp(xp.imag(a_max) * xp.asarray(1.0j, dtype=a_max.dtype))
+
+    # Take log and undo shift
+    out = xp.log1p(s) + xp.log(m) + a_max
+
+    if return_sign:
+        if is_complex(out, xp):
+            out = xp.real(out)
+    elif xp.isdtype(out.dtype, 'real floating'):
+        out[sgn < 0] = xp.nan
+
+    return out, sgn
+
+
+def softmax(x, axis=None):
+    r"""Compute the softmax function.
+
+    The softmax function transforms each element of a collection by
+    computing the exponential of each element divided by the sum of the
+    exponentials of all the elements. That is, if `x` is a one-dimensional
+    numpy array::
+
+        softmax(x) = np.exp(x)/sum(np.exp(x))
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axis : int or tuple of ints, optional
+        Axis to compute values along. Default is None and softmax will be
+        computed over the entire array `x`.
+
+    Returns
+    -------
+    s : ndarray
+        An array the same shape as `x`. The result will sum to 1 along the
+        specified axis.
+
+    Notes
+    -----
+    The formula for the softmax function :math:`\sigma(x)` for a vector
+    :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is
+
+    .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}
+
+    The `softmax` function is the gradient of `logsumexp`.
+
+    The implementation uses shifting to avoid overflow. See [1]_ for more
+    details.
+
+    .. versionadded:: 1.2.0
+
+    References
+    ----------
+    .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the
+       log-sum-exp and softmax functions", IMA Journal of Numerical Analysis,
+       Vol.41(4), :doi:`10.1093/imanum/draa038`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import softmax
+    >>> np.set_printoptions(precision=5)
+
+    >>> x = np.array([[1, 0.5, 0.2, 3],
+    ...               [1,  -1,   7, 3],
+    ...               [2,  12,  13, 3]])
+    ...
+
+    Compute the softmax transformation over the entire array.
+
+    >>> m = softmax(x)
+    >>> m
+    array([[  4.48309e-06,   2.71913e-06,   2.01438e-06,   3.31258e-05],
+           [  4.48309e-06,   6.06720e-07,   1.80861e-03,   3.31258e-05],
+           [  1.21863e-05,   2.68421e-01,   7.29644e-01,   3.31258e-05]])
+
+    >>> m.sum()
+    1.0
+
+    Compute the softmax transformation along the first axis (i.e., the
+    columns).
+
+    >>> m = softmax(x, axis=0)
+
+    >>> m
+    array([[  2.11942e-01,   1.01300e-05,   2.75394e-06,   3.33333e-01],
+           [  2.11942e-01,   2.26030e-06,   2.47262e-03,   3.33333e-01],
+           [  5.76117e-01,   9.99988e-01,   9.97525e-01,   3.33333e-01]])
+
+    >>> m.sum(axis=0)
+    array([ 1.,  1.,  1.,  1.])
+
+    Compute the softmax transformation along the second axis (i.e., the rows).
+
+    >>> m = softmax(x, axis=1)
+    >>> m
+    array([[  1.05877e-01,   6.42177e-02,   4.75736e-02,   7.82332e-01],
+           [  2.42746e-03,   3.28521e-04,   9.79307e-01,   1.79366e-02],
+           [  1.22094e-05,   2.68929e-01,   7.31025e-01,   3.31885e-05]])
+
+    >>> m.sum(axis=1)
+    array([ 1.,  1.,  1.])
+
+    """
+    x = _asarray_validated(x, check_finite=False)
+    x_max = np.amax(x, axis=axis, keepdims=True)
+    exp_x_shifted = np.exp(x - x_max)
+    return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
+
+
+def log_softmax(x, axis=None):
+    r"""Compute the logarithm of the softmax function.
+
+    In principle::
+
+        log_softmax(x) = log(softmax(x))
+
+    but using a more accurate implementation.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axis : int or tuple of ints, optional
+        Axis to compute values along. Default is None and softmax will be
+        computed over the entire array `x`.
+
+    Returns
+    -------
+    s : ndarray or scalar
+        An array with the same shape as `x`. Exponential of the result will
+        sum to 1 along the specified axis. If `x` is a scalar, a scalar is
+        returned.
+
+    Notes
+    -----
+    `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that
+    make `softmax` saturate (see examples below).
+
+    .. versionadded:: 1.5.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import log_softmax
+    >>> from scipy.special import softmax
+    >>> np.set_printoptions(precision=5)
+
+    >>> x = np.array([1000.0, 1.0])
+
+    >>> y = log_softmax(x)
+    >>> y
+    array([   0., -999.])
+
+    >>> with np.errstate(divide='ignore'):
+    ...   y = np.log(softmax(x))
+    ...
+    >>> y
+    array([  0., -inf])
+
+    """
+
+    x = _asarray_validated(x, check_finite=False)
+
+    x_max = np.amax(x, axis=axis, keepdims=True)
+
+    if x_max.ndim > 0:
+        x_max[~np.isfinite(x_max)] = 0
+    elif not np.isfinite(x_max):
+        x_max = 0
+
+    tmp = x - x_max
+    exp_tmp = np.exp(tmp)
+
+    # suppress warnings about log of zero
+    with np.errstate(divide='ignore'):
+        s = np.sum(exp_tmp, axis=axis, keepdims=True)
+        out = np.log(s)
+
+    out = tmp - out
+    return out
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py b/venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e519093dface79e21f16d7063541ad107f5ca96
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py
@@ -0,0 +1,453 @@
+import os
+import sys
+import time
+from itertools import zip_longest
+
+import numpy as np
+from numpy.testing import assert_
+import pytest
+
+from scipy.special._testutils import assert_func_equal
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+# ------------------------------------------------------------------------------
+# Machinery for systematic tests with mpmath
+# ------------------------------------------------------------------------------
+
+class Arg:
+    """Generate a set of numbers on the real axis, concentrating on
+    'interesting' regions and covering all orders of magnitude.
+
+    """
+
+    def __init__(self, a=-np.inf, b=np.inf, inclusive_a=True, inclusive_b=True):
+        if a > b:
+            raise ValueError("a should be less than or equal to b")
+        if a == -np.inf:
+            a = -0.5*np.finfo(float).max
+        if b == np.inf:
+            b = 0.5*np.finfo(float).max
+        self.a, self.b = a, b
+
+        self.inclusive_a, self.inclusive_b = inclusive_a, inclusive_b
+
+    def _positive_values(self, a, b, n):
+        if a < 0:
+            raise ValueError("a should be positive")
+
+        # Try to put half of the points into a linspace between a and
+        # 10 the other half in a logspace.
+        if n % 2 == 0:
+            nlogpts = n//2
+            nlinpts = nlogpts
+        else:
+            nlogpts = n//2
+            nlinpts = nlogpts + 1
+
+        if a >= 10:
+            # Outside of linspace range; just return a logspace.
+            pts = np.logspace(np.log10(a), np.log10(b), n)
+        elif a > 0 and b < 10:
+            # Outside of logspace range; just return a linspace
+            pts = np.linspace(a, b, n)
+        elif a > 0:
+            # Linspace between a and 10 and a logspace between 10 and
+            # b.
+            linpts = np.linspace(a, 10, nlinpts, endpoint=False)
+            logpts = np.logspace(1, np.log10(b), nlogpts)
+            pts = np.hstack((linpts, logpts))
+        elif a == 0 and b <= 10:
+            # Linspace between 0 and b and a logspace between 0 and
+            # the smallest positive point of the linspace
+            linpts = np.linspace(0, b, nlinpts)
+            if linpts.size > 1:
+                right = np.log10(linpts[1])
+            else:
+                right = -30
+            logpts = np.logspace(-30, right, nlogpts, endpoint=False)
+            pts = np.hstack((logpts, linpts))
+        else:
+            # Linspace between 0 and 10, logspace between 0 and the
+            # smallest positive point of the linspace, and a logspace
+            # between 10 and b.
+            if nlogpts % 2 == 0:
+                nlogpts1 = nlogpts//2
+                nlogpts2 = nlogpts1
+            else:
+                nlogpts1 = nlogpts//2
+                nlogpts2 = nlogpts1 + 1
+            linpts = np.linspace(0, 10, nlinpts, endpoint=False)
+            if linpts.size > 1:
+                right = np.log10(linpts[1])
+            else:
+                right = -30
+            logpts1 = np.logspace(-30, right, nlogpts1, endpoint=False)
+            logpts2 = np.logspace(1, np.log10(b), nlogpts2)
+            pts = np.hstack((logpts1, linpts, logpts2))
+
+        return np.sort(pts)
+
+    def values(self, n):
+        """Return an array containing n numbers."""
+        a, b = self.a, self.b
+        if a == b:
+            return np.zeros(n)
+
+        if not self.inclusive_a:
+            n += 1
+        if not self.inclusive_b:
+            n += 1
+
+        if n % 2 == 0:
+            n1 = n//2
+            n2 = n1
+        else:
+            n1 = n//2
+            n2 = n1 + 1
+
+        if a >= 0:
+            pospts = self._positive_values(a, b, n)
+            negpts = []
+        elif b <= 0:
+            pospts = []
+            negpts = -self._positive_values(-b, -a, n)
+        else:
+            pospts = self._positive_values(0, b, n1)
+            negpts = -self._positive_values(0, -a, n2 + 1)
+            # Don't want to get zero twice
+            negpts = negpts[1:]
+        pts = np.hstack((negpts[::-1], pospts))
+
+        if not self.inclusive_a:
+            pts = pts[1:]
+        if not self.inclusive_b:
+            pts = pts[:-1]
+        return pts
+
+
+class FixedArg:
+    def __init__(self, values):
+        self._values = np.asarray(values)
+
+    def values(self, n):
+        return self._values
+
+
+class ComplexArg:
+    def __init__(self, a=complex(-np.inf, -np.inf), b=complex(np.inf, np.inf)):
+        self.real = Arg(a.real, b.real)
+        self.imag = Arg(a.imag, b.imag)
+
+    def values(self, n):
+        m = int(np.floor(np.sqrt(n)))
+        x = self.real.values(m)
+        y = self.imag.values(m + 1)
+        return (x[:,None] + 1j*y[None,:]).ravel()
+
+
+class IntArg:
+    def __init__(self, a=-1000, b=1000):
+        self.a = a
+        self.b = b
+
+    def values(self, n):
+        v1 = Arg(self.a, self.b).values(max(1 + n//2, n-5)).astype(int)
+        v2 = np.arange(-5, 5)
+        v = np.unique(np.r_[v1, v2])
+        v = v[(v >= self.a) & (v < self.b)]
+        return v
+
+
+def get_args(argspec, n):
+    if isinstance(argspec, np.ndarray):
+        args = argspec.copy()
+    else:
+        nargs = len(argspec)
+        ms = np.asarray(
+            [1.5 if isinstance(spec, ComplexArg) else 1.0 for spec in argspec]
+        )
+        ms = (n**(ms/sum(ms))).astype(int) + 1
+
+        args = [spec.values(m) for spec, m in zip(argspec, ms)]
+        args = np.array(np.broadcast_arrays(*np.ix_(*args))).reshape(nargs, -1).T
+
+    return args
+
+
+class MpmathData:
+    def __init__(self, scipy_func, mpmath_func, arg_spec, name=None,
+                 dps=None, prec=None, n=None, rtol=1e-7, atol=1e-300,
+                 ignore_inf_sign=False, distinguish_nan_and_inf=True,
+                 nan_ok=True, param_filter=None):
+
+        # mpmath tests are really slow (see gh-6989).  Use a small number of
+        # points by default, increase back to 5000 (old default) if XSLOW is
+        # set
+        if n is None:
+            try:
+                is_xslow = int(os.environ.get('SCIPY_XSLOW', '0'))
+            except ValueError:
+                is_xslow = False
+
+            n = 5000 if is_xslow else 500
+
+        self.scipy_func = scipy_func
+        self.mpmath_func = mpmath_func
+        self.arg_spec = arg_spec
+        self.dps = dps
+        self.prec = prec
+        self.n = n
+        self.rtol = rtol
+        self.atol = atol
+        self.ignore_inf_sign = ignore_inf_sign
+        self.nan_ok = nan_ok
+        if isinstance(self.arg_spec, np.ndarray):
+            self.is_complex = np.issubdtype(self.arg_spec.dtype, np.complexfloating)
+        else:
+            self.is_complex = any(
+                [isinstance(arg, ComplexArg) for arg in self.arg_spec]
+            )
+        self.ignore_inf_sign = ignore_inf_sign
+        self.distinguish_nan_and_inf = distinguish_nan_and_inf
+        if not name or name == '':
+            name = getattr(scipy_func, '__name__', None)
+        if not name or name == '':
+            name = getattr(mpmath_func, '__name__', None)
+        self.name = name
+        self.param_filter = param_filter
+
+    def check(self):
+        np.random.seed(1234)
+
+        # Generate values for the arguments
+        argarr = get_args(self.arg_spec, self.n)
+
+        # Check
+        old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+        try:
+            if self.dps is not None:
+                dps_list = [self.dps]
+            else:
+                dps_list = [20]
+            if self.prec is not None:
+                mpmath.mp.prec = self.prec
+
+            # Proper casting of mpmath input and output types. Using
+            # native mpmath types as inputs gives improved precision
+            # in some cases.
+            if np.issubdtype(argarr.dtype, np.complexfloating):
+                pytype = mpc2complex
+
+                def mptype(x):
+                    return mpmath.mpc(complex(x))
+            else:
+                def mptype(x):
+                    return mpmath.mpf(float(x))
+
+                def pytype(x):
+                    if abs(x.imag) > 1e-16*(1 + abs(x.real)):
+                        return np.nan
+                    else:
+                        return mpf2float(x.real)
+
+            # Try out different dps until one (or none) works
+            for j, dps in enumerate(dps_list):
+                mpmath.mp.dps = dps
+
+                try:
+                    assert_func_equal(
+                        self.scipy_func,
+                        lambda *a: pytype(self.mpmath_func(*map(mptype, a))),
+                        argarr,
+                        vectorized=False,
+                        rtol=self.rtol,
+                        atol=self.atol,
+                        ignore_inf_sign=self.ignore_inf_sign,
+                        distinguish_nan_and_inf=self.distinguish_nan_and_inf,
+                        nan_ok=self.nan_ok,
+                        param_filter=self.param_filter
+                    )
+                    break
+                except AssertionError:
+                    if j >= len(dps_list)-1:
+                        # reraise the Exception
+                        tp, value, tb = sys.exc_info()
+                        if value.__traceback__ is not tb:
+                            raise value.with_traceback(tb)
+                        raise value
+        finally:
+            mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+    def __repr__(self):
+        if self.is_complex:
+            return f""
+        else:
+            return f""
+
+
+def assert_mpmath_equal(*a, **kw):
+    d = MpmathData(*a, **kw)
+    d.check()
+
+
+def nonfunctional_tooslow(func):
+    return pytest.mark.skip(
+        reason="    Test not yet functional (too slow), needs more work."
+    )(func)
+
+
+# ------------------------------------------------------------------------------
+# Tools for dealing with mpmath quirks
+# ------------------------------------------------------------------------------
+
+def mpf2float(x):
+    """
+    Convert an mpf to the nearest floating point number. Just using
+    float directly doesn't work because of results like this:
+
+    with mp.workdps(50):
+        float(mpf("0.99999999999999999")) = 0.9999999999999999
+
+    """
+    return float(mpmath.nstr(x, 17, min_fixed=0, max_fixed=0))
+
+
+def mpc2complex(x):
+    return complex(mpf2float(x.real), mpf2float(x.imag))
+
+
+def trace_args(func):
+    def tofloat(x):
+        if isinstance(x, mpmath.mpc):
+            return complex(x)
+        else:
+            return float(x)
+
+    def wrap(*a, **kw):
+        sys.stderr.write(f"{tuple(map(tofloat, a))!r}: ")
+        sys.stderr.flush()
+        try:
+            r = func(*a, **kw)
+            sys.stderr.write(f"-> {r!r}")
+        finally:
+            sys.stderr.write("\n")
+            sys.stderr.flush()
+        return r
+    return wrap
+
+
+try:
+    import signal
+    POSIX = ('setitimer' in dir(signal))
+except ImportError:
+    POSIX = False
+
+
+class TimeoutError(Exception):
+    pass
+
+
+def time_limited(timeout=0.5, return_val=np.nan, use_sigalrm=True):
+    """
+    Decorator for setting a timeout for pure-Python functions.
+
+    If the function does not return within `timeout` seconds, the
+    value `return_val` is returned instead.
+
+    On POSIX this uses SIGALRM by default. On non-POSIX, settrace is
+    used. Do not use this with threads: the SIGALRM implementation
+    does probably not work well. The settrace implementation only
+    traces the current thread.
+
+    The settrace implementation slows down execution speed. Slowdown
+    by a factor around 10 is probably typical.
+    """
+    if POSIX and use_sigalrm:
+        def sigalrm_handler(signum, frame):
+            raise TimeoutError()
+
+        def deco(func):
+            def wrap(*a, **kw):
+                old_handler = signal.signal(signal.SIGALRM, sigalrm_handler)
+                signal.setitimer(signal.ITIMER_REAL, timeout)
+                try:
+                    return func(*a, **kw)
+                except TimeoutError:
+                    return return_val
+                finally:
+                    signal.setitimer(signal.ITIMER_REAL, 0)
+                    signal.signal(signal.SIGALRM, old_handler)
+            return wrap
+    else:
+        def deco(func):
+            def wrap(*a, **kw):
+                start_time = time.time()
+
+                def trace(frame, event, arg):
+                    if time.time() - start_time > timeout:
+                        raise TimeoutError()
+                    return trace
+                sys.settrace(trace)
+                try:
+                    return func(*a, **kw)
+                except TimeoutError:
+                    sys.settrace(None)
+                    return return_val
+                finally:
+                    sys.settrace(None)
+            return wrap
+    return deco
+
+
+def exception_to_nan(func):
+    """Decorate function to return nan if it raises an exception"""
+    def wrap(*a, **kw):
+        try:
+            return func(*a, **kw)
+        except Exception:
+            return np.nan
+    return wrap
+
+
+def inf_to_nan(func):
+    """Decorate function to return nan if it returns inf"""
+    def wrap(*a, **kw):
+        v = func(*a, **kw)
+        if not np.isfinite(v):
+            return np.nan
+        return v
+    return wrap
+
+
+def mp_assert_allclose(res, std, atol=0, rtol=1e-17):
+    """
+    Compare lists of mpmath.mpf's or mpmath.mpc's directly so that it
+    can be done to higher precision than double.
+    """
+    failures = []
+    for k, (resval, stdval) in enumerate(zip_longest(res, std)):
+        if resval is None or stdval is None:
+            raise ValueError('Lengths of inputs res and std are not equal.')
+        if mpmath.fabs(resval - stdval) > atol + rtol*mpmath.fabs(stdval):
+            failures.append((k, resval, stdval))
+
+    nfail = len(failures)
+    if nfail > 0:
+        ndigits = int(abs(np.log10(rtol)))
+        msg = [""]
+        msg.append(f"Bad results ({nfail} out of {k + 1}) for the following points:")
+        for k, resval, stdval in failures:
+            resrep = mpmath.nstr(resval, ndigits, min_fixed=0, max_fixed=0)
+            stdrep = mpmath.nstr(stdval, ndigits, min_fixed=0, max_fixed=0)
+            if stdval == 0:
+                rdiff = "inf"
+            else:
+                rdiff = mpmath.fabs((resval - stdval)/stdval)
+                rdiff = mpmath.nstr(rdiff, 3)
+            msg.append(f"{k}: {resrep} != {stdrep} (rdiff {rdiff})")
+        assert_(False, "\n".join(msg))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py b/venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bb1be9461c629a48841f1d01268e8d11eee230f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py
@@ -0,0 +1,610 @@
+import collections
+import numbers
+import numpy as np
+
+from ._input_validation import _nonneg_int_or_fail
+
+from ._special_ufuncs import (legendre_p, assoc_legendre_p,
+                              sph_legendre_p, sph_harm_y)
+from ._gufuncs import (legendre_p_all, assoc_legendre_p_all,
+                       sph_legendre_p_all, sph_harm_y_all)
+
+__all__ = [
+    "assoc_legendre_p",
+    "assoc_legendre_p_all",
+    "legendre_p",
+    "legendre_p_all",
+    "sph_harm_y",
+    "sph_harm_y_all",
+    "sph_legendre_p",
+    "sph_legendre_p_all",
+]
+
+
+class MultiUFunc:
+    def __init__(self, ufunc_or_ufuncs, doc=None, *,
+                 force_complex_output=False, **default_kwargs):
+        if not isinstance(ufunc_or_ufuncs, np.ufunc):
+            if isinstance(ufunc_or_ufuncs, collections.abc.Mapping):
+                ufuncs_iter = ufunc_or_ufuncs.values()
+            elif isinstance(ufunc_or_ufuncs, collections.abc.Iterable):
+                ufuncs_iter = ufunc_or_ufuncs
+            else:
+                raise ValueError("ufunc_or_ufuncs should be a ufunc or a"
+                                 " ufunc collection")
+
+            # Perform input validation to ensure all ufuncs in ufuncs are
+            # actually ufuncs and all take the same input types.
+            seen_input_types = set()
+            for ufunc in ufuncs_iter:
+                if not isinstance(ufunc, np.ufunc):
+                    raise ValueError("All ufuncs must have type `numpy.ufunc`."
+                                     f" Received {ufunc_or_ufuncs}")
+                seen_input_types.add(frozenset(x.split("->")[0] for x in ufunc.types))
+            if len(seen_input_types) > 1:
+                raise ValueError("All ufuncs must take the same input types.")
+
+        self._ufunc_or_ufuncs = ufunc_or_ufuncs
+        self.__doc = doc
+        self.__force_complex_output = force_complex_output
+        self._default_kwargs = default_kwargs
+        self._resolve_out_shapes = None
+        self._finalize_out = None
+        self._key = None
+        self._ufunc_default_args = lambda *args, **kwargs: ()
+        self._ufunc_default_kwargs = lambda *args, **kwargs: {}
+
+    @property
+    def __doc__(self):
+        return self.__doc
+
+    def _override_key(self, func):
+        """Set `key` method by decorating a function.
+        """
+        self._key = func
+
+    def _override_ufunc_default_args(self, func):
+        self._ufunc_default_args = func
+
+    def _override_ufunc_default_kwargs(self, func):
+        self._ufunc_default_kwargs = func
+
+    def _override_resolve_out_shapes(self, func):
+        """Set `resolve_out_shapes` method by decorating a function."""
+        if func.__doc__ is None:
+            func.__doc__ = \
+                """Resolve to output shapes based on relevant inputs."""
+        func.__name__ = "resolve_out_shapes"
+        self._resolve_out_shapes = func
+
+    def _override_finalize_out(self, func):
+        self._finalize_out = func
+
+    def _resolve_ufunc(self, **kwargs):
+        """Resolve to a ufunc based on keyword arguments."""
+
+        if isinstance(self._ufunc_or_ufuncs, np.ufunc):
+            return self._ufunc_or_ufuncs
+
+        ufunc_key = self._key(**kwargs)
+        return self._ufunc_or_ufuncs[ufunc_key]
+
+    def __call__(self, *args, **kwargs):
+        kwargs = self._default_kwargs | kwargs
+
+        args += self._ufunc_default_args(**kwargs)
+
+        ufunc = self._resolve_ufunc(**kwargs)
+
+        # array arguments to be passed to the ufunc
+        ufunc_args = [np.asarray(arg) for arg in args[-ufunc.nin:]]
+
+        ufunc_kwargs = self._ufunc_default_kwargs(**kwargs)
+
+        if (self._resolve_out_shapes is not None):
+            ufunc_arg_shapes = tuple(np.shape(ufunc_arg) for ufunc_arg in ufunc_args)
+            ufunc_out_shapes = self._resolve_out_shapes(*args[:-ufunc.nin],
+                                                        *ufunc_arg_shapes, ufunc.nout,
+                                                        **kwargs)
+
+            ufunc_arg_dtypes = tuple(ufunc_arg.dtype if hasattr(ufunc_arg, 'dtype')
+                                     else np.dtype(type(ufunc_arg))
+                                     for ufunc_arg in ufunc_args)
+
+            if hasattr(ufunc, 'resolve_dtypes'):
+                ufunc_dtypes = ufunc_arg_dtypes + ufunc.nout * (None,)
+                ufunc_dtypes = ufunc.resolve_dtypes(ufunc_dtypes)
+                ufunc_out_dtypes = ufunc_dtypes[-ufunc.nout:]
+            else:
+                ufunc_out_dtype = np.result_type(*ufunc_arg_dtypes)
+                if (not np.issubdtype(ufunc_out_dtype, np.inexact)):
+                    ufunc_out_dtype = np.float64
+
+                ufunc_out_dtypes = ufunc.nout * (ufunc_out_dtype,)
+
+            if self.__force_complex_output:
+                ufunc_out_dtypes = tuple(np.result_type(1j, ufunc_out_dtype)
+                                         for ufunc_out_dtype in ufunc_out_dtypes)
+
+            out = tuple(np.empty(ufunc_out_shape, dtype=ufunc_out_dtype)
+                        for ufunc_out_shape, ufunc_out_dtype
+                        in zip(ufunc_out_shapes, ufunc_out_dtypes))
+
+            ufunc_kwargs['out'] = out
+
+        out = ufunc(*ufunc_args, **ufunc_kwargs)
+        if (self._finalize_out is not None):
+            out = self._finalize_out(out)
+
+        return out
+
+
+sph_legendre_p = MultiUFunc(
+    sph_legendre_p,
+    r"""sph_legendre_p(n, m, theta, *, diff_n=0)
+
+    Spherical Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the spherical Legendre polynomial. Must have ``n >= 0``.
+    m : ArrayLike[int]
+        Order of the spherical Legendre polynomial.
+    theta : ArrayLike[float]
+        Input value.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Spherical Legendre polynomial with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    The spherical counterpart of an (unnormalized) associated Legendre polynomial has
+    the additional factor
+
+    .. math::
+
+        \sqrt{\frac{(2 n + 1) (n - m)!}{4 \pi (n + m)!}}
+
+    It is the same as the spherical harmonic :math:`Y_{n}^{m}(\theta, \phi)`
+    with :math:`\phi = 0`.
+    """, diff_n=0
+)
+
+
+@sph_legendre_p._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+sph_legendre_p_all = MultiUFunc(
+    sph_legendre_p_all,
+    """sph_legendre_p_all(n, m, theta, *, diff_n=0)
+
+    All spherical Legendre polynomials of the first kind up to the
+    specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    sph_legendre_p
+    """, diff_n=0
+)
+
+
+@sph_legendre_p_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_legendre_p_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [()] + [(0, 1, -1)]}
+
+
+@sph_legendre_p_all._override_resolve_out_shapes
+def _(n, m, theta_shape, nout, diff_n):
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) + theta_shape + (diff_n + 1,),)
+
+
+@sph_legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+assoc_legendre_p = MultiUFunc(
+    assoc_legendre_p,
+    r"""assoc_legendre_p(n, m, z, *, branch_cut=2, norm=False, diff_n=0)
+
+    Associated Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the associated Legendre polynomial. Must have ``n >= 0``.
+    m : ArrayLike[int]
+        order of the associated Legendre polynomial.
+    z : ArrayLike[float | complex]
+        Input value.
+    branch_cut : Optional[ArrayLike[int]]
+        Selects branch cut. Must be 2 (default) or 3.
+        2: cut on the real axis ``|z| > 1``
+        3: cut on the real axis ``-1 < z < 1``
+    norm : Optional[bool]
+        If ``True``, compute the normalized associated Legendre polynomial.
+        Default is ``False``.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Associated Legendre polynomial with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    The normalized counterpart of an (unnormalized) associated Legendre
+    polynomial has the additional factor
+
+    .. math::
+
+        \sqrt{\frac{(2 n + 1) (n - m)!}{2 (n + m)!}}
+    """, branch_cut=2, norm=False, diff_n=0
+)
+
+
+@assoc_legendre_p._override_key
+def _(branch_cut, norm, diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return norm, diff_n
+
+
+@assoc_legendre_p._override_ufunc_default_args
+def _(branch_cut, norm, diff_n):
+    return branch_cut,
+
+
+@assoc_legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+assoc_legendre_p_all = MultiUFunc(
+    assoc_legendre_p_all,
+    """assoc_legendre_p_all(n, m, z, *, branch_cut=2, norm=False, diff_n=0)
+
+    All associated Legendre polynomials of the first kind up to the
+    specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    assoc_legendre_p
+    """, branch_cut=2, norm=False, diff_n=0
+)
+
+
+@assoc_legendre_p_all._override_key
+def _(branch_cut, norm, diff_n):
+    if not ((isinstance(diff_n, numbers.Integral))
+            and diff_n >= 0):
+        raise ValueError(
+            f"diff_n must be a non-negative integer, received: {diff_n}."
+        )
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return norm, diff_n
+
+
+@assoc_legendre_p_all._override_ufunc_default_args
+def _(branch_cut, norm, diff_n):
+    return branch_cut,
+
+
+@assoc_legendre_p_all._override_ufunc_default_kwargs
+def _(branch_cut, norm, diff_n):
+    return {'axes': [(), ()] + [(0, 1, -1)]}
+
+
+@assoc_legendre_p_all._override_resolve_out_shapes
+def _(n, m, z_shape, branch_cut_shape, nout, **kwargs):
+    diff_n = kwargs['diff_n']
+
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    if not isinstance(m, numbers.Integral) or (m < 0):
+        raise ValueError("m must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) +
+        np.broadcast_shapes(z_shape, branch_cut_shape) + (diff_n + 1,),)
+
+
+@assoc_legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+legendre_p = MultiUFunc(
+    legendre_p,
+    """legendre_p(n, z, *, diff_n=0)
+
+    Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the Legendre polynomial. Must have ``n >= 0``.
+    z : ArrayLike[float]
+        Input value.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Legendre polynomial with ``diff_n`` derivatives.
+
+    See Also
+    --------
+    legendre
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    """, diff_n=0
+)
+
+
+@legendre_p._override_key
+def _(diff_n):
+    if (not isinstance(diff_n, numbers.Integral)) or (diff_n < 0):
+        raise ValueError(
+            f"diff_n must be a non-negative integer, received: {diff_n}."
+        )
+    if not 0 <= diff_n <= 2:
+        raise NotImplementedError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+legendre_p_all = MultiUFunc(
+    legendre_p_all,
+    """legendre_p_all(n, z, *, diff_n=0)
+
+    All Legendre polynomials of the first kind up to the
+    specified degree ``n``.
+
+    Output shape is ``(n + 1, ...)``. The entry at ``j``
+    corresponds to degree ``j`` for all  ``0 <= j <= n``.
+
+    See Also
+    --------
+    legendre_p
+    """, diff_n=0
+)
+
+
+@legendre_p_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@legendre_p_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [(), (0, -1)]}
+
+
+@legendre_p_all._override_resolve_out_shapes
+def _(n, z_shape, nout, diff_n):
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+
+    return nout * ((n + 1,) + z_shape + (diff_n + 1,),)
+
+
+@legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+sph_harm_y = MultiUFunc(
+    sph_harm_y,
+    r"""sph_harm_y(n, m, theta, phi, *, diff_n=0)
+
+    Spherical harmonics. They are defined as
+
+    .. math::
+
+        Y_n^m(\theta,\phi) = \sqrt{\frac{2 n + 1}{4 \pi} \frac{(n - m)!}{(n + m)!}}
+            P_n^m(\cos(\theta)) e^{i m \phi}
+
+    where :math:`P_n^m` are the (unnormalized) associated Legendre polynomials.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the harmonic. Must have ``n >= 0``. This is
+        often denoted by ``l`` (lower case L) in descriptions of
+        spherical harmonics.
+    m : ArrayLike[int]
+        Order of the harmonic.
+    theta : ArrayLike[float]
+        Polar (colatitudinal) coordinate; must be in ``[0, pi]``.
+    phi : ArrayLike[float]
+        Azimuthal (longitudinal) coordinate; must be in ``[0, 2*pi]``.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    y : ndarray[complex] or tuple[ndarray[complex]]
+       Spherical harmonics with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    There are different conventions for the meanings of the input
+    arguments ``theta`` and ``phi``. In SciPy ``theta`` is the
+    polar angle and ``phi`` is the azimuthal angle. It is common to
+    see the opposite convention, that is, ``theta`` as the azimuthal angle
+    and ``phi`` as the polar angle.
+
+    Note that SciPy's spherical harmonics include the Condon-Shortley
+    phase [2]_ because it is part of `sph_legendre_p`.
+
+    With SciPy's conventions, the first several spherical harmonics
+    are
+
+    .. math::
+
+        Y_0^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{1}{\pi}} \\
+        Y_1^{-1}(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{2\pi}}
+                                    e^{-i\phi} \sin(\theta) \\
+        Y_1^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{\pi}}
+                                 \cos(\theta) \\
+        Y_1^1(\theta, \phi) &= -\frac{1}{2} \sqrt{\frac{3}{2\pi}}
+                                 e^{i\phi} \sin(\theta).
+
+    References
+    ----------
+    .. [1] Digital Library of Mathematical Functions, 14.30.
+           https://dlmf.nist.gov/14.30
+    .. [2] https://en.wikipedia.org/wiki/Spherical_harmonics#Condon.E2.80.93Shortley_phase
+    """, force_complex_output=True, diff_n=0
+)
+
+
+@sph_harm_y._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_harm_y._override_finalize_out
+def _(out):
+    if (out.shape[-1] == 1):
+        return out[..., 0, 0]
+
+    if (out.shape[-1] == 2):
+        return out[..., 0, 0], out[..., [1, 0], [0, 1]]
+
+    if (out.shape[-1] == 3):
+        return (out[..., 0, 0], out[..., [1, 0], [0, 1]],
+            out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]])
+
+
+sph_harm_y_all = MultiUFunc(
+    sph_harm_y_all,
+    """sph_harm_y_all(n, m, theta, phi, *, diff_n=0)
+
+    All spherical harmonics up to the specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    sph_harm_y
+    """, force_complex_output=True, diff_n=0
+)
+
+
+@sph_harm_y_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_harm_y_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [(), ()] + [(0, 1, -2, -1)]}
+
+
+@sph_harm_y_all._override_resolve_out_shapes
+def _(n, m, theta_shape, phi_shape, nout, **kwargs):
+    diff_n = kwargs['diff_n']
+
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) + np.broadcast_shapes(theta_shape, phi_shape) +
+        (diff_n + 1, diff_n + 1),)
+
+
+@sph_harm_y_all._override_finalize_out
+def _(out):
+    if (out.shape[-1] == 1):
+        return out[..., 0, 0]
+
+    if (out.shape[-1] == 2):
+        return out[..., 0, 0], out[..., [1, 0], [0, 1]]
+
+    if (out.shape[-1] == 3):
+        return (out[..., 0, 0], out[..., [1, 0], [0, 1]],
+            out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]])
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py b/venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..e021f5a899b2b9218d59527fd91fb6cf7a545042
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py
@@ -0,0 +1,2592 @@
+"""
+A collection of functions to find the weights and abscissas for
+Gaussian Quadrature.
+
+These calculations are done by finding the eigenvalues of a
+tridiagonal matrix whose entries are dependent on the coefficients
+in the recursion formula for the orthogonal polynomials with the
+corresponding weighting function over the interval.
+
+Many recursion relations for orthogonal polynomials are given:
+
+.. math::
+
+    a1n f_{n+1} (x) = (a2n + a3n x ) f_n (x) - a4n f_{n-1} (x)
+
+The recursion relation of interest is
+
+.. math::
+
+    P_{n+1} (x) = (x - A_n) P_n (x) - B_n P_{n-1} (x)
+
+where :math:`P` has a different normalization than :math:`f`.
+
+The coefficients can be found as:
+
+.. math::
+
+    A_n = -a2n / a3n
+    \\qquad
+    B_n = ( a4n / a3n \\sqrt{h_n-1 / h_n})^2
+
+where
+
+.. math::
+
+    h_n = \\int_a^b w(x) f_n(x)^2
+
+assume:
+
+.. math::
+
+    P_0 (x) = 1
+    \\qquad
+    P_{-1} (x) == 0
+
+For the mathematical background, see [golub.welsch-1969-mathcomp]_ and
+[abramowitz.stegun-1965]_.
+
+References
+----------
+.. [golub.welsch-1969-mathcomp]
+   Golub, Gene H, and John H Welsch. 1969. Calculation of Gauss
+   Quadrature Rules. *Mathematics of Computation* 23, 221-230+s1--s10.
+
+.. [abramowitz.stegun-1965]
+   Abramowitz, Milton, and Irene A Stegun. (1965) *Handbook of
+   Mathematical Functions: with Formulas, Graphs, and Mathematical
+   Tables*. Gaithersburg, MD: National Bureau of Standards.
+   http://www.math.sfu.ca/~cbm/aands/
+
+.. [townsend.trogdon.olver-2014]
+   Townsend, A. and Trogdon, T. and Olver, S. (2014)
+   *Fast computation of Gauss quadrature nodes and
+   weights on the whole real line*. :arXiv:`1410.5286`.
+
+.. [townsend.trogdon.olver-2015]
+   Townsend, A. and Trogdon, T. and Olver, S. (2015)
+   *Fast computation of Gauss quadrature nodes and
+   weights on the whole real line*.
+   IMA Journal of Numerical Analysis
+   :doi:`10.1093/imanum/drv002`.
+"""
+#
+# Author:  Travis Oliphant 2000
+# Updated Sep. 2003 (fixed bugs --- tested to be accurate)
+
+# SciPy imports.
+import numpy as np
+from numpy import (exp, inf, pi, sqrt, floor, sin, cos, around,
+                   hstack, arccos, arange)
+from scipy import linalg
+from scipy.special import airy
+
+# Local imports.
+# There is no .pyi file for _specfun
+from . import _specfun  # type: ignore
+from . import _ufuncs
+_gam = _ufuncs.gamma
+
+_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
+             'jacobi', 'laguerre', 'genlaguerre', 'hermite',
+             'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
+             'sh_chebyu', 'sh_jacobi']
+
+# Correspondence between new and old names of root functions
+_rootfuns_map = {'roots_legendre': 'p_roots',
+                 'roots_chebyt': 't_roots',
+                 'roots_chebyu': 'u_roots',
+                 'roots_chebyc': 'c_roots',
+                 'roots_chebys': 's_roots',
+                 'roots_jacobi': 'j_roots',
+                 'roots_laguerre': 'l_roots',
+                 'roots_genlaguerre': 'la_roots',
+                 'roots_hermite': 'h_roots',
+                 'roots_hermitenorm': 'he_roots',
+                 'roots_gegenbauer': 'cg_roots',
+                 'roots_sh_legendre': 'ps_roots',
+                 'roots_sh_chebyt': 'ts_roots',
+                 'roots_sh_chebyu': 'us_roots',
+                 'roots_sh_jacobi': 'js_roots'}
+
+__all__ = _polyfuns + list(_rootfuns_map.keys())
+
+
+class orthopoly1d(np.poly1d):
+
+    def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None,
+                 limits=None, monic=False, eval_func=None):
+        equiv_weights = [weights[k] / wfunc(roots[k]) for
+                         k in range(len(roots))]
+        mu = sqrt(hn)
+        if monic:
+            evf = eval_func
+            if evf:
+                knn = kn
+                def eval_func(x):
+                    return evf(x) / knn
+            mu = mu / abs(kn)
+            kn = 1.0
+
+        # compute coefficients from roots, then scale
+        poly = np.poly1d(roots, r=True)
+        np.poly1d.__init__(self, poly.coeffs * float(kn))
+
+        self.weights = np.array(list(zip(roots, weights, equiv_weights)))
+        self.weight_func = wfunc
+        self.limits = limits
+        self.normcoef = mu
+
+        # Note: eval_func will be discarded on arithmetic
+        self._eval_func = eval_func
+
+    def __call__(self, v):
+        if self._eval_func and not isinstance(v, np.poly1d):
+            return self._eval_func(v)
+        else:
+            return np.poly1d.__call__(self, v)
+
+    def _scale(self, p):
+        if p == 1.0:
+            return
+        self._coeffs *= p
+
+        evf = self._eval_func
+        if evf:
+            self._eval_func = lambda x: evf(x) * p
+        self.normcoef *= p
+
+
+def _gen_roots_and_weights(n, mu0, an_func, bn_func, f, df, symmetrize, mu):
+    """[x,w] = gen_roots_and_weights(n,an_func,sqrt_bn_func,mu)
+
+    Returns the roots (x) of an nth order orthogonal polynomial,
+    and weights (w) to use in appropriate Gaussian quadrature with that
+    orthogonal polynomial.
+
+    The polynomials have the recurrence relation
+          P_n+1(x) = (x - A_n) P_n(x) - B_n P_n-1(x)
+
+    an_func(n)          should return A_n
+    sqrt_bn_func(n)     should return sqrt(B_n)
+    mu ( = h_0 )        is the integral of the weight over the orthogonal
+                        interval
+    """
+    k = np.arange(n, dtype='d')
+    c = np.zeros((2, n))
+    c[0,1:] = bn_func(k[1:])
+    c[1,:] = an_func(k)
+    x = linalg.eigvals_banded(c, overwrite_a_band=True)
+
+    # improve roots by one application of Newton's method
+    y = f(n, x)
+    dy = df(n, x)
+    x -= y/dy
+
+    # fm and dy may contain very large/small values, so we
+    # log-normalize them to maintain precision in the product fm*dy
+    fm = f(n-1, x)
+    log_fm = np.log(np.abs(fm))
+    log_dy = np.log(np.abs(dy))
+    fm /= np.exp((log_fm.max() + log_fm.min()) / 2.)
+    dy /= np.exp((log_dy.max() + log_dy.min()) / 2.)
+    w = 1.0 / (fm * dy)
+
+    if symmetrize:
+        w = (w + w[::-1]) / 2
+        x = (x - x[::-1]) / 2
+
+    w *= mu0 / w.sum()
+
+    if mu:
+        return x, w, mu0
+    else:
+        return x, w
+
+# Jacobi Polynomials 1               P^(alpha,beta)_n(x)
+
+
+def roots_jacobi(n, alpha, beta, mu=False):
+    r"""Gauss-Jacobi quadrature.
+
+    Compute the sample points and weights for Gauss-Jacobi
+    quadrature. The sample points are the roots of the nth degree
+    Jacobi polynomial, :math:`P^{\alpha, \beta}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
+    weight function :math:`w(x) = (1 - x)^{\alpha} (1 +
+    x)^{\beta}`. See 22.2.1 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -1
+    beta : float
+        beta must be > -1
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha <= -1 or beta <= -1:
+        raise ValueError("alpha and beta must be greater than -1.")
+
+    if alpha == 0.0 and beta == 0.0:
+        return roots_legendre(m, mu)
+    if alpha == beta:
+        return roots_gegenbauer(m, alpha+0.5, mu)
+
+    if (alpha + beta) <= 1000:
+        mu0 = 2.0**(alpha+beta+1) * _ufuncs.beta(alpha+1, beta+1)
+    else:
+        # Avoid overflows in pow and beta for very large parameters
+        mu0 = np.exp((alpha + beta + 1) * np.log(2.0)
+                     + _ufuncs.betaln(alpha+1, beta+1))
+    a = alpha
+    b = beta
+    if a + b == 0.0:
+        def an_func(k):
+            return np.where(k == 0, (b - a) / (2 + a + b), 0.0)
+    else:
+        def an_func(k):
+            return np.where(
+                k == 0,
+                (b - a) / (2 + a + b),
+                (b * b - a * a) / ((2.0 * k + a + b) * (2.0 * k + a + b + 2))
+            )
+
+    def bn_func(k):
+        return (
+            2.0 / (2.0 * k + a + b)
+            * np.sqrt((k + a) * (k + b) / (2 * k + a + b + 1))
+            * np.where(k == 1, 1.0, np.sqrt(k * (k + a + b) / (2.0 * k + a + b - 1)))
+        )
+
+    def f(n, x):
+        return _ufuncs.eval_jacobi(n, a, b, x)
+    def df(n, x):
+        return 0.5 * (n + a + b + 1) * _ufuncs.eval_jacobi(n - 1, a + 1, b + 1, x)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
+
+
+def jacobi(n, alpha, beta, monic=False):
+    r"""Jacobi polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}P_n^{(\alpha, \beta)}
+          + (\beta - \alpha - (\alpha + \beta + 2)x)
+            \frac{d}{dx}P_n^{(\alpha, \beta)}
+          + n(n + \alpha + \beta + 1)P_n^{(\alpha, \beta)} = 0
+
+    for :math:`\alpha, \beta > -1`; :math:`P_n^{(\alpha, \beta)}` is a
+    polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -1.
+    beta : float
+        Parameter, must be greater than -1.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Jacobi polynomial.
+
+    Notes
+    -----
+    For fixed :math:`\alpha, \beta`, the polynomials
+    :math:`P_n^{(\alpha, \beta)}` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x)^\alpha(1 + x)^\beta`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The Jacobi polynomials satisfy the recurrence relation:
+
+    .. math::
+        P_n^{(\alpha, \beta-1)}(x) - P_n^{(\alpha-1, \beta)}(x)
+          = P_{n-1}^{(\alpha, \beta)}(x)
+
+    This can be verified, for example, for :math:`\alpha = \beta = 2`
+    and :math:`n = 1` over the interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import jacobi
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(jacobi(0, 2, 2)(x),
+    ...             jacobi(1, 2, 1)(x) - jacobi(1, 1, 2)(x))
+    True
+
+    Plot of the Jacobi polynomial :math:`P_5^{(\alpha, -0.5)}` for
+    different values of :math:`\alpha`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Jacobi polynomials $P_5^{(\alpha, -0.5)}$')
+    >>> for alpha in np.arange(0, 4, 1):
+    ...     ax.plot(x, jacobi(5, alpha, -0.5)(x), label=rf'$\alpha={alpha}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return (1 - x) ** alpha * (1 + x) ** beta
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
+                           eval_func=np.ones_like)
+    x, w, mu = roots_jacobi(n, alpha, beta, mu=True)
+    ab1 = alpha + beta + 1.0
+    hn = 2**ab1 / (2 * n + ab1) * _gam(n + alpha + 1)
+    hn *= _gam(n + beta + 1.0) / _gam(n + 1) / _gam(n + ab1)
+    kn = _gam(2 * n + ab1) / 2.0**n / _gam(n + 1) / _gam(n + ab1)
+    # here kn = coefficient on x^n term
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
+                    lambda x: _ufuncs.eval_jacobi(n, alpha, beta, x))
+    return p
+
+# Jacobi Polynomials shifted         G_n(p,q,x)
+
+
+def roots_sh_jacobi(n, p1, q1, mu=False):
+    """Gauss-Jacobi (shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Jacobi (shifted)
+    quadrature. The sample points are the roots of the nth degree
+    shifted Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[0, 1]` with
+    weight function :math:`w(x) = (1 - x)^{p-q} x^{q-1}`. See 22.2.2
+    in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    p1 : float
+        (p1 - q1) must be > -1
+    q1 : float
+        q1 must be > 0
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    if (p1-q1) <= -1 or q1 <= 0:
+        message = "(p - q) must be greater than -1, and q must be greater than 0."
+        raise ValueError(message)
+    x, w, m = roots_jacobi(n, p1-q1, q1-1, True)
+    x = (x + 1) / 2
+    scale = 2.0**p1
+    w /= scale
+    m /= scale
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def sh_jacobi(n, p, q, monic=False):
+    r"""Shifted Jacobi polynomial.
+
+    Defined by
+
+    .. math::
+
+        G_n^{(p, q)}(x)
+          = \binom{2n + p - 1}{n}^{-1}P_n^{(p - q, q - 1)}(2x - 1),
+
+    where :math:`P_n^{(\cdot, \cdot)}` is the nth Jacobi polynomial.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    p : float
+        Parameter, must have :math:`p > q - 1`.
+    q : float
+        Parameter, must be greater than 0.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    G : orthopoly1d
+        Shifted Jacobi polynomial.
+
+    Notes
+    -----
+    For fixed :math:`p, q`, the polynomials :math:`G_n^{(p, q)}` are
+    orthogonal over :math:`[0, 1]` with weight function :math:`(1 -
+    x)^{p - q}x^{q - 1}`.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return (1.0 - x) ** (p - q) * x ** (q - 1.0)
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
+                           eval_func=np.ones_like)
+    n1 = n
+    x, w = roots_sh_jacobi(n1, p, q)
+    hn = _gam(n + 1) * _gam(n + q) * _gam(n + p) * _gam(n + p - q + 1)
+    hn /= (2 * n + p) * (_gam(2 * n + p)**2)
+    # kn = 1.0 in standard form so monic is redundant. Kept for compatibility.
+    kn = 1.0
+    pp = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(0, 1), monic=monic,
+                     eval_func=lambda x: _ufuncs.eval_sh_jacobi(n, p, q, x))
+    return pp
+
+# Generalized Laguerre               L^(alpha)_n(x)
+
+
+def roots_genlaguerre(n, alpha, mu=False):
+    r"""Gauss-generalized Laguerre quadrature.
+
+    Compute the sample points and weights for Gauss-generalized
+    Laguerre quadrature. The sample points are the roots of the nth
+    degree generalized Laguerre polynomial, :math:`L^{\alpha}_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0,
+    \infty]` with weight function :math:`w(x) = x^{\alpha}
+    e^{-x}`. See 22.3.9 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -1
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha < -1:
+        raise ValueError("alpha must be greater than -1.")
+
+    mu0 = _ufuncs.gamma(alpha + 1)
+
+    if m == 1:
+        x = np.array([alpha+1.0], 'd')
+        w = np.array([mu0], 'd')
+        if mu:
+            return x, w, mu0
+        else:
+            return x, w
+
+    def an_func(k):
+        return 2 * k + alpha + 1
+    def bn_func(k):
+        return -np.sqrt(k * (k + alpha))
+    def f(n, x):
+        return _ufuncs.eval_genlaguerre(n, alpha, x)
+    def df(n, x):
+        return (n * _ufuncs.eval_genlaguerre(n, alpha, x)
+                - (n + alpha) * _ufuncs.eval_genlaguerre(n - 1, alpha, x)) / x
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
+
+
+def genlaguerre(n, alpha, monic=False):
+    r"""Generalized (associated) Laguerre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        x\frac{d^2}{dx^2}L_n^{(\alpha)}
+          + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)}
+          + nL_n^{(\alpha)} = 0,
+
+    where :math:`\alpha > -1`; :math:`L_n^{(\alpha)}` is a polynomial
+    of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -1.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    L : orthopoly1d
+        Generalized Laguerre polynomial.
+
+    See Also
+    --------
+    laguerre : Laguerre polynomial.
+    hyp1f1 : confluent hypergeometric function
+
+    Notes
+    -----
+    For fixed :math:`\alpha`, the polynomials :math:`L_n^{(\alpha)}`
+    are orthogonal over :math:`[0, \infty)` with weight function
+    :math:`e^{-x}x^\alpha`.
+
+    The Laguerre polynomials are the special case where :math:`\alpha
+    = 0`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The generalized Laguerre polynomials are closely related to the confluent
+    hypergeometric function :math:`{}_1F_1`:
+
+        .. math::
+            L_n^{(\alpha)} = \binom{n + \alpha}{n} {}_1F_1(-n, \alpha +1, x)
+
+    This can be verified, for example,  for :math:`n = \alpha = 3` over the
+    interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import binom
+    >>> from scipy.special import genlaguerre
+    >>> from scipy.special import hyp1f1
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(genlaguerre(3, 3)(x), binom(6, 3) * hyp1f1(-3, 4, x))
+    True
+
+    This is the plot of the generalized Laguerre polynomials
+    :math:`L_3^{(\alpha)}` for some values of :math:`\alpha`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-4.0, 12.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-5.0, 10.0)
+    >>> ax.set_title(r'Generalized Laguerre polynomials $L_3^{\alpha}$')
+    >>> for alpha in np.arange(0, 5):
+    ...     ax.plot(x, genlaguerre(3, alpha)(x), label=rf'$L_3^{(alpha)}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if alpha <= -1:
+        raise ValueError("alpha must be > -1")
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_genlaguerre(n1, alpha)
+    def wfunc(x):
+        return exp(-x) * x ** alpha
+    if n == 0:
+        x, w = [], []
+    hn = _gam(n + alpha + 1) / _gam(n + 1)
+    kn = (-1)**n / _gam(n + 1)
+    p = orthopoly1d(x, w, hn, kn, wfunc, (0, inf), monic,
+                    lambda x: _ufuncs.eval_genlaguerre(n, alpha, x))
+    return p
+
+# Laguerre                      L_n(x)
+
+
+def roots_laguerre(n, mu=False):
+    r"""Gauss-Laguerre quadrature.
+
+    Compute the sample points and weights for Gauss-Laguerre
+    quadrature. The sample points are the roots of the nth degree
+    Laguerre polynomial, :math:`L_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[0, \infty]` with weight function
+    :math:`w(x) = e^{-x}`. See 22.2.13 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.laguerre.laggauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    return roots_genlaguerre(n, 0.0, mu=mu)
+
+
+def laguerre(n, monic=False):
+    r"""Laguerre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0;
+
+    :math:`L_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    L : orthopoly1d
+        Laguerre Polynomial.
+
+    See Also
+    --------
+    genlaguerre : Generalized (associated) Laguerre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`L_n` are orthogonal over :math:`[0,
+    \infty)` with weight function :math:`e^{-x}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The Laguerre polynomials :math:`L_n` are the special case
+    :math:`\alpha = 0` of the generalized Laguerre polynomials
+    :math:`L_n^{(\alpha)}`.
+    Let's verify it on the interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import genlaguerre
+    >>> from scipy.special import laguerre
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(genlaguerre(3, 0)(x), laguerre(3)(x))
+    True
+
+    The polynomials :math:`L_n` also satisfy the recurrence relation:
+
+    .. math::
+        (n + 1)L_{n+1}(x) = (2n +1 -x)L_n(x) - nL_{n-1}(x)
+
+    This can be easily checked on :math:`[0, 1]` for :math:`n = 3`:
+
+    >>> x = np.arange(0.0, 1.0, 0.01)
+    >>> np.allclose(4 * laguerre(4)(x),
+    ...             (7 - x) * laguerre(3)(x) - 3 * laguerre(2)(x))
+    True
+
+    This is the plot of the first few Laguerre polynomials :math:`L_n`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-1.0, 5.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-5.0, 5.0)
+    >>> ax.set_title(r'Laguerre polynomials $L_n$')
+    >>> for n in np.arange(0, 5):
+    ...     ax.plot(x, laguerre(n)(x), label=rf'$L_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_laguerre(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 1.0
+    kn = (-1)**n / _gam(n + 1)
+    p = orthopoly1d(x, w, hn, kn, lambda x: exp(-x), (0, inf), monic,
+                    lambda x: _ufuncs.eval_laguerre(n, x))
+    return p
+
+# Hermite  1                         H_n(x)
+
+
+def roots_hermite(n, mu=False):
+    r"""Gauss-Hermite (physicist's) quadrature.
+
+    Compute the sample points and weights for Gauss-Hermite
+    quadrature. The sample points are the roots of the nth degree
+    Hermite polynomial, :math:`H_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-\infty, \infty]` with weight
+    function :math:`w(x) = e^{-x^2}`. See 22.2.14 in [AS]_ for
+    details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.hermite.hermgauss
+    roots_hermitenorm
+
+    Notes
+    -----
+    For small n up to 150 a modified version of the Golub-Welsch
+    algorithm is used. Nodes are computed from the eigenvalue
+    problem and improved by one step of a Newton iteration.
+    The weights are computed from the well-known analytical formula.
+
+    For n larger than 150 an optimal asymptotic algorithm is applied
+    which computes nodes and weights in a numerically stable manner.
+    The algorithm has linear runtime making computation for very
+    large n (several thousand or more) feasible.
+
+    References
+    ----------
+    .. [townsend.trogdon.olver-2014]
+        Townsend, A. and Trogdon, T. and Olver, S. (2014)
+        *Fast computation of Gauss quadrature nodes and
+        weights on the whole real line*. :arXiv:`1410.5286`.
+    .. [townsend.trogdon.olver-2015]
+        Townsend, A. and Trogdon, T. and Olver, S. (2015)
+        *Fast computation of Gauss quadrature nodes and
+        weights on the whole real line*.
+        IMA Journal of Numerical Analysis
+        :doi:`10.1093/imanum/drv002`.
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = np.sqrt(np.pi)
+    if n <= 150:
+        def an_func(k):
+            return 0.0 * k
+        def bn_func(k):
+            return np.sqrt(k / 2.0)
+        f = _ufuncs.eval_hermite
+        def df(n, x):
+            return 2.0 * n * _ufuncs.eval_hermite(n - 1, x)
+        return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+    else:
+        nodes, weights = _roots_hermite_asy(m)
+        if mu:
+            return nodes, weights, mu0
+        else:
+            return nodes, weights
+
+
+def _compute_tauk(n, k, maxit=5):
+    """Helper function for Tricomi initial guesses
+
+    For details, see formula 3.1 in lemma 3.1 in the
+    original paper.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots :math:`\tau_k` to compute
+    maxit : int
+        Number of Newton maxit performed, the default
+        value of 5 is sufficient.
+
+    Returns
+    -------
+    tauk : ndarray
+        Roots of equation 3.1
+
+    See Also
+    --------
+    initial_nodes_a
+    roots_hermite_asy
+    """
+    a = n % 2 - 0.5
+    c = (4.0*floor(n/2.0) - 4.0*k + 3.0)*pi / (4.0*floor(n/2.0) + 2.0*a + 2.0)
+    def f(x):
+        return x - sin(x) - c
+    def df(x):
+        return 1.0 - cos(x)
+    xi = 0.5*pi
+    for i in range(maxit):
+        xi = xi - f(xi)/df(xi)
+    return xi
+
+
+def _initial_nodes_a(n, k):
+    r"""Tricomi initial guesses
+
+    Computes an initial approximation to the square of the `k`-th
+    (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The formula is the one from lemma 3.1 in the
+    original paper. The guesses are accurate except in the region
+    near :math:`\sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots to compute
+
+    Returns
+    -------
+    xksq : ndarray
+        Square of the approximate roots
+
+    See Also
+    --------
+    initial_nodes
+    roots_hermite_asy
+    """
+    tauk = _compute_tauk(n, k)
+    sigk = cos(0.5*tauk)**2
+    a = n % 2 - 0.5
+    nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
+    # Initial approximation of Hermite roots (square)
+    xksq = nu*sigk - 1.0/(3.0*nu) * (5.0/(4.0*(1.0-sigk)**2) - 1.0/(1.0-sigk) - 0.25)
+    return xksq
+
+
+def _initial_nodes_b(n, k):
+    r"""Gatteschi initial guesses
+
+    Computes an initial approximation to the square of the kth
+    (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The formula is the one from lemma 3.2 in the
+    original paper. The guesses are accurate in the region just
+    below :math:`\sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots to compute
+
+    Returns
+    -------
+    xksq : ndarray
+        Square of the approximate root
+
+    See Also
+    --------
+    initial_nodes
+    roots_hermite_asy
+    """
+    a = n % 2 - 0.5
+    nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
+    # Airy roots by approximation
+    ak = _specfun.airyzo(k.max(), 1)[0][::-1]
+    # Initial approximation of Hermite roots (square)
+    xksq = (nu
+            + 2.0**(2.0/3.0) * ak * nu**(1.0/3.0)
+            + 1.0/5.0 * 2.0**(4.0/3.0) * ak**2 * nu**(-1.0/3.0)
+            + (9.0/140.0 - 12.0/175.0 * ak**3) * nu**(-1.0)
+            + (16.0/1575.0 * ak + 92.0/7875.0 * ak**4) * 2.0**(2.0/3.0) * nu**(-5.0/3.0)
+            - (15152.0/3031875.0 * ak**5 + 1088.0/121275.0 * ak**2)
+              * 2.0**(1.0/3.0) * nu**(-7.0/3.0))
+    return xksq
+
+
+def _initial_nodes(n):
+    """Initial guesses for the Hermite roots
+
+    Computes an initial approximation to the non-negative
+    roots :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The Tricomi and Gatteschi initial
+    guesses are used in the region where they are accurate.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+
+    Returns
+    -------
+    xk : ndarray
+        Approximate roots
+
+    See Also
+    --------
+    roots_hermite_asy
+    """
+    # Turnover point
+    # linear polynomial fit to error of 10, 25, 40, ..., 1000 point rules
+    fit = 0.49082003*n - 4.37859653
+    turnover = around(fit).astype(int)
+    # Compute all approximations
+    ia = arange(1, int(floor(n*0.5)+1))
+    ib = ia[::-1]
+    xasq = _initial_nodes_a(n, ia[:turnover+1])
+    xbsq = _initial_nodes_b(n, ib[turnover+1:])
+    # Combine
+    iv = sqrt(hstack([xasq, xbsq]))
+    # Central node is always zero
+    if n % 2 == 1:
+        iv = hstack([0.0, iv])
+    return iv
+
+
+def _pbcf(n, theta):
+    r"""Asymptotic series expansion of parabolic cylinder function
+
+    The implementation is based on sections 3.2 and 3.3 from the
+    original paper. Compared to the published version this code
+    adds one more term to the asymptotic series. The detailed
+    formulas can be found at [parabolic-asymptotics]_. The evaluation
+    is done in a transformed variable :math:`\theta := \arccos(t)`
+    where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    theta : ndarray
+        Transformed position variable
+
+    Returns
+    -------
+    U : ndarray
+        Value of the parabolic cylinder function :math:`U(a, \theta)`.
+    Ud : ndarray
+        Value of the derivative :math:`U^{\prime}(a, \theta)` of
+        the parabolic cylinder function.
+
+    See Also
+    --------
+    roots_hermite_asy
+
+    References
+    ----------
+    .. [parabolic-asymptotics]
+       https://dlmf.nist.gov/12.10#vii
+    """
+    st = sin(theta)
+    ct = cos(theta)
+    # https://dlmf.nist.gov/12.10#vii
+    mu = 2.0*n + 1.0
+    # https://dlmf.nist.gov/12.10#E23
+    eta = 0.5*theta - 0.5*st*ct
+    # https://dlmf.nist.gov/12.10#E39
+    zeta = -(3.0*eta/2.0) ** (2.0/3.0)
+    # https://dlmf.nist.gov/12.10#E40
+    phi = (-zeta / st**2) ** (0.25)
+    # Coefficients
+    # https://dlmf.nist.gov/12.10#E43
+    a0 = 1.0
+    a1 = 0.10416666666666666667
+    a2 = 0.08355034722222222222
+    a3 = 0.12822657455632716049
+    a4 = 0.29184902646414046425
+    a5 = 0.88162726744375765242
+    b0 = 1.0
+    b1 = -0.14583333333333333333
+    b2 = -0.09874131944444444444
+    b3 = -0.14331205391589506173
+    b4 = -0.31722720267841354810
+    b5 = -0.94242914795712024914
+    # Polynomials
+    # https://dlmf.nist.gov/12.10#E9
+    # https://dlmf.nist.gov/12.10#E10
+    ctp = ct ** arange(16).reshape((-1,1))
+    u0 = 1.0
+    u1 = (1.0*ctp[3,:] - 6.0*ct) / 24.0
+    u2 = (-9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0
+    u3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:]
+          - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0
+    u4 = (72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:]
+          + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0
+    u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:]
+          - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:]
+          - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0
+    v0 = 1.0
+    v1 = (1.0*ctp[3,:] + 6.0*ct) / 24.0
+    v2 = (15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0
+    v3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:] 
+          + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0
+    v4 = (-121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:]
+          - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0
+    v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:]
+          - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:]
+          + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0
+    # Airy Evaluation (Bi and Bip unused)
+    Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta)
+    # Prefactor for U
+    P = 2.0*sqrt(pi) * mu**(1.0/6.0) * phi
+    # Terms for U
+    # https://dlmf.nist.gov/12.10#E42
+    phip = phi ** arange(6, 31, 6).reshape((-1,1))
+    A0 = b0*u0
+    A1 = (b2*u0 + phip[0,:]*b1*u1 + phip[1,:]*b0*u2) / zeta**3
+    A2 = (b4*u0 + phip[0,:]*b3*u1 + phip[1,:]*b2*u2 + phip[2,:]*b1*u3
+          + phip[3,:]*b0*u4) / zeta**6
+    B0 = -(a1*u0 + phip[0,:]*a0*u1) / zeta**2
+    B1 = -(a3*u0 + phip[0,:]*a2*u1 + phip[1,:]*a1*u2 + phip[2,:]*a0*u3) / zeta**5
+    B2 = -(a5*u0 + phip[0,:]*a4*u1 + phip[1,:]*a3*u2 + phip[2,:]*a2*u3
+           + phip[3,:]*a1*u4 + phip[4,:]*a0*u5) / zeta**8
+    # U
+    # https://dlmf.nist.gov/12.10#E35
+    U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) +
+             Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0))
+    # Prefactor for derivative of U
+    Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi
+    # Terms for derivative of U
+    # https://dlmf.nist.gov/12.10#E46
+    C0 = -(b1*v0 + phip[0,:]*b0*v1) / zeta
+    C1 = -(b3*v0 + phip[0,:]*b2*v1 + phip[1,:]*b1*v2 + phip[2,:]*b0*v3) / zeta**4
+    C2 = -(b5*v0 + phip[0,:]*b4*v1 + phip[1,:]*b3*v2 + phip[2,:]*b2*v3
+           + phip[3,:]*b1*v4 + phip[4,:]*b0*v5) / zeta**7
+    D0 = a0*v0
+    D1 = (a2*v0 + phip[0,:]*a1*v1 + phip[1,:]*a0*v2) / zeta**3
+    D2 = (a4*v0 + phip[0,:]*a3*v1 + phip[1,:]*a2*v2 + phip[2,:]*a1*v3
+          + phip[3,:]*a0*v4) / zeta**6
+    # Derivative of U
+    # https://dlmf.nist.gov/12.10#E36
+    Ud = Pd * (Ai * (C0 + C1/mu**2.0 + C2/mu**4.0) / mu**(4.0/6.0) +
+               Aip * (D0 + D1/mu**2.0 + D2/mu**4.0))
+    return U, Ud
+
+
+def _newton(n, x_initial, maxit=5):
+    """Newton iteration for polishing the asymptotic approximation
+    to the zeros of the Hermite polynomials.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    x_initial : ndarray
+        Initial guesses for the roots
+    maxit : int
+        Maximal number of Newton iterations.
+        The default 5 is sufficient, usually
+        only one or two steps are needed.
+
+    Returns
+    -------
+    nodes : ndarray
+        Quadrature nodes
+    weights : ndarray
+        Quadrature weights
+
+    See Also
+    --------
+    roots_hermite_asy
+    """
+    # Variable transformation
+    mu = sqrt(2.0*n + 1.0)
+    t = x_initial / mu
+    theta = arccos(t)
+    # Newton iteration
+    for i in range(maxit):
+        u, ud = _pbcf(n, theta)
+        dtheta = u / (sqrt(2.0) * mu * sin(theta) * ud)
+        theta = theta + dtheta
+        if max(abs(dtheta)) < 1e-14:
+            break
+    # Undo variable transformation
+    x = mu * cos(theta)
+    # Central node is always zero
+    if n % 2 == 1:
+        x[0] = 0.0
+    # Compute weights
+    w = exp(-x**2) / (2.0*ud**2)
+    return x, w
+
+
+def _roots_hermite_asy(n):
+    r"""Gauss-Hermite (physicist's) quadrature for large n.
+
+    Computes the sample points and weights for Gauss-Hermite quadrature.
+    The sample points are the roots of the nth degree Hermite polynomial,
+    :math:`H_n(x)`. These sample points and weights correctly integrate
+    polynomials of degree :math:`2n - 1` or less over the interval
+    :math:`[-\infty, \infty]` with weight function :math:`f(x) = e^{-x^2}`.
+
+    This method relies on asymptotic expansions which work best for n > 150.
+    The algorithm has linear runtime making computation for very large n
+    feasible.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+
+    Returns
+    -------
+    nodes : ndarray
+        Quadrature nodes
+    weights : ndarray
+        Quadrature weights
+
+    See Also
+    --------
+    roots_hermite
+
+    References
+    ----------
+    .. [townsend.trogdon.olver-2014]
+       Townsend, A. and Trogdon, T. and Olver, S. (2014)
+       *Fast computation of Gauss quadrature nodes and
+       weights on the whole real line*. :arXiv:`1410.5286`.
+
+    .. [townsend.trogdon.olver-2015]
+       Townsend, A. and Trogdon, T. and Olver, S. (2015)
+       *Fast computation of Gauss quadrature nodes and
+       weights on the whole real line*.
+       IMA Journal of Numerical Analysis
+       :doi:`10.1093/imanum/drv002`.
+    """
+    iv = _initial_nodes(n)
+    nodes, weights = _newton(n, iv)
+    # Combine with negative parts
+    if n % 2 == 0:
+        nodes = hstack([-nodes[::-1], nodes])
+        weights = hstack([weights[::-1], weights])
+    else:
+        nodes = hstack([-nodes[-1:0:-1], nodes])
+        weights = hstack([weights[-1:0:-1], weights])
+    # Scale weights
+    weights *= sqrt(pi) / sum(weights)
+    return nodes, weights
+
+
+def hermite(n, monic=False):
+    r"""Physicist's Hermite polynomial.
+
+    Defined by
+
+    .. math::
+
+        H_n(x) = (-1)^ne^{x^2}\frac{d^n}{dx^n}e^{-x^2};
+
+    :math:`H_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    H : orthopoly1d
+        Hermite polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`H_n` are orthogonal over :math:`(-\infty,
+    \infty)` with weight function :math:`e^{-x^2}`.
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    >>> p_monic = special.hermite(3, monic=True)
+    >>> p_monic
+    poly1d([ 1. ,  0. , -1.5,  0. ])
+    >>> p_monic(1)
+    -0.49999999999999983
+    >>> x = np.linspace(-3, 3, 400)
+    >>> y = p_monic(x)
+    >>> plt.plot(x, y)
+    >>> plt.title("Monic Hermite polynomial of degree 3")
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("H_3(x)")
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_hermite(n1)
+    def wfunc(x):
+        return exp(-x * x)
+    if n == 0:
+        x, w = [], []
+    hn = 2**n * _gam(n + 1) * sqrt(pi)
+    kn = 2**n
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-inf, inf), monic,
+                    lambda x: _ufuncs.eval_hermite(n, x))
+    return p
+
+# Hermite  2                         He_n(x)
+
+
+def roots_hermitenorm(n, mu=False):
+    r"""Gauss-Hermite (statistician's) quadrature.
+
+    Compute the sample points and weights for Gauss-Hermite
+    quadrature. The sample points are the roots of the nth degree
+    Hermite polynomial, :math:`He_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-\infty, \infty]` with weight
+    function :math:`w(x) = e^{-x^2/2}`. See 22.2.15 in [AS]_ for more
+    details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.hermite_e.hermegauss
+
+    Notes
+    -----
+    For small n up to 150 a modified version of the Golub-Welsch
+    algorithm is used. Nodes are computed from the eigenvalue
+    problem and improved by one step of a Newton iteration.
+    The weights are computed from the well-known analytical formula.
+
+    For n larger than 150 an optimal asymptotic algorithm is used
+    which computes nodes and weights in a numerical stable manner.
+    The algorithm has linear runtime making computation for very
+    large n (several thousand or more) feasible.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = np.sqrt(2.0*np.pi)
+    if n <= 150:
+        def an_func(k):
+            return 0.0 * k
+        def bn_func(k):
+            return np.sqrt(k)
+        f = _ufuncs.eval_hermitenorm
+        def df(n, x):
+            return n * _ufuncs.eval_hermitenorm(n - 1, x)
+        return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+    else:
+        nodes, weights = _roots_hermite_asy(m)
+        # Transform
+        nodes *= sqrt(2)
+        weights *= sqrt(2)
+        if mu:
+            return nodes, weights, mu0
+        else:
+            return nodes, weights
+
+
+def hermitenorm(n, monic=False):
+    r"""Normalized (probabilist's) Hermite polynomial.
+
+    Defined by
+
+    .. math::
+
+        He_n(x) = (-1)^ne^{x^2/2}\frac{d^n}{dx^n}e^{-x^2/2};
+
+    :math:`He_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    He : orthopoly1d
+        Hermite polynomial.
+
+    Notes
+    -----
+
+    The polynomials :math:`He_n` are orthogonal over :math:`(-\infty,
+    \infty)` with weight function :math:`e^{-x^2/2}`.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_hermitenorm(n1)
+    def wfunc(x):
+        return exp(-x * x / 2.0)
+    if n == 0:
+        x, w = [], []
+    hn = sqrt(2 * pi) * _gam(n + 1)
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(-inf, inf), monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_hermitenorm(n, x))
+    return p
+
+# The remainder of the polynomials can be derived from the ones above.
+
+# Ultraspherical (Gegenbauer)        C^(alpha)_n(x)
+
+
+def roots_gegenbauer(n, alpha, mu=False):
+    r"""Gauss-Gegenbauer quadrature.
+
+    Compute the sample points and weights for Gauss-Gegenbauer
+    quadrature. The sample points are the roots of the nth degree
+    Gegenbauer polynomial, :math:`C^{\alpha}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
+    weight function :math:`w(x) = (1 - x^2)^{\alpha - 1/2}`. See
+    22.2.3 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -0.5
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha < -0.5:
+        raise ValueError("alpha must be greater than -0.5.")
+    elif alpha == 0.0:
+        # C(n,0,x) == 0 uniformly, however, as alpha->0, C(n,alpha,x)->T(n,x)
+        # strictly, we should just error out here, since the roots are not
+        # really defined, but we used to return something useful, so let's
+        # keep doing so.
+        return roots_chebyt(n, mu)
+
+    if alpha <= 170:
+        mu0 = (np.sqrt(np.pi) * _ufuncs.gamma(alpha + 0.5)) \
+              / _ufuncs.gamma(alpha + 1)
+    else:
+        # For large alpha we use a Taylor series expansion around inf,
+        # expressed as a 6th order polynomial of a^-1 and using Horner's
+        # method to minimize computation and maximize precision
+        inv_alpha = 1. / alpha
+        coeffs = np.array([0.000207186, -0.00152206, -0.000640869,
+                           0.00488281, 0.0078125, -0.125, 1.])
+        mu0 = coeffs[0]
+        for term in range(1, len(coeffs)):
+            mu0 = mu0 * inv_alpha + coeffs[term]
+        mu0 = mu0 * np.sqrt(np.pi / alpha)
+    def an_func(k):
+        return 0.0 * k
+    def bn_func(k):
+        return np.sqrt(k * (k + 2 * alpha - 1) / (4 * (k + alpha) * (k + alpha - 1)))
+    def f(n, x):
+        return _ufuncs.eval_gegenbauer(n, alpha, x)
+    def df(n, x):
+        return (
+            -n * x * _ufuncs.eval_gegenbauer(n, alpha, x)
+            + (n + 2 * alpha - 1) * _ufuncs.eval_gegenbauer(n - 1, alpha, x)
+        ) / (1 - x ** 2)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+
+
+def gegenbauer(n, alpha, monic=False):
+    r"""Gegenbauer (ultraspherical) polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}C_n^{(\alpha)}
+          - (2\alpha + 1)x\frac{d}{dx}C_n^{(\alpha)}
+          + n(n + 2\alpha)C_n^{(\alpha)} = 0
+
+    for :math:`\alpha > -1/2`; :math:`C_n^{(\alpha)}` is a polynomial
+    of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -0.5.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    C : orthopoly1d
+        Gegenbauer polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`C_n^{(\alpha)}` are orthogonal over
+    :math:`[-1,1]` with weight function :math:`(1 - x^2)^{(\alpha -
+    1/2)}`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    We can initialize a variable ``p`` as a Gegenbauer polynomial using the
+    `gegenbauer` function and evaluate at a point ``x = 1``.
+
+    >>> p = special.gegenbauer(3, 0.5, monic=False)
+    >>> p
+    poly1d([ 2.5,  0. , -1.5,  0. ])
+    >>> p(1)
+    1.0
+
+    To evaluate ``p`` at various points ``x`` in the interval ``(-3, 3)``,
+    simply pass an array ``x`` to ``p`` as follows:
+
+    >>> x = np.linspace(-3, 3, 400)
+    >>> y = p(x)
+
+    We can then visualize ``x, y`` using `matplotlib.pyplot`.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y)
+    >>> ax.set_title("Gegenbauer (ultraspherical) polynomial of degree 3")
+    >>> ax.set_xlabel("x")
+    >>> ax.set_ylabel("G_3(x)")
+    >>> plt.show()
+
+    """
+    if not np.isfinite(alpha) or alpha <= -0.5 :
+        raise ValueError("`alpha` must be a finite number greater than -1/2")
+    base = jacobi(n, alpha - 0.5, alpha - 0.5, monic=monic)
+    if monic or n == 0:
+        return base
+    #  Abrahmowitz and Stegan 22.5.20
+    factor = (_gam(2*alpha + n) * _gam(alpha + 0.5) /
+              _gam(2*alpha) / _gam(alpha + 0.5 + n))
+    base._scale(factor)
+    base.__dict__['_eval_func'] = lambda x: _ufuncs.eval_gegenbauer(float(n),
+                                                                    alpha, x)
+    return base
+
+# Chebyshev of the first kind: T_n(x) =
+#     n! sqrt(pi) / _gam(n+1./2)* P^(-1/2,-1/2)_n(x)
+# Computed anew.
+
+
+def roots_chebyt(n, mu=False):
+    r"""Gauss-Chebyshev (first kind) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the first kind, :math:`T_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
+    with weight function :math:`w(x) = 1/\sqrt{1 - x^2}`. See 22.2.4
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.chebyshev.chebgauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError('n must be a positive integer.')
+    x = _ufuncs._sinpi(np.arange(-m + 1, m, 2) / (2*m))
+    w = np.full_like(x, pi/m)
+    if mu:
+        return x, w, pi
+    else:
+        return x, w
+
+
+def chebyt(n, monic=False):
+    r"""Chebyshev polynomial of the first kind.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}T_n - x\frac{d}{dx}T_n + n^2T_n = 0;
+
+    :math:`T_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    T : orthopoly1d
+        Chebyshev polynomial of the first kind.
+
+    See Also
+    --------
+    chebyu : Chebyshev polynomial of the second kind.
+
+    Notes
+    -----
+    The polynomials :math:`T_n` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x^2)^{-1/2}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Chebyshev polynomials of the first kind of order :math:`n` can
+    be obtained as the determinant of specific :math:`n \times n`
+    matrices. As an example we can check how the points obtained from
+    the determinant of the following :math:`3 \times 3` matrix
+    lay exactly on :math:`T_3`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.linalg import det
+    >>> from scipy.special import chebyt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Chebyshev polynomial $T_3$')
+    >>> ax.plot(x, chebyt(3)(x), label=rf'$T_3$')
+    >>> for p in np.arange(-1.0, 1.0, 0.1):
+    ...     ax.plot(p,
+    ...             det(np.array([[p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
+    ...             'rx')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    They are also related to the Jacobi Polynomials
+    :math:`P_n^{(-0.5, -0.5)}` through the relation:
+
+    .. math::
+        P_n^{(-0.5, -0.5)}(x) = \frac{1}{4^n} \binom{2n}{n} T_n(x)
+
+    Let's verify it for :math:`n = 3`:
+
+    >>> from scipy.special import binom
+    >>> from scipy.special import jacobi
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(jacobi(3, -0.5, -0.5)(x),
+    ...             1/64 * binom(6, 3) * chebyt(3)(x))
+    True
+
+    We can plot the Chebyshev polynomials :math:`T_n` for some values
+    of :math:`n`:
+
+    >>> x = np.arange(-1.5, 1.5, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-4.0, 4.0)
+    >>> ax.set_title(r'Chebyshev polynomials $T_n$')
+    >>> for n in np.arange(2,5):
+    ...     ax.plot(x, chebyt(n)(x), label=rf'$T_n={n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return 1.0 / sqrt(1 - x * x)
+    if n == 0:
+        return orthopoly1d([], [], pi, 1.0, wfunc, (-1, 1), monic,
+                           lambda x: _ufuncs.eval_chebyt(n, x))
+    n1 = n
+    x, w, mu = roots_chebyt(n1, mu=True)
+    hn = pi / 2
+    kn = 2**(n - 1)
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
+                    lambda x: _ufuncs.eval_chebyt(n, x))
+    return p
+
+# Chebyshev of the second kind
+#    U_n(x) = (n+1)! sqrt(pi) / (2*_gam(n+3./2)) * P^(1/2,1/2)_n(x)
+
+
+def roots_chebyu(n, mu=False):
+    r"""Gauss-Chebyshev (second kind) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the second kind, :math:`U_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
+    with weight function :math:`w(x) = \sqrt{1 - x^2}`. See 22.2.5 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError('n must be a positive integer.')
+    t = np.arange(m, 0, -1) * pi / (m + 1)
+    x = np.cos(t)
+    w = pi * np.sin(t)**2 / (m + 1)
+    if mu:
+        return x, w, pi / 2
+    else:
+        return x, w
+
+
+def chebyu(n, monic=False):
+    r"""Chebyshev polynomial of the second kind.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}U_n - 3x\frac{d}{dx}U_n
+          + n(n + 2)U_n = 0;
+
+    :math:`U_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    U : orthopoly1d
+        Chebyshev polynomial of the second kind.
+
+    See Also
+    --------
+    chebyt : Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`U_n` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x^2)^{1/2}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Chebyshev polynomials of the second kind of order :math:`n` can
+    be obtained as the determinant of specific :math:`n \times n`
+    matrices. As an example we can check how the points obtained from
+    the determinant of the following :math:`3 \times 3` matrix
+    lay exactly on :math:`U_3`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.linalg import det
+    >>> from scipy.special import chebyu
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Chebyshev polynomial $U_3$')
+    >>> ax.plot(x, chebyu(3)(x), label=rf'$U_3$')
+    >>> for p in np.arange(-1.0, 1.0, 0.1):
+    ...     ax.plot(p,
+    ...             det(np.array([[2*p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
+    ...             'rx')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    They satisfy the recurrence relation:
+
+    .. math::
+        U_{2n-1}(x) = 2 T_n(x)U_{n-1}(x)
+
+    where the :math:`T_n` are the Chebyshev polynomial of the first kind.
+    Let's verify it for :math:`n = 2`:
+
+    >>> from scipy.special import chebyt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(chebyu(3)(x), 2 * chebyt(2)(x) * chebyu(1)(x))
+    True
+
+    We can plot the Chebyshev polynomials :math:`U_n` for some values
+    of :math:`n`:
+
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-1.5, 1.5)
+    >>> ax.set_title(r'Chebyshev polynomials $U_n$')
+    >>> for n in np.arange(1,5):
+    ...     ax.plot(x, chebyu(n)(x), label=rf'$U_n={n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    base = jacobi(n, 0.5, 0.5, monic=monic)
+    if monic:
+        return base
+    factor = sqrt(pi) / 2.0 * _gam(n + 2) / _gam(n + 1.5)
+    base._scale(factor)
+    return base
+
+# Chebyshev of the first kind        C_n(x)
+
+
+def roots_chebyc(n, mu=False):
+    r"""Gauss-Chebyshev (first kind) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the first kind, :math:`C_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
+    with weight function :math:`w(x) = 1 / \sqrt{1 - (x/2)^2}`. See
+    22.2.6 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyt(n, True)
+    x *= 2
+    w *= 2
+    m *= 2
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def chebyc(n, monic=False):
+    r"""Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+
+    Defined as :math:`C_n(x) = 2T_n(x/2)`, where :math:`T_n` is the
+    nth Chebychev polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    C : orthopoly1d
+        Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+
+    See Also
+    --------
+    chebyt : Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`C_n(x)` are orthogonal over :math:`[-2, 2]`
+    with weight function :math:`1/\sqrt{1 - (x/2)^2}`.
+
+    References
+    ----------
+    .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
+           Section 22. National Bureau of Standards, 1972.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_chebyc(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 4 * pi * ((n == 0) + 1)
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn,
+                    wfunc=lambda x: 1.0 / sqrt(1 - x * x / 4.0),
+                    limits=(-2, 2), monic=monic)
+    if not monic:
+        p._scale(2.0 / p(2))
+        p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebyc(n, x)
+    return p
+
+# Chebyshev of the second kind       S_n(x)
+
+
+def roots_chebys(n, mu=False):
+    r"""Gauss-Chebyshev (second kind) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the second kind, :math:`S_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
+    with weight function :math:`w(x) = \sqrt{1 - (x/2)^2}`. See 22.2.7
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyu(n, True)
+    x *= 2
+    w *= 2
+    m *= 2
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def chebys(n, monic=False):
+    r"""Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+
+    Defined as :math:`S_n(x) = U_n(x/2)` where :math:`U_n` is the
+    nth Chebychev polynomial of the second kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    S : orthopoly1d
+        Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+
+    See Also
+    --------
+    chebyu : Chebyshev polynomial of the second kind
+
+    Notes
+    -----
+    The polynomials :math:`S_n(x)` are orthogonal over :math:`[-2, 2]`
+    with weight function :math:`\sqrt{1 - (x/2)}^2`.
+
+    References
+    ----------
+    .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
+           Section 22. National Bureau of Standards, 1972.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_chebys(n1)
+    if n == 0:
+        x, w = [], []
+    hn = pi
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn,
+                    wfunc=lambda x: sqrt(1 - x * x / 4.0),
+                    limits=(-2, 2), monic=monic)
+    if not monic:
+        factor = (n + 1.0) / p(2)
+        p._scale(factor)
+        p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebys(n, x)
+    return p
+
+# Shifted Chebyshev of the first kind     T^*_n(x)
+
+
+def roots_sh_chebyt(n, mu=False):
+    r"""Gauss-Chebyshev (first kind, shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    shifted Chebyshev polynomial of the first kind, :math:`T_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
+    with weight function :math:`w(x) = 1/\sqrt{x - x^2}`. See 22.2.8
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    xw = roots_chebyt(n, mu)
+    return ((xw[0] + 1) / 2,) + xw[1:]
+
+
+def sh_chebyt(n, monic=False):
+    r"""Shifted Chebyshev polynomial of the first kind.
+
+    Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth
+    Chebyshev polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    T : orthopoly1d
+        Shifted Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function :math:`(x - x^2)^{-1/2}`.
+
+    """
+    base = sh_jacobi(n, 0.0, 0.5, monic=monic)
+    if monic:
+        return base
+    if n > 0:
+        factor = 4**n / 2.0
+    else:
+        factor = 1.0
+    base._scale(factor)
+    return base
+
+
+# Shifted Chebyshev of the second kind    U^*_n(x)
+def roots_sh_chebyu(n, mu=False):
+    r"""Gauss-Chebyshev (second kind, shifted) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    shifted Chebyshev polynomial of the second kind, :math:`U_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
+    with weight function :math:`w(x) = \sqrt{x - x^2}`. See 22.2.9 in
+    [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyu(n, True)
+    x = (x + 1) / 2
+    m_us = _ufuncs.beta(1.5, 1.5)
+    w *= m_us / m
+    if mu:
+        return x, w, m_us
+    else:
+        return x, w
+
+
+def sh_chebyu(n, monic=False):
+    r"""Shifted Chebyshev polynomial of the second kind.
+
+    Defined as :math:`U^*_n(x) = U_n(2x - 1)` for :math:`U_n` the nth
+    Chebyshev polynomial of the second kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    U : orthopoly1d
+        Shifted Chebyshev polynomial of the second kind.
+
+    Notes
+    -----
+    The polynomials :math:`U^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function :math:`(x - x^2)^{1/2}`.
+
+    """
+    base = sh_jacobi(n, 2.0, 1.5, monic=monic)
+    if monic:
+        return base
+    factor = 4**n
+    base._scale(factor)
+    return base
+
+# Legendre
+
+
+def roots_legendre(n, mu=False):
+    r"""Gauss-Legendre quadrature.
+
+    Compute the sample points and weights for Gauss-Legendre
+    quadrature [GL]_. The sample points are the roots of the nth degree
+    Legendre polynomial :math:`P_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-1, 1]` with weight function
+    :math:`w(x) = 1`. See 2.2.10 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.legendre.leggauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [GL] Gauss-Legendre quadrature, Wikipedia,
+        https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import roots_legendre, eval_legendre
+    >>> roots, weights = roots_legendre(9)
+
+    ``roots`` holds the roots, and ``weights`` holds the weights for
+    Gauss-Legendre quadrature.
+
+    >>> roots
+    array([-0.96816024, -0.83603111, -0.61337143, -0.32425342,  0.        ,
+            0.32425342,  0.61337143,  0.83603111,  0.96816024])
+    >>> weights
+    array([0.08127439, 0.18064816, 0.2606107 , 0.31234708, 0.33023936,
+           0.31234708, 0.2606107 , 0.18064816, 0.08127439])
+
+    Verify that we have the roots by evaluating the degree 9 Legendre
+    polynomial at ``roots``.  All the values are approximately zero:
+
+    >>> eval_legendre(9, roots)
+    array([-8.88178420e-16, -2.22044605e-16,  1.11022302e-16,  1.11022302e-16,
+            0.00000000e+00, -5.55111512e-17, -1.94289029e-16,  1.38777878e-16,
+           -8.32667268e-17])
+
+    Here we'll show how the above values can be used to estimate the
+    integral from 1 to 2 of f(t) = t + 1/t with Gauss-Legendre
+    quadrature [GL]_.  First define the function and the integration
+    limits.
+
+    >>> def f(t):
+    ...    return t + 1/t
+    ...
+    >>> a = 1
+    >>> b = 2
+
+    We'll use ``integral(f(t), t=a, t=b)`` to denote the definite integral
+    of f from t=a to t=b.  The sample points in ``roots`` are from the
+    interval [-1, 1], so we'll rewrite the integral with the simple change
+    of variable::
+
+        x = 2/(b - a) * t - (a + b)/(b - a)
+
+    with inverse::
+
+        t = (b - a)/2 * x + (a + b)/2
+
+    Then::
+
+        integral(f(t), a, b) =
+            (b - a)/2 * integral(f((b-a)/2*x + (a+b)/2), x=-1, x=1)
+
+    We can approximate the latter integral with the values returned
+    by `roots_legendre`.
+
+    Map the roots computed above from [-1, 1] to [a, b].
+
+    >>> t = (b - a)/2 * roots + (a + b)/2
+
+    Approximate the integral as the weighted sum of the function values.
+
+    >>> (b - a)/2 * f(t).dot(weights)
+    2.1931471805599276
+
+    Compare that to the exact result, which is 3/2 + log(2):
+
+    >>> 1.5 + np.log(2)
+    2.1931471805599454
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = 2.0
+    def an_func(k):
+        return 0.0 * k
+    def bn_func(k):
+        return k * np.sqrt(1.0 / (4 * k * k - 1))
+    f = _ufuncs.eval_legendre
+    def df(n, x):
+        return (-n * x * _ufuncs.eval_legendre(n, x)
+                + n * _ufuncs.eval_legendre(n - 1, x)) / (1 - x ** 2)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+
+
+def legendre(n, monic=False):
+    r"""Legendre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        \frac{d}{dx}\left[(1 - x^2)\frac{d}{dx}P_n(x)\right]
+          + n(n + 1)P_n(x) = 0;
+
+    :math:`P_n(x)` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Legendre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`P_n` are orthogonal over :math:`[-1, 1]`
+    with weight function 1.
+
+    Examples
+    --------
+    Generate the 3rd-order Legendre polynomial 1/2*(5x^3 + 0x^2 - 3x + 0):
+
+    >>> from scipy.special import legendre
+    >>> legendre(3)
+    poly1d([ 2.5,  0. , -1.5,  0. ])
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_legendre(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 2.0 / (2 * n + 1)
+    kn = _gam(2 * n + 1) / _gam(n + 1)**2 / 2.0**n
+    p = orthopoly1d(x, w, hn, kn, wfunc=lambda x: 1.0, limits=(-1, 1),
+                    monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_legendre(n, x))
+    return p
+
+# Shifted Legendre              P^*_n(x)
+
+
+def roots_sh_legendre(n, mu=False):
+    r"""Gauss-Legendre (shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Legendre
+    quadrature. The sample points are the roots of the nth degree
+    shifted Legendre polynomial :math:`P^*_n(x)`. These sample points
+    and weights correctly integrate polynomials of degree :math:`2n -
+    1` or less over the interval :math:`[0, 1]` with weight function
+    :math:`w(x) = 1.0`. See 2.2.11 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w = roots_legendre(n)
+    x = (x + 1) / 2
+    w /= 2
+    if mu:
+        return x, w, 1.0
+    else:
+        return x, w
+
+
+def sh_legendre(n, monic=False):
+    r"""Shifted Legendre polynomial.
+
+    Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth
+    Legendre polynomial.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Shifted Legendre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function 1.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return 0.0 * x + 1.0
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (0, 1), monic,
+                           lambda x: _ufuncs.eval_sh_legendre(n, x))
+    x, w = roots_sh_legendre(n)
+    hn = 1.0 / (2 * n + 1.0)
+    kn = _gam(2 * n + 1) / _gam(n + 1)**2
+    p = orthopoly1d(x, w, hn, kn, wfunc, limits=(0, 1), monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_sh_legendre(n, x))
+    return p
+
+
+# Make the old root function names an alias for the new ones
+_modattrs = globals()
+for newfun, oldfun in _rootfuns_map.items():
+    _modattrs[oldfun] = _modattrs[newfun]
+    __all__.append(oldfun)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi b/venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e0ae3ce3be90187cd957fe16cc6d145a7093da5a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi
@@ -0,0 +1,330 @@
+from typing import (
+    Any,
+    Callable,
+    Literal,
+    Optional,
+    overload,
+)
+
+import numpy as np
+
+_IntegerType = int | np.integer
+_FloatingType = float | np.floating
+_PointsAndWeights = tuple[np.ndarray, np.ndarray]
+_PointsAndWeightsAndMu = tuple[np.ndarray, np.ndarray, float]
+
+_ArrayLike0D = bool | int | float | complex | str | bytes | np.generic
+
+__all__ = [
+    'legendre',
+    'chebyt',
+    'chebyu',
+    'chebyc',
+    'chebys',
+    'jacobi',
+    'laguerre',
+    'genlaguerre',
+    'hermite',
+    'hermitenorm',
+    'gegenbauer',
+    'sh_legendre',
+    'sh_chebyt',
+    'sh_chebyu',
+    'sh_jacobi',
+    'roots_legendre',
+    'roots_chebyt',
+    'roots_chebyu',
+    'roots_chebyc',
+    'roots_chebys',
+    'roots_jacobi',
+    'roots_laguerre',
+    'roots_genlaguerre',
+    'roots_hermite',
+    'roots_hermitenorm',
+    'roots_gegenbauer',
+    'roots_sh_legendre',
+    'roots_sh_chebyt',
+    'roots_sh_chebyu',
+    'roots_sh_jacobi',
+]
+
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_laguerre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_laguerre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_laguerre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_hermite(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_hermite(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_hermite(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_hermitenorm(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_hermitenorm(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_hermitenorm(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyt(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyt(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyu(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyu(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyc(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyc(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyc(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebys(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebys(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebys(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyt(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyt(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyu(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyu(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_legendre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_legendre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_legendre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_legendre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_legendre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_legendre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+class orthopoly1d(np.poly1d):
+    def __init__(
+            self,
+            roots: np.typing.ArrayLike,
+            weights: np.typing.ArrayLike | None,
+            hn: float = ...,
+            kn: float = ...,
+            wfunc = Optional[Callable[[float], float]],  # noqa: UP007
+            limits = tuple[float, float] | None,
+            monic: bool = ...,
+            eval_func: np.ufunc = ...,
+    ) -> None: ...
+    @property
+    def limits(self) -> tuple[float, float]: ...
+    def weight_func(self, x: float) -> float: ...
+    @overload
+    def __call__(self, x: _ArrayLike0D) -> Any: ...
+    @overload
+    def __call__(self, x: np.poly1d) -> np.poly1d: ...  # type: ignore[overload-overlap]
+    @overload
+    def __call__(self, x: np.typing.ArrayLike) -> np.ndarray: ...
+
+def legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyc(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebys(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def laguerre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def hermite(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def hermitenorm(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def sh_legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_jacobi(
+        n: _IntegerType,
+        p: _FloatingType,
+        q: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+
+# These functions are not public, but still need stubs because they
+# get checked in the tests.
+def _roots_hermite_asy(n: _IntegerType) -> _PointsAndWeights: ...
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab5dd6daa5dd2f2bf70b9115929a2f31cd4421a2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f50feb02f134e4228e2572be1d5512c626c170a0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4dde50cc71dcef1d58781b20f4ef5f73784ff106
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f38dea8332c07aeaf85245d6d098a0f4f72065f4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7b3a7e2db63936e3dc5c75c2168791cd84b1eec
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20f48ba8701f61938c379888b8eaf9c8f6601786
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25bfe648894cde336145aa182634090729eef08e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75e19d6300bee56d28be81cebbc3b2bdddfaa51a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c6a41824d32be35945c145a9c0efabd26043a5b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..222a57ae767a397955834a87ff5a5bc738dcb075
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eee1952fa1ee5f76518afc03969420ea6220c0e6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d651f2f68eaf23fa825948fd8aabb08abbc5f148
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52604adb1060d3236833b378a128be8335f386c8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bed53ec15bc611832aa68191a8388bcc3967ab09
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..662c12bc74b31478c87471fbd1cce8bea285e765
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py
@@ -0,0 +1,17 @@
+import mpmath
+
+
+def f(x):
+    return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi)
+
+
+# Note: 40 digits might be overkill; a few more digits than the default
+# might be sufficient.
+mpmath.mp.dps = 40
+ts = mpmath.taylor(f, -mpmath.pi, 20)
+p, q = mpmath.pade(ts, 9, 10)
+
+p = [float(c) for c in p]
+q = [float(c) for c in q]
+print('p =', p)
+print('q =', q)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..3491b8acd588a2cacfc48f0a3a60c6ae88c3e8c5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py
@@ -0,0 +1,54 @@
+"""Precompute the polynomials for the asymptotic expansion of the
+generalized exponential integral.
+
+Sources
+-------
+[1] NIST, Digital Library of Mathematical Functions,
+    https://dlmf.nist.gov/8.20#ii
+
+"""
+import os
+
+try:
+    import sympy
+    from sympy import Poly
+    x = sympy.symbols('x')
+except ImportError:
+    pass
+
+
+def generate_A(K):
+    A = [Poly(1, x)]
+    for k in range(K):
+        A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff())
+    return A
+
+
+WARNING = """\
+/* This file was automatically generated by _precompute/expn_asy.py.
+ * Do not edit it manually!
+ */
+"""
+
+
+def main():
+    print(__doc__)
+    fn = os.path.join('..', 'cephes', 'expn.h')
+
+    K = 12
+    A = generate_A(K)
+    with open(fn + '.new', 'w') as f:
+        f.write(WARNING)
+        f.write(f"#define nA {len(A)}\n")
+        for k, Ak in enumerate(A):
+            ', '.join([str(x.evalf(18)) for x in Ak.coeffs()])
+            f.write(f"static const double A{k}[] = {{tmp}};\n")
+        ", ".join([f"A{k}" for k in range(K + 1)])
+        f.write("static const double *A[] = {{tmp}};\n")
+        ", ".join([str(Ak.degree()) for Ak in A])
+        f.write("static const int Adegs[] = {{tmp}};\n")
+    os.rename(fn + '.new', fn)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..98035457c78706ae01c02273ae1ab458b4ca140d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py
@@ -0,0 +1,116 @@
+"""
+Precompute coefficients of Temme's asymptotic expansion for gammainc.
+
+This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram.
+
+Sources:
+[1] NIST, "Digital Library of Mathematical Functions",
+    https://dlmf.nist.gov/
+
+"""
+import os
+from scipy.special._precompute.utils import lagrange_inversion
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+
+def compute_a(n):
+    """a_k from DLMF 5.11.6"""
+    a = [mp.sqrt(2)/2]
+    for k in range(1, n):
+        ak = a[-1]/k
+        for j in range(1, len(a)):
+            ak -= a[j]*a[-j]/(j + 1)
+        ak /= a[0]*(1 + mp.mpf(1)/(k + 1))
+        a.append(ak)
+    return a
+
+
+def compute_g(n):
+    """g_k from DLMF 5.11.3/5.11.5"""
+    a = compute_a(2*n)
+    g = [mp.sqrt(2)*mp.rf(0.5, k)*a[2*k] for k in range(n)]
+    return g
+
+
+def eta(lam):
+    """Function from DLMF 8.12.1 shifted to be centered at 0."""
+    if lam > 0:
+        return mp.sqrt(2*(lam - mp.log(lam + 1)))
+    elif lam < 0:
+        return -mp.sqrt(2*(lam - mp.log(lam + 1)))
+    else:
+        return 0
+
+
+def compute_alpha(n):
+    """alpha_n from DLMF 8.12.13"""
+    coeffs = mp.taylor(eta, 0, n - 1)
+    return lagrange_inversion(coeffs)
+
+
+def compute_d(K, N):
+    """d_{k, n} from DLMF 8.12.12"""
+    M = N + 2*K
+    d0 = [-mp.mpf(1)/3]
+    alpha = compute_alpha(M + 2)
+    for n in range(1, M):
+        d0.append((n + 2)*alpha[n+2])
+    d = [d0]
+    g = compute_g(K)
+    for k in range(1, K):
+        dk = []
+        for n in range(M - 2*k):
+            dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2])
+        d.append(dk)
+    for k in range(K):
+        d[k] = d[k][:N]
+    return d
+
+
+header = \
+r"""/* This file was automatically generated by _precomp/gammainc.py.
+ * Do not edit it manually!
+ */
+
+#ifndef IGAM_H
+#define IGAM_H
+
+#define K {}
+#define N {}
+
+static const double d[K][N] =
+{{"""
+
+footer = \
+r"""
+#endif
+"""
+
+
+def main():
+    print(__doc__)
+    K = 25
+    N = 25
+    with mp.workdps(50):
+        d = compute_d(K, N)
+    fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h')
+    with open(fn + '.new', 'w') as f:
+        f.write(header.format(K, N))
+        for k, row in enumerate(d):
+            row = [mp.nstr(x, 17, min_fixed=0, max_fixed=0) for x in row]
+            f.write('{')
+            f.write(", ".join(row))
+            if k < K - 1:
+                f.write('},\n')
+            else:
+                f.write('}};\n')
+        f.write(footer)
+    os.rename(fn + '.new', fn)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebbe39f6159fb80c424dbb38eedeba46bd8cccf2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py
@@ -0,0 +1,124 @@
+"""Compute gammainc and gammaincc for large arguments and parameters
+and save the values to data files for use in tests. We can't just
+compare to mpmath's gammainc in test_mpmath.TestSystematic because it
+would take too long.
+
+Note that mpmath's gammainc is computed using hypercomb, but since it
+doesn't allow the user to increase the maximum number of terms used in
+the series it doesn't converge for many arguments. To get around this
+we copy the mpmath implementation but use more terms.
+
+This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB
+ram.
+
+Sources:
+[1] Fredrik Johansson and others. mpmath: a Python library for
+    arbitrary-precision floating-point arithmetic (version 0.19),
+    December 2013. http://mpmath.org/.
+
+"""
+import os
+from time import time
+import numpy as np
+from numpy import pi
+
+from scipy.special._mptestutils import mpf2float
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+
+def gammainc(a, x, dps=50, maxterms=10**8):
+    """Compute gammainc exactly like mpmath does but allow for more
+    summands in hypercomb. See
+
+    mpmath/functions/expintegrals.py#L134
+
+    in the mpmath GitHub repository.
+
+    """
+    with mp.workdps(dps):
+        z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x)
+        G = [z]
+        negb = mp.fneg(b, exact=True)
+
+        def h(z):
+            T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b
+            return (T1,)
+
+        res = mp.hypercomb(h, [z], maxterms=maxterms)
+        return mpf2float(res)
+
+
+def gammaincc(a, x, dps=50, maxterms=10**8):
+    """Compute gammaincc exactly like mpmath does but allow for more
+    terms in hypercomb. See
+
+    mpmath/functions/expintegrals.py#L187
+
+    in the mpmath GitHub repository.
+
+    """
+    with mp.workdps(dps):
+        z, a = a, x
+
+        if mp.isint(z):
+            try:
+                # mpmath has a fast integer path
+                return mpf2float(mp.gammainc(z, a=a, regularized=True))
+            except mp.libmp.NoConvergence:
+                pass
+        nega = mp.fneg(a, exact=True)
+        G = [z]
+        # Use 2F0 series when possible; fall back to lower gamma representation
+        try:
+            def h(z):
+                r = z-1
+                return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]
+            return mpf2float(mp.hypercomb(h, [z], force_series=True))
+        except mp.libmp.NoConvergence:
+            def h(z):
+                T1 = [], [1, z-1], [z], G, [], [], 0
+                T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a
+                return T1, T2
+            return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
+
+
+def main():
+    t0 = time()
+    # It would be nice to have data for larger values, but either this
+    # requires prohibitively large precision (dps > 800) or mpmath has
+    # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a
+    # value around 0.03, while the true value should be close to 0.5
+    # (DLMF 8.12.15).
+    print(__doc__)
+    pwd = os.path.dirname(__file__)
+    r = np.logspace(4, 14, 30)
+    ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30)
+    utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30)
+
+    regimes = [(gammainc, ltheta), (gammaincc, utheta)]
+    for func, theta in regimes:
+        rg, thetag = np.meshgrid(r, theta)
+        a, x = rg*np.cos(thetag), rg*np.sin(thetag)
+        a, x = a.flatten(), x.flatten()
+        dataset = []
+        for i, (a0, x0) in enumerate(zip(a, x)):
+            if func == gammaincc:
+                # Exploit the fast integer path in gammaincc whenever
+                # possible so that the computation doesn't take too
+                # long
+                a0, x0 = np.floor(a0), np.floor(x0)
+            dataset.append((a0, x0, func(a0, x0)))
+        dataset = np.array(dataset)
+        filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
+                                f'{func.__name__}.txt')
+        np.savetxt(filename, dataset)
+
+    print(f"{(time() - t0)/60} minutes elapsed")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4adf14f49184bf75048a28a823909d24e778e04
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py
@@ -0,0 +1,484 @@
+"""This script evaluates scipy's implementation of hyp2f1 against mpmath's.
+
+Author: Albert Steppi
+
+This script is long running and generates a large output file. With default
+arguments, the generated file is roughly 700MB in size and it takes around
+40 minutes using an Intel(R) Core(TM) i5-8250U CPU with n_jobs set to 8
+(full utilization). There are optional arguments which can be used to restrict
+(or enlarge) the computations performed. These are described below.
+The output of this script can be analyzed to identify suitable test cases and
+to find parameter and argument regions where hyp2f1 needs to be improved.
+
+The script has one mandatory positional argument for specifying the path to
+the location where the output file is to be placed, and 4 optional arguments
+--n_jobs, --grid_size, --regions, and --parameter_groups. --n_jobs specifies
+the number of processes to use if running in parallel. The default value is 1.
+The other optional arguments are explained below.
+
+Produces a tab separated values file with 11 columns. The first four columns
+contain the parameters a, b, c and the argument z. The next two contain |z| and
+a region code for which region of the complex plane belongs to. The regions are
+
+    0) z == 1
+    1) |z| < 0.9 and real(z) >= 0
+    2) |z| <= 1 and real(z) < 0
+    3) 0.9 <= |z| <= 1 and |1 - z| < 0.9:
+    4) 0.9 <= |z| <= 1 and |1 - z| >= 0.9 and real(z) >= 0:
+    5) 1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0
+    6) |z| > 1 and not in 5)
+
+The --regions optional argument allows the user to specify a list of regions
+to which computation will be restricted.
+
+Parameters a, b, c are taken from a 10 * 10 * 10 grid with values at
+
+    -16, -8, -4, -2, -1, 1, 2, 4, 8, 16
+
+with random perturbations applied.
+
+There are 9 parameter groups handling the following cases.
+
+    1) A, B, C, B - A, C - A, C - B, C - A - B all non-integral.
+    2) B - A integral
+    3) C - A integral
+    4) C - B integral
+    5) C - A - B integral
+    6) A integral
+    7) B integral
+    8) C integral
+    9) Wider range with c - a - b > 0.
+
+The seventh column of the output file is an integer between 1 and 8 specifying
+the parameter group as above.
+
+The --parameter_groups optional argument allows the user to specify a list of
+parameter groups to which computation will be restricted.
+
+The argument z is taken from a grid in the box
+    -box_size <= real(z) <= box_size, -box_size <= imag(z) <= box_size.
+with grid size specified using the optional command line argument --grid_size,
+and box_size specified with the command line argument --box_size.
+The default value of grid_size is 20 and the default value of box_size is 2.0,
+yielding a 20 * 20 grid in the box with corners -2-2j, -2+2j, 2-2j, 2+2j.
+
+The final four columns have the expected value of hyp2f1 for the given
+parameters and argument as calculated with mpmath, the observed value
+calculated with scipy's hyp2f1, the relative error, and the absolute error.
+
+As special cases of hyp2f1 are moved from the original Fortran implementation
+into Cython, this script can be used to ensure that no regressions occur and
+to point out where improvements are needed.
+"""
+
+
+import os
+import csv
+import argparse
+import numpy as np
+from itertools import product
+from multiprocessing import Pool
+
+
+from scipy.special import hyp2f1
+from scipy.special.tests.test_hyp2f1 import mp_hyp2f1
+
+
+def get_region(z):
+    """Assign numbers for regions where hyp2f1 must be handled differently."""
+    if z == 1 + 0j:
+        return 0
+    elif abs(z) < 0.9 and z.real >= 0:
+        return 1
+    elif abs(z) <= 1 and z.real < 0:
+        return 2
+    elif 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9:
+        return 3
+    elif 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9:
+        return 4
+    elif 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0:
+        return 5
+    else:
+        return 6
+
+
+def get_result(a, b, c, z, group):
+    """Get results for given parameter and value combination."""
+    expected, observed = mp_hyp2f1(a, b, c, z), hyp2f1(a, b, c, z)
+    if (
+            np.isnan(observed) and np.isnan(expected) or
+            expected == observed
+    ):
+        relative_error = 0.0
+        absolute_error = 0.0
+    elif np.isnan(observed):
+        # Set error to infinity if result is nan when not expected to be.
+        # Makes results easier to interpret.
+        relative_error = float("inf")
+        absolute_error = float("inf")
+    else:
+        absolute_error = abs(expected - observed)
+        relative_error = absolute_error / abs(expected)
+
+    return (
+        a,
+        b,
+        c,
+        z,
+        abs(z),
+        get_region(z),
+        group,
+        expected,
+        observed,
+        relative_error,
+        absolute_error,
+    )
+
+
+def get_result_no_mp(a, b, c, z, group):
+    """Get results for given parameter and value combination."""
+    expected, observed = complex('nan'), hyp2f1(a, b, c, z)
+    relative_error, absolute_error = float('nan'), float('nan')
+    return (
+        a,
+        b,
+        c,
+        z,
+        abs(z),
+        get_region(z),
+        group,
+        expected,
+        observed,
+        relative_error,
+        absolute_error,
+    )
+
+
+def get_results(params, Z, n_jobs=1, compute_mp=True):
+    """Batch compute results for multiple parameter and argument values.
+
+    Parameters
+    ----------
+    params : iterable
+        iterable of tuples of floats (a, b, c) specifying parameter values
+        a, b, c for hyp2f1
+    Z : iterable of complex
+        Arguments at which to evaluate hyp2f1
+    n_jobs : Optional[int]
+        Number of jobs for parallel execution.
+
+    Returns
+    -------
+    list
+        List of tuples of results values. See return value in source code
+        of `get_result`.
+    """
+    input_ = (
+        (a, b, c, z, group) for (a, b, c, group), z in product(params, Z)
+    )
+
+    with Pool(n_jobs) as pool:
+        rows = pool.starmap(
+            get_result if compute_mp else get_result_no_mp,
+            input_
+        )
+    return rows
+
+
+def _make_hyp2f1_test_case(a, b, c, z, rtol):
+    """Generate string for single test case as used in test_hyp2f1.py."""
+    expected = mp_hyp2f1(a, b, c, z)
+    return (
+        "    pytest.param(\n"
+        "        Hyp2f1TestCase(\n"
+        f"            a={a},\n"
+        f"            b={b},\n"
+        f"            c={c},\n"
+        f"            z={z},\n"
+        f"            expected={expected},\n"
+        f"            rtol={rtol},\n"
+        "        ),\n"
+        "    ),"
+    )
+
+
+def make_hyp2f1_test_cases(rows):
+    """Generate string for a list of test cases for test_hyp2f1.py.
+
+    Parameters
+    ----------
+    rows : list
+        List of lists of the form [a, b, c, z, rtol] where a, b, c, z are
+        parameters and the argument for hyp2f1 and rtol is an expected
+        relative error for the associated test case.
+
+    Returns
+    -------
+    str
+        String for a list of test cases. The output string can be printed
+        or saved to a file and then copied into an argument for
+        `pytest.mark.parameterize` within `scipy.special.tests.test_hyp2f1.py`.
+    """
+    result = "[\n"
+    result += '\n'.join(
+        _make_hyp2f1_test_case(a, b, c, z, rtol)
+        for a, b, c, z, rtol in rows
+    )
+    result += "\n]"
+    return result
+
+
+def main(
+        outpath,
+        n_jobs=1,
+        box_size=2.0,
+        grid_size=20,
+        regions=None,
+        parameter_groups=None,
+        compute_mp=True,
+):
+    outpath = os.path.realpath(os.path.expanduser(outpath))
+
+    random_state = np.random.RandomState(1234)
+    # Parameters a, b, c selected near these values.
+    root_params = np.array(
+        [-16, -8, -4, -2, -1, 1, 2, 4, 8, 16]
+    )
+    # Perturbations to apply to root values.
+    perturbations = 0.1 * random_state.random_sample(
+        size=(3, len(root_params))
+    )
+
+    params = []
+    # Parameter group 1
+    # -----------------
+    # No integer differences. This has been confirmed for the above seed.
+    A = root_params + perturbations[0, :]
+    B = root_params + perturbations[1, :]
+    C = root_params + perturbations[2, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 1) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 2
+    # -----------------
+    # B - A an integer
+    A = root_params + 0.5
+    B = root_params + 0.5
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 2) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 3
+    # -----------------
+    # C - A an integer
+    A = root_params + 0.5
+    B = root_params + perturbations[1, :]
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 3) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 4
+    # -----------------
+    # C - B an integer
+    A = root_params + perturbations[0, :]
+    B = root_params + 0.5
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 4) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 5
+    # -----------------
+    # C - A - B an integer
+    A = root_params + 0.25
+    B = root_params + 0.25
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 5) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 6
+    # -----------------
+    # A an integer
+    A = root_params
+    B = root_params + perturbations[0, :]
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 6) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 7
+    # -----------------
+    # B an integer
+    A = root_params + perturbations[0, :]
+    B = root_params
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 7) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 8
+    # -----------------
+    # C an integer
+    A = root_params + perturbations[0, :]
+    B = root_params + perturbations[1, :]
+    C = root_params
+    params.extend(
+        sorted(
+            ((a, b, c, 8) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 9
+    # -----------------
+    # Wide range of magnitudes, c - a - b > 0.
+    phi = (1 + np.sqrt(5))/2
+    P = phi**np.arange(16)
+    P = np.hstack([-P, P])
+    group_9_params = sorted(
+        (
+            (a, b, c, 9) for a, b, c in product(P, P, P) if c - a - b > 0
+        ),
+        key=lambda x: max(abs(x[0]), abs(x[1])),
+    )
+
+    if parameter_groups is not None:
+        # Group 9 params only used if specified in arguments.
+        params.extend(group_9_params)
+        params = [
+            (a, b, c, group) for a, b, c, group in params
+            if group in parameter_groups
+        ]
+
+    # grid_size * grid_size grid in box with corners
+    # -2 - 2j, -2 + 2j, 2 - 2j, 2 + 2j
+    X, Y = np.meshgrid(
+        np.linspace(-box_size, box_size, grid_size),
+        np.linspace(-box_size, box_size, grid_size)
+    )
+    Z = X + Y * 1j
+    Z = Z.flatten().tolist()
+    # Add z = 1 + 0j (region 0).
+    Z.append(1 + 0j)
+    if regions is not None:
+        Z = [z for z in Z if get_region(z) in regions]
+
+    # Evaluate scipy and mpmath's hyp2f1 for all parameter combinations
+    # above against all arguments in the grid Z
+    rows = get_results(params, Z, n_jobs=n_jobs, compute_mp=compute_mp)
+
+    with open(outpath, "w", newline="") as f:
+        writer = csv.writer(f, delimiter="\t")
+        writer.writerow(
+            [
+                "a",
+                "b",
+                "c",
+                "z",
+                "|z|",
+                "region",
+                "parameter_group",
+                "expected",  # mpmath's hyp2f1
+                "observed",  # scipy's hyp2f1
+                "relative_error",
+                "absolute_error",
+            ]
+        )
+        for row in rows:
+            writer.writerow(row)
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(
+        description="Test scipy's hyp2f1 against mpmath's on a grid in the"
+        " complex plane over a grid of parameter values. Saves output to file"
+        " specified in positional argument \"outpath\"."
+        " Caution: With default arguments, the generated output file is"
+        " roughly 700MB in size. Script may take several hours to finish if"
+        " \"--n_jobs\" is set to 1."
+    )
+    parser.add_argument(
+        "outpath", type=str, help="Path to output tsv file."
+    )
+    parser.add_argument(
+        "--n_jobs",
+        type=int,
+        default=1,
+        help="Number of jobs for multiprocessing.",
+    )
+    parser.add_argument(
+        "--box_size",
+        type=float,
+        default=2.0,
+        help="hyp2f1 is evaluated in box of side_length 2*box_size centered"
+        " at the origin."
+    )
+    parser.add_argument(
+        "--grid_size",
+        type=int,
+        default=20,
+        help="hyp2f1 is evaluated on grid_size * grid_size grid in box of side"
+        " length 2*box_size centered at the origin."
+    )
+    parser.add_argument(
+        "--parameter_groups",
+        type=int,
+        nargs='+',
+        default=None,
+        help="Restrict to supplied parameter groups. See the Docstring for"
+        " this module for more info on parameter groups. Calculate for all"
+        " parameter groups by default."
+    )
+    parser.add_argument(
+        "--regions",
+        type=int,
+        nargs='+',
+        default=None,
+        help="Restrict to argument z only within the supplied regions. See"
+        " the Docstring for this module for more info on regions. Calculate"
+        " for all regions by default."
+    )
+    parser.add_argument(
+        "--no_mp",
+        action='store_true',
+        help="If this flag is set, do not compute results with mpmath. Saves"
+        " time if results have already been computed elsewhere. Fills in"
+        " \"expected\" column with None values."
+    )
+    args = parser.parse_args()
+    compute_mp = not args.no_mp
+    print(args.parameter_groups)
+    main(
+        args.outpath,
+        n_jobs=args.n_jobs,
+        box_size=args.box_size,
+        grid_size=args.grid_size,
+        parameter_groups=args.parameter_groups,
+        regions=args.regions,
+        compute_mp=compute_mp,
+    )
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdbf35b2cf85f1f7a6e73579546ed5cfe508fa6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py
@@ -0,0 +1,68 @@
+"""Compute a Pade approximation for the principal branch of the
+Lambert W function around 0 and compare it to various other
+approximations.
+
+"""
+import numpy as np
+
+try:
+    import mpmath
+    import matplotlib.pyplot as plt
+except ImportError:
+    pass
+
+
+def lambertw_pade():
+    derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)]
+    p, q = mpmath.pade(derivs, 3, 2)
+    return p, q
+
+
+def main():
+    print(__doc__)
+    with mpmath.workdps(50):
+        p, q = lambertw_pade()
+        p, q = p[::-1], q[::-1]
+        print(f"p = {p}")
+        print(f"q = {q}")
+
+    x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    lambertw_std = []
+    for z0 in z.flatten():
+        lambertw_std.append(complex(mpmath.lambertw(z0)))
+    lambertw_std = np.array(lambertw_std).reshape(x.shape)
+
+    fig, axes = plt.subplots(nrows=3, ncols=1)
+    # Compare Pade approximation to true result
+    p = np.array([float(p0) for p0 in p])
+    q = np.array([float(q0) for q0 in q])
+    pade_approx = np.polyval(p, z)/np.polyval(q, z)
+    pade_err = abs(pade_approx - lambertw_std)
+    axes[0].pcolormesh(x, y, pade_err)
+    # Compare two terms of asymptotic series to true result
+    asy_approx = np.log(z) - np.log(np.log(z))
+    asy_err = abs(asy_approx - lambertw_std)
+    axes[1].pcolormesh(x, y, asy_err)
+    # Compare two terms of the series around the branch point to the
+    # true result
+    p = np.sqrt(2*(np.exp(1)*z + 1))
+    series_approx = -1 + p - p**2/3
+    series_err = abs(series_approx - lambertw_std)
+    im = axes[2].pcolormesh(x, y, series_err)
+
+    fig.colorbar(im, ax=axes.ravel().tolist())
+    plt.show()
+
+    fig, ax = plt.subplots(nrows=1, ncols=1)
+    pade_better = pade_err < asy_err
+    im = ax.pcolormesh(x, y, pade_better)
+    t = np.linspace(-0.3, 0.3)
+    ax.plot(-2.5*abs(t) - 0.2, t, 'r')
+    fig.colorbar(im, ax=ax)
+    plt.show()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..74051ac7b46c70dc01919a362d05a8bbbe11333a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py
@@ -0,0 +1,43 @@
+"""Precompute series coefficients for log-Gamma."""
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def stirling_series(N):
+    with mpmath.workdps(100):
+        coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1))
+                  for n in range(1, N + 1)]
+    return coeffs
+
+
+def taylor_series_at_1(N):
+    coeffs = []
+    with mpmath.workdps(100):
+        coeffs.append(-mpmath.euler)
+        for n in range(2, N + 1):
+            coeffs.append((-1)**n*mpmath.zeta(n)/n)
+    return coeffs
+
+
+def main():
+    print(__doc__)
+    print()
+    stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+                       for x in stirling_series(8)[::-1]]
+    taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+                     for x in taylor_series_at_1(23)[::-1]]
+    print("Stirling series coefficients")
+    print("----------------------------")
+    print("\n".join(stirling_coeffs))
+    print()
+    print("Taylor series coefficients")
+    print("--------------------------")
+    print("\n".join(taylor_coeffs))
+    print()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbf6009368540dbf603b61f5b72510f0acd1a65b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py
@@ -0,0 +1,131 @@
+"""
+Convergence regions of the expansions used in ``struve.c``
+
+Note that for v >> z both functions tend rapidly to 0,
+and for v << -z, they tend to infinity.
+
+The floating-point functions over/underflow in the lower left and right
+corners of the figure.
+
+
+Figure legend
+=============
+
+Red region
+    Power series is close (1e-12) to the mpmath result
+
+Blue region
+    Asymptotic series is close to the mpmath result
+
+Green region
+    Bessel series is close to the mpmath result
+
+Dotted colored lines
+    Boundaries of the regions
+
+Solid colored lines
+    Boundaries estimated by the routine itself. These will be used
+    for determining which of the results to use.
+
+Black dashed line
+    The line z = 0.7*|v| + 12
+
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+
+import mpmath
+
+
+def err_metric(a, b, atol=1e-290):
+    m = abs(a - b) / (atol + abs(b))
+    m[np.isinf(b) & (a == b)] = 0
+    return m
+
+
+def do_plot(is_h=True):
+    from scipy.special._ufuncs import (_struve_power_series,
+                                       _struve_asymp_large_z,
+                                       _struve_bessel_series)
+
+    vs = np.linspace(-1000, 1000, 91)
+    zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]])
+
+    rp = _struve_power_series(vs[:,None], zs[None,:], is_h)
+    ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h)
+    rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h)
+
+    mpmath.mp.dps = 50
+    if is_h:
+        def sh(v, z):
+            return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z)))
+    else:
+        def sh(v, z):
+            return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z)))
+    ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:])
+
+    err_a = err_metric(ra[0], ex) + 1e-300
+    err_p = err_metric(rp[0], ex) + 1e-300
+    err_b = err_metric(rb[0], ex) + 1e-300
+
+    err_est_a = abs(ra[1]/ra[0])
+    err_est_p = abs(rp[1]/rp[0])
+    err_est_b = abs(rb[1]/rb[0])
+
+    z_cutoff = 0.7*abs(vs) + 12
+
+    levels = [-1000, -12]
+
+    plt.cla()
+
+    plt.hold(1)
+    plt.contourf(vs, zs, np.log10(err_p).T,
+                 levels=levels, colors=['r', 'r'], alpha=0.1)
+    plt.contourf(vs, zs, np.log10(err_a).T,
+                 levels=levels, colors=['b', 'b'], alpha=0.1)
+    plt.contourf(vs, zs, np.log10(err_b).T,
+                 levels=levels, colors=['g', 'g'], alpha=0.1)
+
+    plt.contour(vs, zs, np.log10(err_p).T,
+                levels=levels, colors=['r', 'r'], linestyles=[':', ':'])
+    plt.contour(vs, zs, np.log10(err_a).T,
+                levels=levels, colors=['b', 'b'], linestyles=[':', ':'])
+    plt.contour(vs, zs, np.log10(err_b).T,
+                levels=levels, colors=['g', 'g'], linestyles=[':', ':'])
+
+    lp = plt.contour(vs, zs, np.log10(err_est_p).T,
+                     levels=levels, colors=['r', 'r'], linestyles=['-', '-'])
+    la = plt.contour(vs, zs, np.log10(err_est_a).T,
+                     levels=levels, colors=['b', 'b'], linestyles=['-', '-'])
+    lb = plt.contour(vs, zs, np.log10(err_est_b).T,
+                     levels=levels, colors=['g', 'g'], linestyles=['-', '-'])
+
+    plt.clabel(lp, fmt={-1000: 'P', -12: 'P'})
+    plt.clabel(la, fmt={-1000: 'A', -12: 'A'})
+    plt.clabel(lb, fmt={-1000: 'B', -12: 'B'})
+
+    plt.plot(vs, z_cutoff, 'k--')
+
+    plt.xlim(vs.min(), vs.max())
+    plt.ylim(zs.min(), zs.max())
+
+    plt.xlabel('v')
+    plt.ylabel('z')
+
+
+def main():
+    plt.clf()
+    plt.subplot(121)
+    do_plot(True)
+    plt.title('Struve H')
+
+    plt.subplot(122)
+    do_plot(False)
+    plt.title('Struve L')
+
+    plt.savefig('struve_convergence.png')
+    plt.show()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..55cf4083ed5e5a6628fd3316c02ce1a5ce21a92c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py
@@ -0,0 +1,38 @@
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+try:
+    from sympy.abc import x
+except ImportError:
+    pass
+
+
+def lagrange_inversion(a):
+    """Given a series
+
+    f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
+
+    use the Lagrange inversion formula to compute a series
+
+    g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
+
+    so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
+    necessarily b[0] = 0 too.
+
+    The algorithm is naive and could be improved, but speed isn't an
+    issue here and it's easy to read.
+
+    """
+    n = len(a)
+    f = sum(a[i]*x**i for i in range(n))
+    h = (x/f).series(x, 0, n).removeO()
+    hpower = [h**0]
+    for k in range(n):
+        hpower.append((hpower[-1]*h).expand())
+    b = [mp.mpf(0)]
+    for k in range(1, n):
+        b.append(hpower[k].coeff(x, k - 1)/k)
+    b = [mp.mpf(x) for x in b]
+    return b
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..51d56b1cd5c47c7ef005d21aad9827a1e85ec0d9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py
@@ -0,0 +1,342 @@
+"""Precompute coefficients of several series expansions
+of Wright's generalized Bessel function Phi(a, b, x).
+
+See https://dlmf.nist.gov/10.46.E1 with rho=a, beta=b, z=x.
+"""
+from argparse import ArgumentParser, RawTextHelpFormatter
+import numpy as np
+from scipy.integrate import quad
+from scipy.optimize import minimize_scalar, curve_fit
+from time import time
+
+try:
+    import sympy
+    from sympy import EulerGamma, Rational, S, Sum, \
+        factorial, gamma, gammasimp, pi, polygamma, symbols, zeta
+    from sympy.polys.polyfuncs import horner
+except ImportError:
+    pass
+
+
+def series_small_a():
+    """Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.
+    """
+    order = 5
+    a, b, x, k = symbols("a b x k")
+    A = []  # terms with a
+    X = []  # terms with x
+    B = []  # terms with b (polygammas)
+    # Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i])
+    expression = Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
+    expression = gamma(b)/sympy.exp(x) * expression
+
+    # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
+    for n in range(0, order+1):
+        term = expression.diff(a, n).subs(a, 0).simplify().doit()
+        # set the whole bracket involving polygammas to 1
+        x_part = (term.subs(polygamma(0, b), 1)
+                  .replace(polygamma, lambda *args: 0))
+        # sign convention: x part always positive
+        x_part *= (-1)**n
+
+        A.append(a**n/factorial(n))
+        X.append(horner(x_part))
+        B.append(horner((term/x_part).simplify()))
+
+    s = "Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.\n"
+    s += "Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)\n"
+    for name, c in zip(['A', 'X', 'B'], [A, X, B]):
+        for i in range(len(c)):
+            s += f"\n{name}[{i}] = " + str(c[i])
+    return s
+
+
+# expansion of digamma
+def dg_series(z, n):
+    """Symbolic expansion of digamma(z) in z=0 to order n.
+
+    See https://dlmf.nist.gov/5.7.E4 and with https://dlmf.nist.gov/5.5.E2
+    """
+    k = symbols("k")
+    return -1/z - EulerGamma + \
+        sympy.summation((-1)**k * zeta(k) * z**(k-1), (k, 2, n+1))
+
+
+def pg_series(k, z, n):
+    """Symbolic expansion of polygamma(k, z) in z=0 to order n."""
+    return sympy.diff(dg_series(z, n+k), z, k)
+
+
+def series_small_a_small_b():
+    """Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5.
+
+    Be aware of cancellation of poles in b=0 of digamma(b)/Gamma(b) and
+    polygamma functions.
+
+    digamma(b)/Gamma(b) = -1 - 2*M_EG*b + O(b^2)
+    digamma(b)^2/Gamma(b) = 1/b + 3*M_EG + b*(-5/12*PI^2+7/2*M_EG^2) + O(b^2)
+    polygamma(1, b)/Gamma(b) = 1/b + M_EG + b*(1/12*PI^2 + 1/2*M_EG^2) + O(b^2)
+    and so on.
+    """
+    order = 5
+    a, b, x, k = symbols("a b x k")
+    M_PI, M_EG, M_Z3 = symbols("M_PI M_EG M_Z3")
+    c_subs = {pi: M_PI, EulerGamma: M_EG, zeta(3): M_Z3}
+    A = []  # terms with a
+    X = []  # terms with x
+    B = []  # terms with b (polygammas expanded)
+    C = []  # terms that generate B
+    # Phi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i])
+    # B[0] = 1
+    # B[k] = sum(C[k] * b**k/k!, k=0..)
+    # Note: C[k] can be obtained from a series expansion of 1/gamma(b).
+    expression = gamma(b)/sympy.exp(x) * \
+        Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
+
+    # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
+    for n in range(0, order+1):
+        term = expression.diff(a, n).subs(a, 0).simplify().doit()
+        # set the whole bracket involving polygammas to 1
+        x_part = (term.subs(polygamma(0, b), 1)
+                  .replace(polygamma, lambda *args: 0))
+        # sign convention: x part always positive
+        x_part *= (-1)**n
+        # expansion of polygamma part with 1/gamma(b)
+        pg_part = term/x_part/gamma(b)
+        if n >= 1:
+            # Note: highest term is digamma^n
+            pg_part = pg_part.replace(polygamma,
+                                      lambda k, x: pg_series(k, x, order+1+n))
+            pg_part = (pg_part.series(b, 0, n=order+1-n)
+                       .removeO()
+                       .subs(polygamma(2, 1), -2*zeta(3))
+                       .simplify()
+                       )
+
+        A.append(a**n/factorial(n))
+        X.append(horner(x_part))
+        B.append(pg_part)
+
+    # Calculate C and put in the k!
+    C = sympy.Poly(B[1].subs(c_subs), b).coeffs()
+    C.reverse()
+    for i in range(len(C)):
+        C[i] = (C[i] * factorial(i)).simplify()
+
+    s = "Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5."
+    s += "\nPhi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i], i=0..5)\n"
+    s += "B[0] = 1\n"
+    s += "B[i] = sum(C[k+i-1] * b**k/k!, k=0..)\n"
+    s += "\nM_PI = pi"
+    s += "\nM_EG = EulerGamma"
+    s += "\nM_Z3 = zeta(3)"
+    for name, c in zip(['A', 'X'], [A, X]):
+        for i in range(len(c)):
+            s += f"\n{name}[{i}] = "
+            s += str(c[i])
+    # For C, do also compute the values numerically
+    for i in range(len(C)):
+        s += f"\n# C[{i}] = "
+        s += str(C[i])
+        s += f"\nC[{i}] = "
+        s += str(C[i].subs({M_EG: EulerGamma, M_PI: pi, M_Z3: zeta(3)})
+                 .evalf(17))
+
+    # Does B have the assumed structure?
+    s += "\n\nTest if B[i] does have the assumed structure."
+    s += "\nC[i] are derived from B[1] alone."
+    s += "\nTest B[2] == C[1] + b*C[2] + b^2/2*C[3] + b^3/6*C[4] + .."
+    test = sum([b**k/factorial(k) * C[k+1] for k in range(order-1)])
+    test = (test - B[2].subs(c_subs)).simplify()
+    s += f"\ntest successful = {test==S(0)}"
+    s += "\nTest B[3] == C[2] + b*C[3] + b^2/2*C[4] + .."
+    test = sum([b**k/factorial(k) * C[k+2] for k in range(order-2)])
+    test = (test - B[3].subs(c_subs)).simplify()
+    s += f"\ntest successful = {test==S(0)}"
+    return s
+
+
+def asymptotic_series():
+    """Asymptotic expansion for large x.
+
+    Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
+    Z = (a*x)^(1/(1+a))
+
+    Wright (1935) lists the coefficients C_0 and C_1 (he calls them a_0 and
+    a_1). With slightly different notation, Paris (2017) lists coefficients
+    c_k up to order k=3.
+    Paris (2017) uses ZP = (1+a)/a * Z  (ZP = Z of Paris) and
+    C_k = C_0 * (-a/(1+a))^k * c_k
+    """
+    order = 8
+
+    class g(sympy.Function):
+        """Helper function g according to Wright (1935)
+
+        g(n, rho, v) = (1 + (rho+2)/3 * v + (rho+2)*(rho+3)/(2*3) * v^2 + ...)
+
+        Note: Wright (1935) uses square root of above definition.
+        """
+        nargs = 3
+
+        @classmethod
+        def eval(cls, n, rho, v):
+            if not n >= 0:
+                raise ValueError("must have n >= 0")
+            elif n == 0:
+                return 1
+            else:
+                return g(n-1, rho, v) \
+                    + gammasimp(gamma(rho+2+n)/gamma(rho+2)) \
+                    / gammasimp(gamma(3+n)/gamma(3))*v**n
+
+    class coef_C(sympy.Function):
+        """Calculate coefficients C_m for integer m.
+
+        C_m is the coefficient of v^(2*m) in the Taylor expansion in v=0 of
+        Gamma(m+1/2)/(2*pi) * (2/(rho+1))^(m+1/2) * (1-v)^(-b)
+            * g(rho, v)^(-m-1/2)
+        """
+        nargs = 3
+
+        @classmethod
+        def eval(cls, m, rho, beta):
+            if not m >= 0:
+                raise ValueError("must have m >= 0")
+
+            v = symbols("v")
+            expression = (1-v)**(-beta) * g(2*m, rho, v)**(-m-Rational(1, 2))
+            res = expression.diff(v, 2*m).subs(v, 0) / factorial(2*m)
+            res = res * (gamma(m + Rational(1, 2)) / (2*pi)
+                         * (2/(rho+1))**(m + Rational(1, 2)))
+            return res
+
+    # in order to have nice ordering/sorting of expressions, we set a = xa.
+    xa, b, xap1 = symbols("xa b xap1")
+    C0 = coef_C(0, xa, b)
+    # a1 = a(1, rho, beta)
+    s = "Asymptotic expansion for large x\n"
+    s += "Phi(a, b, x) = Z**(1/2-b) * exp((1+a)/a * Z) \n"
+    s += "               * sum((-1)**k * C[k]/Z**k, k=0..6)\n\n"
+    s += "Z      = pow(a * x, 1/(1+a))\n"
+    s += "A[k]   = pow(a, k)\n"
+    s += "B[k]   = pow(b, k)\n"
+    s += "Ap1[k] = pow(1+a, k)\n\n"
+    s += "C[0] = 1./sqrt(2. * M_PI * Ap1[1])\n"
+    for i in range(1, order+1):
+        expr = (coef_C(i, xa, b) / (C0/(1+xa)**i)).simplify()
+        factor = [x.denominator() for x in sympy.Poly(expr).coeffs()]
+        factor = sympy.lcm(factor)
+        expr = (expr * factor).simplify().collect(b, sympy.factor)
+        expr = expr.xreplace({xa+1: xap1})
+        s += f"C[{i}] = C[0] / ({factor} * Ap1[{i}])\n"
+        s += f"C[{i}] *= {str(expr)}\n\n"
+    import re
+    re_a = re.compile(r'xa\*\*(\d+)')
+    s = re_a.sub(r'A[\1]', s)
+    re_b = re.compile(r'b\*\*(\d+)')
+    s = re_b.sub(r'B[\1]', s)
+    s = s.replace('xap1', 'Ap1[1]')
+    s = s.replace('xa', 'a')
+    # max integer = 2^31-1 = 2,147,483,647. Solution: Put a point after 10
+    # or more digits.
+    re_digits = re.compile(r'(\d{10,})')
+    s = re_digits.sub(r'\1.', s)
+    return s
+
+
+def optimal_epsilon_integral():
+    """Fit optimal choice of epsilon for integral representation.
+
+    The integrand of
+        int_0^pi P(eps, a, b, x, phi) * dphi
+    can exhibit oscillatory behaviour. It stems from the cosine of P and can be
+    minimized by minimizing the arc length of the argument
+        f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a * phi) + (1 - b) * phi
+    of cos(f(phi)).
+    We minimize the arc length in eps for a grid of values (a, b, x) and fit a
+    parametric function to it.
+    """
+    def fp(eps, a, b, x, phi):
+        """Derivative of f w.r.t. phi."""
+        eps_a = np.power(1. * eps, -a)
+        return eps * np.cos(phi) - a * x * eps_a * np.cos(a * phi) + 1 - b
+
+    def arclength(eps, a, b, x, epsrel=1e-2, limit=100):
+        """Compute Arc length of f.
+
+        Note that the arc length of a function f from t0 to t1 is given by
+            int_t0^t1 sqrt(1 + f'(t)^2) dt
+        """
+        return quad(lambda phi: np.sqrt(1 + fp(eps, a, b, x, phi)**2),
+                    0, np.pi,
+                    epsrel=epsrel, limit=100)[0]
+
+    # grid of minimal arc length values
+    data_a = [1e-3, 0.1, 0.5, 0.9, 1, 2, 4, 5, 6, 8]
+    data_b = [0, 1, 4, 7, 10]
+    data_x = [1, 1.5, 2, 4, 10, 20, 50, 100, 200, 500, 1e3, 5e3, 1e4]
+    data_a, data_b, data_x = np.meshgrid(data_a, data_b, data_x)
+    data_a, data_b, data_x = (data_a.flatten(), data_b.flatten(),
+                              data_x.flatten())
+    best_eps = []
+    for i in range(data_x.size):
+        best_eps.append(
+            minimize_scalar(lambda eps: arclength(eps, data_a[i], data_b[i],
+                                                  data_x[i]),
+                            bounds=(1e-3, 1000),
+                            method='Bounded', options={'xatol': 1e-3}).x
+        )
+    best_eps = np.array(best_eps)
+    # pandas would be nice, but here a dictionary is enough
+    df = {'a': data_a,
+          'b': data_b,
+          'x': data_x,
+          'eps': best_eps,
+          }
+
+    def func(data, A0, A1, A2, A3, A4, A5):
+        """Compute parametric function to fit."""
+        a = data['a']
+        b = data['b']
+        x = data['x']
+        return (A0 * b * np.exp(-0.5 * a)
+                + np.exp(A1 + 1 / (1 + a) * np.log(x) - A2 * np.exp(-A3 * a)
+                         + A4 / (1 + np.exp(A5 * a))))
+
+    func_params = list(curve_fit(func, df, df['eps'], method='trf')[0])
+
+    s = "Fit optimal eps for integrand P via minimal arc length\n"
+    s += "with parametric function:\n"
+    s += "optimal_eps = (A0 * b * exp(-a/2) + exp(A1 + 1 / (1 + a) * log(x)\n"
+    s += "              - A2 * exp(-A3 * a) + A4 / (1 + exp(A5 * a)))\n\n"
+    s += "Fitted parameters A0 to A5 are:\n"
+    s += ', '.join([f'{x:.5g}' for x in func_params])
+    return s
+
+
+def main():
+    t0 = time()
+    parser = ArgumentParser(description=__doc__,
+                            formatter_class=RawTextHelpFormatter)
+    parser.add_argument('action', type=int, choices=[1, 2, 3, 4],
+                        help='chose what expansion to precompute\n'
+                             '1 : Series for small a\n'
+                             '2 : Series for small a and small b\n'
+                             '3 : Asymptotic series for large x\n'
+                             '    This may take some time (>4h).\n'
+                             '4 : Fit optimal eps for integral representation.'
+                        )
+    args = parser.parse_args()
+
+    switch = {1: lambda: print(series_small_a()),
+              2: lambda: print(series_small_a_small_b()),
+              3: lambda: print(asymptotic_series()),
+              4: lambda: print(optimal_epsilon_integral())
+              }
+    switch.get(args.action, lambda: print("Invalid input."))()
+    print(f"\n{(time() - t0)/60:.1f} minutes elapsed.\n")
+
+
+if __name__ == '__main__':
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..1de9b4fe552ca9178c452194ab84af6ca5daac71
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py
@@ -0,0 +1,152 @@
+"""Compute a grid of values for Wright's generalized Bessel function
+and save the values to data files for use in tests. Using mpmath directly in
+tests would take too long.
+
+This takes about 10 minutes to run on a 2.7 GHz i7 Macbook Pro.
+"""
+from functools import lru_cache
+import os
+from time import time
+
+import numpy as np
+from scipy.special._mptestutils import mpf2float
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+# exp_inf: smallest value x for which exp(x) == inf
+exp_inf = 709.78271289338403
+
+
+# 64 Byte per value
+@lru_cache(maxsize=100_000)
+def rgamma_cached(x, dps):
+    with mp.workdps(dps):
+        return mp.rgamma(x)
+
+
+def mp_wright_bessel(a, b, x, dps=50, maxterms=2000):
+    """Compute Wright's generalized Bessel function as Series with mpmath.
+    """
+    with mp.workdps(dps):
+        a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
+        res = mp.nsum(lambda k: x**k / mp.fac(k)
+                      * rgamma_cached(a * k + b, dps=dps),
+                      [0, mp.inf],
+                      tol=dps, method='s', steps=[maxterms]
+                      )
+        return mpf2float(res)
+
+
+def main():
+    t0 = time()
+    print(__doc__)
+    pwd = os.path.dirname(__file__)
+    eps = np.finfo(float).eps * 100
+
+    a_range = np.array([eps,
+                        1e-4 * (1 - eps), 1e-4, 1e-4 * (1 + eps),
+                        1e-3 * (1 - eps), 1e-3, 1e-3 * (1 + eps),
+                        0.1, 0.5,
+                        1 * (1 - eps), 1, 1 * (1 + eps),
+                        1.5, 2, 4.999, 5, 10])
+    b_range = np.array([0, eps, 1e-10, 1e-5, 0.1, 1, 2, 10, 20, 100])
+    x_range = np.array([0, eps, 1 - eps, 1, 1 + eps,
+                        1.5,
+                        2 - eps, 2, 2 + eps,
+                        9 - eps, 9, 9 + eps,
+                        10 * (1 - eps), 10, 10 * (1 + eps),
+                        100 * (1 - eps), 100, 100 * (1 + eps),
+                        500, exp_inf, 1e3, 1e5, 1e10, 1e20])
+
+    a_range, b_range, x_range = np.meshgrid(a_range, b_range, x_range,
+                                            indexing='ij')
+    a_range = a_range.flatten()
+    b_range = b_range.flatten()
+    x_range = x_range.flatten()
+
+    # filter out some values, especially too large x
+    bool_filter = ~((a_range < 5e-3) & (x_range >= exp_inf))
+    bool_filter = bool_filter & ~((a_range < 0.2) & (x_range > exp_inf))
+    bool_filter = bool_filter & ~((a_range < 0.5) & (x_range > 1e3))
+    bool_filter = bool_filter & ~((a_range < 0.56) & (x_range > 5e3))
+    bool_filter = bool_filter & ~((a_range < 1) & (x_range > 1e4))
+    bool_filter = bool_filter & ~((a_range < 1.4) & (x_range > 1e5))
+    bool_filter = bool_filter & ~((a_range < 1.8) & (x_range > 1e6))
+    bool_filter = bool_filter & ~((a_range < 2.2) & (x_range > 1e7))
+    bool_filter = bool_filter & ~((a_range < 2.5) & (x_range > 1e8))
+    bool_filter = bool_filter & ~((a_range < 2.9) & (x_range > 1e9))
+    bool_filter = bool_filter & ~((a_range < 3.3) & (x_range > 1e10))
+    bool_filter = bool_filter & ~((a_range < 3.7) & (x_range > 1e11))
+    bool_filter = bool_filter & ~((a_range < 4) & (x_range > 1e12))
+    bool_filter = bool_filter & ~((a_range < 4.4) & (x_range > 1e13))
+    bool_filter = bool_filter & ~((a_range < 4.7) & (x_range > 1e14))
+    bool_filter = bool_filter & ~((a_range < 5.1) & (x_range > 1e15))
+    bool_filter = bool_filter & ~((a_range < 5.4) & (x_range > 1e16))
+    bool_filter = bool_filter & ~((a_range < 5.8) & (x_range > 1e17))
+    bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
+    bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
+    bool_filter = bool_filter & ~((a_range < 6.5) & (x_range > 1e19))
+    bool_filter = bool_filter & ~((a_range < 6.9) & (x_range > 1e20))
+
+    # filter out known values that do not meet the required numerical accuracy
+    # see test test_wright_data_grid_failures
+    failing = np.array([
+        [0.1, 100, 709.7827128933841],
+        [0.5, 10, 709.7827128933841],
+        [0.5, 10, 1000],
+        [0.5, 100, 1000],
+        [1, 20, 100000],
+        [1, 100, 100000],
+        [1.0000000000000222, 20, 100000],
+        [1.0000000000000222, 100, 100000],
+        [1.5, 0, 500],
+        [1.5, 2.220446049250313e-14, 500],
+        [1.5, 1.e-10, 500],
+        [1.5, 1.e-05, 500],
+        [1.5, 0.1, 500],
+        [1.5, 20, 100000],
+        [1.5, 100, 100000],
+        ]).tolist()
+
+    does_fail = np.full_like(a_range, False, dtype=bool)
+    for i in range(x_range.size):
+        if [a_range[i], b_range[i], x_range[i]] in failing:
+            does_fail[i] = True
+
+    # filter and flatten
+    a_range = a_range[bool_filter]
+    b_range = b_range[bool_filter]
+    x_range = x_range[bool_filter]
+    does_fail = does_fail[bool_filter]
+
+    dataset = []
+    print(f"Computing {x_range.size} single points.")
+    print("Tests will fail for the following data points:")
+    for i in range(x_range.size):
+        a = a_range[i]
+        b = b_range[i]
+        x = x_range[i]
+        # take care of difficult corner cases
+        maxterms = 1000
+        if a < 1e-6 and x >= exp_inf/10:
+            maxterms = 2000
+        f = mp_wright_bessel(a, b, x, maxterms=maxterms)
+        if does_fail[i]:
+            print("failing data point a, b, x, value = "
+                  f"[{a}, {b}, {x}, {f}]")
+        else:
+            dataset.append((a, b, x, f))
+    dataset = np.array(dataset)
+
+    filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
+                            'wright_bessel.txt')
+    np.savetxt(filename, dataset)
+
+    print(f"{(time() - t0)/60:.1f} minutes elapsed")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bcd0345a9c1b90c45b0e9e3340ab4da4ec5c6d7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py
@@ -0,0 +1,41 @@
+import numpy as np
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def mpmath_wrightomega(x):
+    return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
+
+
+def wrightomega_series_error(x):
+    series = x
+    desired = mpmath_wrightomega(x)
+    return abs(series - desired) / desired
+
+
+def wrightomega_exp_error(x):
+    exponential_approx = mpmath.exp(x)
+    desired = mpmath_wrightomega(x)
+    return abs(exponential_approx - desired) / desired
+
+
+def main():
+    desired_error = 2 * np.finfo(float).eps
+    print('Series Error')
+    for x in [1e5, 1e10, 1e15, 1e20]:
+        with mpmath.workdps(100):
+            error = wrightomega_series_error(x)
+        print(x, error, error < desired_error)
+
+    print('Exp error')
+    for x in [-10, -25, -50, -100, -200, -400, -700, -740]:
+        with mpmath.workdps(100):
+            error = wrightomega_exp_error(x)
+        print(x, error, error < desired_error)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py b/venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py
new file mode 100644
index 0000000000000000000000000000000000000000..d408b1a2fffb6872287452923fcc9394adc13a7c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py
@@ -0,0 +1,27 @@
+"""Compute the Taylor series for zeta(x) - 1 around x = 0."""
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def zetac_series(N):
+    coeffs = []
+    with mpmath.workdps(100):
+        coeffs.append(-1.5)
+        for n in range(1, N):
+            coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n)
+            coeffs.append(coeff)
+    return coeffs
+
+
+def main():
+    print(__doc__)
+    coeffs = zetac_series(10)
+    coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+              for x in coeffs]
+    print("\n".join(coeffs[::-1]))
+
+
+if __name__ == '__main__':
+    main()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_sf_error.py b/venv/lib/python3.10/site-packages/scipy/special/_sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1edc9800759dfda9e49bde1becc775a64bce958
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_sf_error.py
@@ -0,0 +1,15 @@
+"""Warnings and Exceptions that can be raised by special functions."""
+import warnings
+
+
+class SpecialFunctionWarning(Warning):
+    """Warning that can be emitted by special functions."""
+    pass
+
+
+warnings.simplefilter("always", category=SpecialFunctionWarning)
+
+
+class SpecialFunctionError(Exception):
+    """Exception that can be raised by special functions."""
+    pass
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py b/venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..2525eceb47ec2b20b45ca693e19e741f4a666597
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py
@@ -0,0 +1,106 @@
+# Last Change: Sat Mar 21 02:00 PM 2009 J
+
+# Copyright (c) 2001, 2002 Enthought, Inc.
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#   a. Redistributions of source code must retain the above copyright notice,
+#      this list of conditions and the following disclaimer.
+#   b. 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.
+#   c. Neither the name of the Enthought nor the names of its contributors
+#      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 REGENTS 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.
+
+"""Some more special functions which may be useful for multivariate statistical
+analysis."""
+
+import numpy as np
+from scipy.special import gammaln as loggam
+
+
+__all__ = ['multigammaln']
+
+
+def multigammaln(a, d):
+    r"""Returns the log of multivariate gamma, also sometimes called the
+    generalized gamma.
+
+    Parameters
+    ----------
+    a : ndarray
+        The multivariate gamma is computed for each item of `a`.
+    d : int
+        The dimension of the space of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The values of the log multivariate gamma at the given points `a`.
+
+    Notes
+    -----
+    The formal definition of the multivariate gamma of dimension d for a real
+    `a` is
+
+    .. math::
+
+        \Gamma_d(a) = \int_{A>0} e^{-tr(A)} |A|^{a - (d+1)/2} dA
+
+    with the condition :math:`a > (d-1)/2`, and :math:`A > 0` being the set of
+    all the positive definite matrices of dimension `d`.  Note that `a` is a
+    scalar: the integrand only is multivariate, the argument is not (the
+    function is defined over a subset of the real set).
+
+    This can be proven to be equal to the much friendlier equation
+
+    .. math::
+
+        \Gamma_d(a) = \pi^{d(d-1)/4} \prod_{i=1}^{d} \Gamma(a - (i-1)/2).
+
+    References
+    ----------
+    R. J. Muirhead, Aspects of multivariate statistical theory (Wiley Series in
+    probability and mathematical statistics).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import multigammaln, gammaln
+    >>> a = 23.5
+    >>> d = 10
+    >>> multigammaln(a, d)
+    454.1488605074416
+
+    Verify that the result agrees with the logarithm of the equation
+    shown above:
+
+    >>> d*(d-1)/4*np.log(np.pi) + gammaln(a - 0.5*np.arange(0, d)).sum()
+    454.1488605074416
+    """
+    a = np.asarray(a)
+    if not np.isscalar(d) or (np.floor(d) != d):
+        raise ValueError("d should be a positive integer (dimension)")
+    if np.any(a <= 0.5 * (d - 1)):
+        raise ValueError(f"condition a ({a:f}) > 0.5 * (d-1) ({0.5 * (d-1):f}) not met")
+
+    res = (d * (d-1) * 0.25) * np.log(np.pi)
+    res += np.sum(loggam([(a - (j - 1.)/2) for j in range(1, d+1)]), axis=0)
+    return res
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py b/venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3d871fcd07ef092962a4594cf780445daae4458
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py
@@ -0,0 +1,397 @@
+from functools import wraps
+from scipy._lib._util import _lazywhere
+import numpy as np
+from ._ufuncs import (_spherical_jn, _spherical_yn, _spherical_in,
+                      _spherical_kn, _spherical_jn_d, _spherical_yn_d,
+                      _spherical_in_d, _spherical_kn_d)
+
+
+def use_reflection(sign_n_even=None, reflection_fun=None):
+    # - If reflection_fun is not specified, reflects negative `z` and multiplies
+    #   output by appropriate sign (indicated by `sign_n_even`).
+    # - If reflection_fun is specified, calls `reflection_fun` instead of `fun`.
+    # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+    def decorator(fun):
+        def standard_reflection(n, z, derivative):
+            # sign_n_even indicates the sign when the order `n` is even
+            sign = np.where(n % 2 == 0, sign_n_even, -sign_n_even)
+            # By the chain rule, differentiation at `-z` adds a minus sign
+            sign = -sign if derivative else sign
+            # Evaluate at positive z (minus negative z) and adjust the sign
+            return fun(n, -z, derivative) * sign
+
+        @wraps(fun)
+        def wrapper(n, z, derivative=False):
+            z = np.asarray(z)
+
+            if np.issubdtype(z.dtype, np.complexfloating):
+                return fun(n, z, derivative)  # complex dtype just works
+
+            f2 = standard_reflection if reflection_fun is None else reflection_fun
+            return _lazywhere(z.real >= 0, (n, z),
+                              f=lambda n, z: fun(n, z, derivative),
+                              f2=lambda n, z: f2(n, z, derivative))[()]
+        return wrapper
+    return decorator
+
+
+@use_reflection(+1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_jn(n, z, derivative=False):
+    r"""Spherical Bessel function of the first kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n + 1/2}(z),
+
+    where :math:`J_n` is the Bessel function of the first kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    jn : ndarray
+
+    Notes
+    -----
+    For real arguments greater than the order, the function is computed
+    using the ascending recurrence [2]_. For small real or complex
+    arguments, the definitional relation to the cylindrical Bessel function
+    of the first kind is used.
+
+    The derivative is computed using the relations [3]_,
+
+    .. math::
+        j_n'(z) = j_{n-1}(z) - \frac{n + 1}{z} j_n(z).
+
+        j_0'(z) = -j_1(z)
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E3
+    .. [2] https://dlmf.nist.gov/10.51.E1
+    .. [3] https://dlmf.nist.gov/10.51.E2
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The spherical Bessel functions of the first kind :math:`j_n` accept
+    both real and complex second argument. They can return a complex type:
+
+    >>> from scipy.special import spherical_jn
+    >>> spherical_jn(0, 3+5j)
+    (-9.878987731663194-8.021894345786002j)
+    >>> type(spherical_jn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_jn(3, x, True),
+    ...             spherical_jn(2, x) - 4/x * spherical_jn(3, x))
+    True
+
+    The first few :math:`j_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 10.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-0.5, 1.5)
+    >>> ax.set_title(r'Spherical Bessel functions $j_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_jn(n, x), label=rf'$j_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_jn_d(n, z)
+    else:
+        return _spherical_jn(n, z)
+
+
+@use_reflection(-1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_yn(n, z, derivative=False):
+    r"""Spherical Bessel function of the second kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: y_n(z) = \sqrt{\frac{\pi}{2z}} Y_{n + 1/2}(z),
+
+    where :math:`Y_n` is the Bessel function of the second kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    yn : ndarray
+
+    Notes
+    -----
+    For real arguments, the function is computed using the ascending
+    recurrence [2]_.  For complex arguments, the definitional relation to
+    the cylindrical Bessel function of the second kind is used.
+
+    The derivative is computed using the relations [3]_,
+
+    .. math::
+        y_n' = y_{n-1} - \frac{n + 1}{z} y_n.
+
+        y_0' = -y_1
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E4
+    .. [2] https://dlmf.nist.gov/10.51.E1
+    .. [3] https://dlmf.nist.gov/10.51.E2
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The spherical Bessel functions of the second kind :math:`y_n` accept
+    both real and complex second argument. They can return a complex type:
+
+    >>> from scipy.special import spherical_yn
+    >>> spherical_yn(0, 3+5j)
+    (8.022343088587197-9.880052589376795j)
+    >>> type(spherical_yn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_yn(3, x, True),
+    ...             spherical_yn(2, x) - 4/x * spherical_yn(3, x))
+    True
+
+    The first few :math:`y_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 10.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 1.0)
+    >>> ax.set_title(r'Spherical Bessel functions $y_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_yn(n, x), label=rf'$y_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_yn_d(n, z)
+    else:
+        return _spherical_yn(n, z)
+
+
+@use_reflection(+1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_in(n, z, derivative=False):
+    r"""Modified spherical Bessel function of the first kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: i_n(z) = \sqrt{\frac{\pi}{2z}} I_{n + 1/2}(z),
+
+    where :math:`I_n` is the modified Bessel function of the first kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    in : ndarray
+
+    Notes
+    -----
+    The function is computed using its definitional relation to the
+    modified cylindrical Bessel function of the first kind.
+
+    The derivative is computed using the relations [2]_,
+
+    .. math::
+        i_n' = i_{n-1} - \frac{n + 1}{z} i_n.
+
+        i_1' = i_0
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E7
+    .. [2] https://dlmf.nist.gov/10.51.E5
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The modified spherical Bessel functions of the first kind :math:`i_n`
+    accept both real and complex second argument.
+    They can return a complex type:
+
+    >>> from scipy.special import spherical_in
+    >>> spherical_in(0, 3+5j)
+    (-1.1689867793369182-1.2697305267234222j)
+    >>> type(spherical_in(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_in(3, x, True),
+    ...             spherical_in(2, x) - 4/x * spherical_in(3, x))
+    True
+
+    The first few :math:`i_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 6.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-0.5, 5.0)
+    >>> ax.set_title(r'Modified spherical Bessel functions $i_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_in(n, x), label=rf'$i_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_in_d(n, z)
+    else:
+        return _spherical_in(n, z)
+
+
+def spherical_kn_reflection(n, z, derivative=False):
+    # More complex than the other cases, and this will likely be re-implemented
+    # in C++ anyway. Would require multiple function evaluations. Probably about
+    # as fast to just resort to complex math, and much simpler.
+    return spherical_kn(n, z + 0j, derivative=derivative).real
+
+
+@use_reflection(reflection_fun=spherical_kn_reflection)
+def spherical_kn(n, z, derivative=False):
+    r"""Modified spherical Bessel function of the second kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: k_n(z) = \sqrt{\frac{\pi}{2z}} K_{n + 1/2}(z),
+
+    where :math:`K_n` is the modified Bessel function of the second kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    kn : ndarray
+
+    Notes
+    -----
+    The function is computed using its definitional relation to the
+    modified cylindrical Bessel function of the second kind.
+
+    The derivative is computed using the relations [2]_,
+
+    .. math::
+        k_n' = -k_{n-1} - \frac{n + 1}{z} k_n.
+
+        k_0' = -k_1
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E9
+    .. [2] https://dlmf.nist.gov/10.51.E5
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The modified spherical Bessel functions of the second kind :math:`k_n`
+    accept both real and complex second argument.
+    They can return a complex type:
+
+    >>> from scipy.special import spherical_kn
+    >>> spherical_kn(0, 3+5j)
+    (0.012985785614001561+0.003354691603137546j)
+    >>> type(spherical_kn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_kn(3, x, True),
+    ...             - 4/x * spherical_kn(3, x) - spherical_kn(2, x))
+    True
+
+    The first few :math:`k_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 4.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(0.0, 5.0)
+    >>> ax.set_title(r'Modified spherical Bessel functions $k_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_kn(n, x), label=rf'$k_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_kn_d(n, z)
+    else:
+        return _spherical_kn(n, z)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py b/venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f5101198cebcbb5138e88a2050a5c4d7a115d60
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py
@@ -0,0 +1,202 @@
+import os
+import sys
+import functools
+
+import numpy as np
+from scipy._lib._array_api import (
+    array_namespace, scipy_namespace_for, is_numpy
+)
+from . import _ufuncs
+# These don't really need to be imported, but otherwise IDEs might not realize
+# that these are defined in this file / report an error in __init__.py
+from ._ufuncs import (
+    log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln,  # noqa: F401
+    gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy,  # noqa: F401
+    chdtr, chdtrc, betainc, betaincc, stdtr  # noqa: F401
+)
+
+_SCIPY_ARRAY_API = os.environ.get("SCIPY_ARRAY_API", False)
+array_api_compat_prefix = "scipy._lib.array_api_compat"
+
+
+def get_array_special_func(f_name, xp, n_array_args):
+    spx = scipy_namespace_for(xp)
+    f = None
+    if is_numpy(xp):
+        f = getattr(_ufuncs, f_name, None)
+    elif spx is not None:
+        f = getattr(spx.special, f_name, None)
+
+    if f is not None:
+        return f
+
+    # if generic array-API implementation is available, use that;
+    # otherwise, fall back to NumPy/SciPy
+    if f_name in _generic_implementations:
+        _f = _generic_implementations[f_name](xp=xp, spx=spx)
+        if _f is not None:
+            return _f
+
+    _f = getattr(_ufuncs, f_name, None)
+    def __f(*args, _f=_f, _xp=xp, **kwargs):
+        array_args = args[:n_array_args]
+        other_args = args[n_array_args:]
+        array_args = [np.asarray(arg) for arg in array_args]
+        out = _f(*array_args, *other_args, **kwargs)
+        return _xp.asarray(out)
+
+    return __f
+
+
+def _get_shape_dtype(*args, xp):
+    args = xp.broadcast_arrays(*args)
+    shape = args[0].shape
+    dtype = xp.result_type(*args)
+    if xp.isdtype(dtype, 'integral'):
+        dtype = xp.float64
+        args = [xp.asarray(arg, dtype=dtype) for arg in args]
+    return args, shape, dtype
+
+
+def _rel_entr(xp, spx):
+    def __rel_entr(x, y, *, xp=xp):
+        args, shape, dtype = _get_shape_dtype(x, y, xp=xp)
+        x, y = args
+        res = xp.full(x.shape, xp.inf, dtype=dtype)
+        res[(x == 0) & (y >= 0)] = xp.asarray(0, dtype=dtype)
+        i = (x > 0) & (y > 0)
+        res[i] = x[i] * (xp.log(x[i]) - xp.log(y[i]))
+        return res
+    return __rel_entr
+
+
+def _xlogy(xp, spx):
+    def __xlogy(x, y, *, xp=xp):
+        with np.errstate(divide='ignore', invalid='ignore'):
+            temp = x * xp.log(y)
+        return xp.where(x == 0., xp.asarray(0., dtype=temp.dtype), temp)
+    return __xlogy
+
+
+def _chdtr(xp, spx):
+    # The difference between this and just using `gammainc`
+    # defined by `get_array_special_func` is that if `gammainc`
+    # isn't found, we don't want to use the SciPy version; we'll
+    # return None here and use the SciPy version of `chdtr`.
+    gammainc = getattr(spx.special, 'gammainc', None) if spx else None  # noqa: F811
+    if gammainc is None and hasattr(xp, 'special'):
+        gammainc = getattr(xp.special, 'gammainc', None)
+    if gammainc is None:
+        return None
+
+    def __chdtr(v, x):
+        res = gammainc(v / 2, x / 2)  # this is almost all we need
+        # The rest can be removed when google/jax#20507 is resolved
+        mask = (v == 0) & (x > 0)  # JAX returns NaN
+        res = xp.where(mask, 1., res)
+        mask = xp.isinf(v) & xp.isinf(x)  # JAX returns 1.0
+        return xp.where(mask, xp.nan, res)
+    return __chdtr
+
+
+def _chdtrc(xp, spx):
+    # The difference between this and just using `gammaincc`
+    # defined by `get_array_special_func` is that if `gammaincc`
+    # isn't found, we don't want to use the SciPy version; we'll
+    # return None here and use the SciPy version of `chdtrc`.
+    gammaincc = getattr(spx.special, 'gammaincc', None) if spx else None  # noqa: F811
+    if gammaincc is None and hasattr(xp, 'special'):
+        gammaincc = getattr(xp.special, 'gammaincc', None)
+    if gammaincc is None:
+        return None
+
+    def __chdtrc(v, x):
+        res = xp.where(x >= 0, gammaincc(v/2, x/2), 1)
+        i_nan = ((x == 0) & (v == 0)) | xp.isnan(x) | xp.isnan(v) | (v <= 0)
+        res = xp.where(i_nan, xp.nan, res)
+        return res
+    return __chdtrc
+
+
+def _betaincc(xp, spx):
+    betainc = getattr(spx.special, 'betainc', None) if spx else None  # noqa: F811
+    if betainc is None and hasattr(xp, 'special'):
+        betainc = getattr(xp.special, 'betainc', None)
+    if betainc is None:
+        return None
+
+    def __betaincc(a, b, x):
+        # not perfect; might want to just rely on SciPy
+        return betainc(b, a, 1-x)
+    return __betaincc
+
+
+def _stdtr(xp, spx):
+    betainc = getattr(spx.special, 'betainc', None) if spx else None  # noqa: F811
+    if betainc is None and hasattr(xp, 'special'):
+        betainc = getattr(xp.special, 'betainc', None)
+    if betainc is None:
+        return None
+
+    def __stdtr(df, t):
+        x = df / (t ** 2 + df)
+        tail = betainc(df / 2, 0.5, x) / 2
+        return xp.where(t < 0, tail, 1 - tail)
+
+    return __stdtr
+
+
+_generic_implementations = {'rel_entr': _rel_entr,
+                            'xlogy': _xlogy,
+                            'chdtr': _chdtr,
+                            'chdtrc': _chdtrc,
+                            'betaincc': _betaincc,
+                            'stdtr': _stdtr,
+                            }
+
+
+# functools.wraps doesn't work because:
+# 'numpy.ufunc' object has no attribute '__module__'
+def support_alternative_backends(f_name, n_array_args):
+    func = getattr(_ufuncs, f_name)
+
+    @functools.wraps(func)
+    def wrapped(*args, **kwargs):
+        xp = array_namespace(*args[:n_array_args])
+        f = get_array_special_func(f_name, xp, n_array_args)
+        return f(*args, **kwargs)
+
+    return wrapped
+
+
+array_special_func_map = {
+    'log_ndtr': 1,
+    'ndtr': 1,
+    'ndtri': 1,
+    'erf': 1,
+    'erfc': 1,
+    'i0': 1,
+    'i0e': 1,
+    'i1': 1,
+    'i1e': 1,
+    'gammaln': 1,
+    'gammainc': 2,
+    'gammaincc': 2,
+    'logit': 1,
+    'expit': 1,
+    'entr': 1,
+    'rel_entr': 2,
+    'xlogy': 2,
+    'chdtr': 2,
+    'chdtrc': 2,
+    'betainc': 3,
+    'betaincc': 3,
+    'stdtr': 2,
+}
+
+for f_name, n_array_args in array_special_func_map.items():
+    f = (support_alternative_backends(f_name, n_array_args) if _SCIPY_ARRAY_API
+         else getattr(_ufuncs, f_name))
+    sys.modules[__name__].__dict__[f_name] = f
+
+__all__ = list(array_special_func_map)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi b/venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1e6c272f16fa2bd3ae75af412bc6ae3270158ce4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi
@@ -0,0 +1,9 @@
+import numpy as np
+
+def have_fenv() -> bool: ...
+def random_double(size: int, rng: np.random.RandomState) -> np.float64: ...
+def test_add_round(size: int, mode: str, rng: np.random.RandomState): ...
+
+def _dd_exp(xhi: float, xlo: float) -> tuple[float, float]: ...
+def _dd_log(xhi: float, xlo: float) -> tuple[float, float]: ...
+def _dd_expm1(xhi: float, xlo: float) -> tuple[float, float]: ...
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_testutils.py b/venv/lib/python3.10/site-packages/scipy/special/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0c2bd3053d076aacfa8be1d53cd851443fd8821
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_testutils.py
@@ -0,0 +1,321 @@
+import os
+import functools
+import operator
+from scipy._lib import _pep440
+
+import numpy as np
+from numpy.testing import assert_
+import pytest
+
+import scipy.special as sc
+
+__all__ = ['with_special_errors', 'assert_func_equal', 'FuncData']
+
+
+#------------------------------------------------------------------------------
+# Check if a module is present to be used in tests
+#------------------------------------------------------------------------------
+
+class MissingModule:
+    def __init__(self, name):
+        self.name = name
+
+
+def check_version(module, min_ver):
+    if type(module) is MissingModule:
+        return pytest.mark.skip(reason=f"{module.name} is not installed")
+    return pytest.mark.skipif(
+        _pep440.parse(module.__version__) < _pep440.Version(min_ver),
+        reason=f"{module.__name__} version >= {min_ver} required"
+    )
+
+
+#------------------------------------------------------------------------------
+# Enable convergence and loss of precision warnings -- turn off one by one
+#------------------------------------------------------------------------------
+
+def with_special_errors(func):
+    """
+    Enable special function errors (such as underflow, overflow,
+    loss of precision, etc.)
+    """
+    @functools.wraps(func)
+    def wrapper(*a, **kw):
+        with sc.errstate(all='raise'):
+            res = func(*a, **kw)
+        return res
+    return wrapper
+
+
+#------------------------------------------------------------------------------
+# Comparing function values at many data points at once, with helpful
+# error reports
+#------------------------------------------------------------------------------
+
+def assert_func_equal(func, results, points, rtol=None, atol=None,
+                      param_filter=None, knownfailure=None,
+                      vectorized=True, dtype=None, nan_ok=False,
+                      ignore_inf_sign=False, distinguish_nan_and_inf=True):
+    if hasattr(points, 'next'):
+        # it's a generator
+        points = list(points)
+
+    points = np.asarray(points)
+    if points.ndim == 1:
+        points = points[:,None]
+    nparams = points.shape[1]
+
+    if hasattr(results, '__name__'):
+        # function
+        data = points
+        result_columns = None
+        result_func = results
+    else:
+        # dataset
+        data = np.c_[points, results]
+        result_columns = list(range(nparams, data.shape[1]))
+        result_func = None
+
+    fdata = FuncData(func, data, list(range(nparams)),
+                     result_columns=result_columns, result_func=result_func,
+                     rtol=rtol, atol=atol, param_filter=param_filter,
+                     knownfailure=knownfailure, nan_ok=nan_ok, vectorized=vectorized,
+                     ignore_inf_sign=ignore_inf_sign,
+                     distinguish_nan_and_inf=distinguish_nan_and_inf)
+    fdata.check()
+
+
+class FuncData:
+    """
+    Data set for checking a special function.
+
+    Parameters
+    ----------
+    func : function
+        Function to test
+    data : numpy array
+        columnar data to use for testing
+    param_columns : int or tuple of ints
+        Columns indices in which the parameters to `func` lie.
+        Can be imaginary integers to indicate that the parameter
+        should be cast to complex.
+    result_columns : int or tuple of ints, optional
+        Column indices for expected results from `func`.
+    result_func : callable, optional
+        Function to call to obtain results.
+    rtol : float, optional
+        Required relative tolerance. Default is 5*eps.
+    atol : float, optional
+        Required absolute tolerance. Default is 5*tiny.
+    param_filter : function, or tuple of functions/Nones, optional
+        Filter functions to exclude some parameter ranges.
+        If omitted, no filtering is done.
+    knownfailure : str, optional
+        Known failure error message to raise when the test is run.
+        If omitted, no exception is raised.
+    nan_ok : bool, optional
+        If nan is always an accepted result.
+    vectorized : bool, optional
+        Whether all functions passed in are vectorized.
+    ignore_inf_sign : bool, optional
+        Whether to ignore signs of infinities.
+        (Doesn't matter for complex-valued functions.)
+    distinguish_nan_and_inf : bool, optional
+        If True, treat numbers which contain nans or infs as
+        equal. Sets ignore_inf_sign to be True.
+
+    """
+
+    def __init__(self, func, data, param_columns, result_columns=None,
+                 result_func=None, rtol=None, atol=None, param_filter=None,
+                 knownfailure=None, dataname=None, nan_ok=False, vectorized=True,
+                 ignore_inf_sign=False, distinguish_nan_and_inf=True):
+        self.func = func
+        self.data = data
+        self.dataname = dataname
+        if not hasattr(param_columns, '__len__'):
+            param_columns = (param_columns,)
+        self.param_columns = tuple(param_columns)
+        if result_columns is not None:
+            if not hasattr(result_columns, '__len__'):
+                result_columns = (result_columns,)
+            self.result_columns = tuple(result_columns)
+            if result_func is not None:
+                message = "Only result_func or result_columns should be provided"
+                raise ValueError(message)
+        elif result_func is not None:
+            self.result_columns = None
+        else:
+            raise ValueError("Either result_func or result_columns should be provided")
+        self.result_func = result_func
+        self.rtol = rtol
+        self.atol = atol
+        if not hasattr(param_filter, '__len__'):
+            param_filter = (param_filter,)
+        self.param_filter = param_filter
+        self.knownfailure = knownfailure
+        self.nan_ok = nan_ok
+        self.vectorized = vectorized
+        self.ignore_inf_sign = ignore_inf_sign
+        self.distinguish_nan_and_inf = distinguish_nan_and_inf
+        if not self.distinguish_nan_and_inf:
+            self.ignore_inf_sign = True
+
+    def get_tolerances(self, dtype):
+        if not np.issubdtype(dtype, np.inexact):
+            dtype = np.dtype(float)
+        info = np.finfo(dtype)
+        rtol, atol = self.rtol, self.atol
+        if rtol is None:
+            rtol = 5*info.eps
+        if atol is None:
+            atol = 5*info.tiny
+        return rtol, atol
+
+    def check(self, data=None, dtype=None, dtypes=None):
+        """Check the special function against the data."""
+        __tracebackhide__ = operator.methodcaller(
+            'errisinstance', AssertionError
+        )
+
+        if self.knownfailure:
+            pytest.xfail(reason=self.knownfailure)
+
+        if data is None:
+            data = self.data
+
+        if dtype is None:
+            dtype = data.dtype
+        else:
+            data = data.astype(dtype)
+
+        rtol, atol = self.get_tolerances(dtype)
+
+        # Apply given filter functions
+        if self.param_filter:
+            param_mask = np.ones((data.shape[0],), np.bool_)
+            for j, filter in zip(self.param_columns, self.param_filter):
+                if filter:
+                    param_mask &= list(filter(data[:,j]))
+            data = data[param_mask]
+
+        # Pick parameters from the correct columns
+        params = []
+        for idx, j in enumerate(self.param_columns):
+            if np.iscomplexobj(j):
+                j = int(j.imag)
+                params.append(data[:,j].astype(complex))
+            elif dtypes and idx < len(dtypes):
+                params.append(data[:, j].astype(dtypes[idx]))
+            else:
+                params.append(data[:,j])
+
+        # Helper for evaluating results
+        def eval_func_at_params(func, skip_mask=None):
+            if self.vectorized:
+                got = func(*params)
+            else:
+                got = []
+                for j in range(len(params[0])):
+                    if skip_mask is not None and skip_mask[j]:
+                        got.append(np.nan)
+                        continue
+                    got.append(func(*tuple([params[i][j] for i in range(len(params))])))
+                got = np.asarray(got)
+            if not isinstance(got, tuple):
+                got = (got,)
+            return got
+
+        # Evaluate function to be tested
+        got = eval_func_at_params(self.func)
+
+        # Grab the correct results
+        if self.result_columns is not None:
+            # Correct results passed in with the data
+            wanted = tuple([data[:,icol] for icol in self.result_columns])
+        else:
+            # Function producing correct results passed in
+            skip_mask = None
+            if self.nan_ok and len(got) == 1:
+                # Don't spend time evaluating what doesn't need to be evaluated
+                skip_mask = np.isnan(got[0])
+            wanted = eval_func_at_params(self.result_func, skip_mask=skip_mask)
+
+        # Check the validity of each output returned
+        assert_(len(got) == len(wanted))
+
+        for output_num, (x, y) in enumerate(zip(got, wanted)):
+            if np.issubdtype(x.dtype, np.complexfloating) or self.ignore_inf_sign:
+                pinf_x = np.isinf(x)
+                pinf_y = np.isinf(y)
+                minf_x = np.isinf(x)
+                minf_y = np.isinf(y)
+            else:
+                pinf_x = np.isposinf(x)
+                pinf_y = np.isposinf(y)
+                minf_x = np.isneginf(x)
+                minf_y = np.isneginf(y)
+            nan_x = np.isnan(x)
+            nan_y = np.isnan(y)
+
+            with np.errstate(all='ignore'):
+                abs_y = np.absolute(y)
+                abs_y[~np.isfinite(abs_y)] = 0
+                diff = np.absolute(x - y)
+                diff[~np.isfinite(diff)] = 0
+
+                rdiff = diff / np.absolute(y)
+                rdiff[~np.isfinite(rdiff)] = 0
+
+            tol_mask = (diff <= atol + rtol*abs_y)
+            pinf_mask = (pinf_x == pinf_y)
+            minf_mask = (minf_x == minf_y)
+
+            nan_mask = (nan_x == nan_y)
+
+            bad_j = ~(tol_mask & pinf_mask & minf_mask & nan_mask)
+
+            point_count = bad_j.size
+            if self.nan_ok:
+                bad_j &= ~nan_x
+                bad_j &= ~nan_y
+                point_count -= (nan_x | nan_y).sum()
+
+            if not self.distinguish_nan_and_inf and not self.nan_ok:
+                # If nan's are okay we've already covered all these cases
+                inf_x = np.isinf(x)
+                inf_y = np.isinf(y)
+                both_nonfinite = (inf_x & nan_y) | (nan_x & inf_y)
+                bad_j &= ~both_nonfinite
+                point_count -= both_nonfinite.sum()
+
+            if np.any(bad_j):
+                # Some bad results: inform what, where, and how bad
+                msg = [""]
+                msg.append(f"Max |adiff|: {diff[bad_j].max():g}")
+                msg.append(f"Max |rdiff|: {rdiff[bad_j].max():g}")
+                msg.append("Bad results (%d out of %d) for the following points "
+                           "(in output %d):"
+                           % (np.sum(bad_j), point_count, output_num,))
+                for j in np.nonzero(bad_j)[0]:
+                    j = int(j)
+                    def fmt(x):
+                        return '%30s' % np.array2string(x[j], precision=18)
+                    a = "  ".join(map(fmt, params))
+                    b = "  ".join(map(fmt, got))
+                    c = "  ".join(map(fmt, wanted))
+                    d = fmt(rdiff)
+                    msg.append(f"{a} => {b} != {c}  (rdiff {d})")
+                assert_(False, "\n".join(msg))
+
+    def __repr__(self):
+        """Pretty-printing"""
+        if np.any(list(map(np.iscomplexobj, self.param_columns))):
+            is_complex = " (complex)"
+        else:
+            is_complex = ""
+        if self.dataname:
+            return (f"")
+        else:
+            return f""
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0ccf14137096c862a0644cdb229cb98b4556e5d7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi
@@ -0,0 +1,521 @@
+from typing import Any
+
+import numpy as np
+
+__all__ = [
+    'geterr',
+    'seterr',
+    'errstate',
+    'agm',
+    'airy',
+    'airye',
+    'bdtr',
+    'bdtrc',
+    'bdtri',
+    'bdtrik',
+    'bdtrin',
+    'bei',
+    'beip',
+    'ber',
+    'berp',
+    'besselpoly',
+    'beta',
+    'betainc',
+    'betaincc',
+    'betainccinv',
+    'betaincinv',
+    'betaln',
+    'binom',
+    'boxcox',
+    'boxcox1p',
+    'btdtria',
+    'btdtrib',
+    'cbrt',
+    'chdtr',
+    'chdtrc',
+    'chdtri',
+    'chdtriv',
+    'chndtr',
+    'chndtridf',
+    'chndtrinc',
+    'chndtrix',
+    'cosdg',
+    'cosm1',
+    'cotdg',
+    'dawsn',
+    'ellipe',
+    'ellipeinc',
+    'ellipj',
+    'ellipk',
+    'ellipkinc',
+    'ellipkm1',
+    'elliprc',
+    'elliprd',
+    'elliprf',
+    'elliprg',
+    'elliprj',
+    'entr',
+    'erf',
+    'erfc',
+    'erfcinv',
+    'erfcx',
+    'erfi',
+    'erfinv',
+    'eval_chebyc',
+    'eval_chebys',
+    'eval_chebyt',
+    'eval_chebyu',
+    'eval_gegenbauer',
+    'eval_genlaguerre',
+    'eval_hermite',
+    'eval_hermitenorm',
+    'eval_jacobi',
+    'eval_laguerre',
+    'eval_legendre',
+    'eval_sh_chebyt',
+    'eval_sh_chebyu',
+    'eval_sh_jacobi',
+    'eval_sh_legendre',
+    'exp1',
+    'exp10',
+    'exp2',
+    'expi',
+    'expit',
+    'expm1',
+    'expn',
+    'exprel',
+    'fdtr',
+    'fdtrc',
+    'fdtri',
+    'fdtridfd',
+    'fresnel',
+    'gamma',
+    'gammainc',
+    'gammaincc',
+    'gammainccinv',
+    'gammaincinv',
+    'gammaln',
+    'gammasgn',
+    'gdtr',
+    'gdtrc',
+    'gdtria',
+    'gdtrib',
+    'gdtrix',
+    'hankel1',
+    'hankel1e',
+    'hankel2',
+    'hankel2e',
+    'huber',
+    'hyp0f1',
+    'hyp1f1',
+    'hyp2f1',
+    'hyperu',
+    'i0',
+    'i0e',
+    'i1',
+    'i1e',
+    'inv_boxcox',
+    'inv_boxcox1p',
+    'it2i0k0',
+    'it2j0y0',
+    'it2struve0',
+    'itairy',
+    'iti0k0',
+    'itj0y0',
+    'itmodstruve0',
+    'itstruve0',
+    'iv',
+    'ive',
+    'j0',
+    'j1',
+    'jn',
+    'jv',
+    'jve',
+    'k0',
+    'k0e',
+    'k1',
+    'k1e',
+    'kei',
+    'keip',
+    'kelvin',
+    'ker',
+    'kerp',
+    'kl_div',
+    'kn',
+    'kolmogi',
+    'kolmogorov',
+    'kv',
+    'kve',
+    'log1p',
+    'log_expit',
+    'log_ndtr',
+    'log_wright_bessel',
+    'loggamma',
+    'logit',
+    'lpmv',
+    'mathieu_a',
+    'mathieu_b',
+    'mathieu_cem',
+    'mathieu_modcem1',
+    'mathieu_modcem2',
+    'mathieu_modsem1',
+    'mathieu_modsem2',
+    'mathieu_sem',
+    'modfresnelm',
+    'modfresnelp',
+    'modstruve',
+    'nbdtr',
+    'nbdtrc',
+    'nbdtri',
+    'nbdtrik',
+    'nbdtrin',
+    'ncfdtr',
+    'ncfdtri',
+    'ncfdtridfd',
+    'ncfdtridfn',
+    'ncfdtrinc',
+    'nctdtr',
+    'nctdtridf',
+    'nctdtrinc',
+    'nctdtrit',
+    'ndtr',
+    'ndtri',
+    'ndtri_exp',
+    'nrdtrimn',
+    'nrdtrisd',
+    'obl_ang1',
+    'obl_ang1_cv',
+    'obl_cv',
+    'obl_rad1',
+    'obl_rad1_cv',
+    'obl_rad2',
+    'obl_rad2_cv',
+    'owens_t',
+    'pbdv',
+    'pbvv',
+    'pbwa',
+    'pdtr',
+    'pdtrc',
+    'pdtri',
+    'pdtrik',
+    'poch',
+    'powm1',
+    'pro_ang1',
+    'pro_ang1_cv',
+    'pro_cv',
+    'pro_rad1',
+    'pro_rad1_cv',
+    'pro_rad2',
+    'pro_rad2_cv',
+    'pseudo_huber',
+    'psi',
+    'radian',
+    'rel_entr',
+    'rgamma',
+    'round',
+    'shichi',
+    'sici',
+    'sindg',
+    'smirnov',
+    'smirnovi',
+    'spence',
+    'sph_harm',
+    'stdtr',
+    'stdtridf',
+    'stdtrit',
+    'struve',
+    'tandg',
+    'tklmbda',
+    'voigt_profile',
+    'wofz',
+    'wright_bessel',
+    'wrightomega',
+    'xlog1py',
+    'xlogy',
+    'y0',
+    'y1',
+    'yn',
+    'yv',
+    'yve',
+    'zetac'
+]
+
+def geterr() -> dict[str, str]: ...
+def seterr(**kwargs: str) -> dict[str, str]: ...
+
+class errstate:
+    def __init__(self, **kargs: str) -> None: ...
+    def __enter__(self) -> None: ...
+    def __exit__(
+        self,
+        exc_type: Any,  # Unused
+        exc_value: Any,  # Unused
+        traceback: Any,  # Unused
+    ) -> None: ...
+
+_cosine_cdf: np.ufunc
+_cosine_invcdf: np.ufunc
+_cospi: np.ufunc
+_ellip_harm: np.ufunc
+_factorial: np.ufunc
+_igam_fac: np.ufunc
+_kolmogc: np.ufunc
+_kolmogci: np.ufunc
+_kolmogp: np.ufunc
+_lambertw: np.ufunc
+_lanczos_sum_expg_scaled: np.ufunc
+_lgam1p: np.ufunc
+_log1pmx: np.ufunc
+_riemann_zeta: np.ufunc
+_scaled_exp1: np.ufunc
+_sf_error_test_function: np.ufunc
+_sinpi: np.ufunc
+_smirnovc: np.ufunc
+_smirnovci: np.ufunc
+_smirnovp: np.ufunc
+_spherical_in: np.ufunc
+_spherical_in_d: np.ufunc
+_spherical_jn: np.ufunc
+_spherical_jn_d: np.ufunc
+_spherical_kn: np.ufunc
+_spherical_kn_d: np.ufunc
+_spherical_yn: np.ufunc
+_spherical_yn_d: np.ufunc
+_stirling2_inexact: np.ufunc
+_struve_asymp_large_z: np.ufunc
+_struve_bessel_series: np.ufunc
+_struve_power_series: np.ufunc
+_zeta: np.ufunc
+agm: np.ufunc
+airy: np.ufunc
+airye: np.ufunc
+bdtr: np.ufunc
+bdtrc: np.ufunc
+bdtri: np.ufunc
+bdtrik: np.ufunc
+bdtrin: np.ufunc
+bei: np.ufunc
+beip: np.ufunc
+ber: np.ufunc
+berp: np.ufunc
+besselpoly: np.ufunc
+beta: np.ufunc
+betainc: np.ufunc
+betaincc: np.ufunc
+betainccinv: np.ufunc
+betaincinv: np.ufunc
+betaln: np.ufunc
+binom: np.ufunc
+boxcox1p: np.ufunc
+boxcox: np.ufunc
+btdtria: np.ufunc
+btdtrib: np.ufunc
+cbrt: np.ufunc
+chdtr: np.ufunc
+chdtrc: np.ufunc
+chdtri: np.ufunc
+chdtriv: np.ufunc
+chndtr: np.ufunc
+chndtridf: np.ufunc
+chndtrinc: np.ufunc
+chndtrix: np.ufunc
+cosdg: np.ufunc
+cosm1: np.ufunc
+cotdg: np.ufunc
+dawsn: np.ufunc
+ellipe: np.ufunc
+ellipeinc: np.ufunc
+ellipj: np.ufunc
+ellipk: np.ufunc
+ellipkinc: np.ufunc
+ellipkm1: np.ufunc
+elliprc: np.ufunc
+elliprd: np.ufunc
+elliprf: np.ufunc
+elliprg: np.ufunc
+elliprj: np.ufunc
+entr: np.ufunc
+erf: np.ufunc
+erfc: np.ufunc
+erfcinv: np.ufunc
+erfcx: np.ufunc
+erfi: np.ufunc
+erfinv: np.ufunc
+eval_chebyc: np.ufunc
+eval_chebys: np.ufunc
+eval_chebyt: np.ufunc
+eval_chebyu: np.ufunc
+eval_gegenbauer: np.ufunc
+eval_genlaguerre: np.ufunc
+eval_hermite: np.ufunc
+eval_hermitenorm: np.ufunc
+eval_jacobi: np.ufunc
+eval_laguerre: np.ufunc
+eval_legendre: np.ufunc
+eval_sh_chebyt: np.ufunc
+eval_sh_chebyu: np.ufunc
+eval_sh_jacobi: np.ufunc
+eval_sh_legendre: np.ufunc
+exp10: np.ufunc
+exp1: np.ufunc
+exp2: np.ufunc
+expi: np.ufunc
+expit: np.ufunc
+expm1: np.ufunc
+expn: np.ufunc
+exprel: np.ufunc
+fdtr: np.ufunc
+fdtrc: np.ufunc
+fdtri: np.ufunc
+fdtridfd: np.ufunc
+fresnel: np.ufunc
+gamma: np.ufunc
+gammainc: np.ufunc
+gammaincc: np.ufunc
+gammainccinv: np.ufunc
+gammaincinv: np.ufunc
+gammaln: np.ufunc
+gammasgn: np.ufunc
+gdtr: np.ufunc
+gdtrc: np.ufunc
+gdtria: np.ufunc
+gdtrib: np.ufunc
+gdtrix: np.ufunc
+hankel1: np.ufunc
+hankel1e: np.ufunc
+hankel2: np.ufunc
+hankel2e: np.ufunc
+huber: np.ufunc
+hyp0f1: np.ufunc
+hyp1f1: np.ufunc
+hyp2f1: np.ufunc
+hyperu: np.ufunc
+i0: np.ufunc
+i0e: np.ufunc
+i1: np.ufunc
+i1e: np.ufunc
+inv_boxcox1p: np.ufunc
+inv_boxcox: np.ufunc
+it2i0k0: np.ufunc
+it2j0y0: np.ufunc
+it2struve0: np.ufunc
+itairy: np.ufunc
+iti0k0: np.ufunc
+itj0y0: np.ufunc
+itmodstruve0: np.ufunc
+itstruve0: np.ufunc
+iv: np.ufunc
+ive: np.ufunc
+j0: np.ufunc
+j1: np.ufunc
+jn: np.ufunc
+jv: np.ufunc
+jve: np.ufunc
+k0: np.ufunc
+k0e: np.ufunc
+k1: np.ufunc
+k1e: np.ufunc
+kei: np.ufunc
+keip: np.ufunc
+kelvin: np.ufunc
+ker: np.ufunc
+kerp: np.ufunc
+kl_div: np.ufunc
+kn: np.ufunc
+kolmogi: np.ufunc
+kolmogorov: np.ufunc
+kv: np.ufunc
+kve: np.ufunc
+log1p: np.ufunc
+log_expit: np.ufunc
+log_ndtr: np.ufunc
+log_wright_bessel: np.ufunc
+loggamma: np.ufunc
+logit: np.ufunc
+lpmv: np.ufunc
+mathieu_a: np.ufunc
+mathieu_b: np.ufunc
+mathieu_cem: np.ufunc
+mathieu_modcem1: np.ufunc
+mathieu_modcem2: np.ufunc
+mathieu_modsem1: np.ufunc
+mathieu_modsem2: np.ufunc
+mathieu_sem: np.ufunc
+modfresnelm: np.ufunc
+modfresnelp: np.ufunc
+modstruve: np.ufunc
+nbdtr: np.ufunc
+nbdtrc: np.ufunc
+nbdtri: np.ufunc
+nbdtrik: np.ufunc
+nbdtrin: np.ufunc
+ncfdtr: np.ufunc
+ncfdtri: np.ufunc
+ncfdtridfd: np.ufunc
+ncfdtridfn: np.ufunc
+ncfdtrinc: np.ufunc
+nctdtr: np.ufunc
+nctdtridf: np.ufunc
+nctdtrinc: np.ufunc
+nctdtrit: np.ufunc
+ndtr: np.ufunc
+ndtri: np.ufunc
+ndtri_exp: np.ufunc
+nrdtrimn: np.ufunc
+nrdtrisd: np.ufunc
+obl_ang1: np.ufunc
+obl_ang1_cv: np.ufunc
+obl_cv: np.ufunc
+obl_rad1: np.ufunc
+obl_rad1_cv: np.ufunc
+obl_rad2: np.ufunc
+obl_rad2_cv: np.ufunc
+owens_t: np.ufunc
+pbdv: np.ufunc
+pbvv: np.ufunc
+pbwa: np.ufunc
+pdtr: np.ufunc
+pdtrc: np.ufunc
+pdtri: np.ufunc
+pdtrik: np.ufunc
+poch: np.ufunc
+powm1: np.ufunc
+pro_ang1: np.ufunc
+pro_ang1_cv: np.ufunc
+pro_cv: np.ufunc
+pro_rad1: np.ufunc
+pro_rad1_cv: np.ufunc
+pro_rad2: np.ufunc
+pro_rad2_cv: np.ufunc
+pseudo_huber: np.ufunc
+psi: np.ufunc
+radian: np.ufunc
+rel_entr: np.ufunc
+rgamma: np.ufunc
+round: np.ufunc
+shichi: np.ufunc
+sici: np.ufunc
+sindg: np.ufunc
+smirnov: np.ufunc
+smirnovi: np.ufunc
+spence: np.ufunc
+sph_harm: np.ufunc
+stdtr: np.ufunc
+stdtridf: np.ufunc
+stdtrit: np.ufunc
+struve: np.ufunc
+tandg: np.ufunc
+tklmbda: np.ufunc
+voigt_profile: np.ufunc
+wofz: np.ufunc
+wright_bessel: np.ufunc
+wrightomega: np.ufunc
+xlog1py: np.ufunc
+xlogy: np.ufunc
+y0: np.ufunc
+y1: np.ufunc
+yn: np.ufunc
+yv: np.ufunc
+yve: np.ufunc
+zetac: np.ufunc
+
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..5f9afc828a16d598b3ba76582111cd964cfe764a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx
@@ -0,0 +1,14358 @@
+# This file is automatically generated by _generate_pyx.py.
+# Do not edit manually!
+
+from libc.math cimport NAN
+
+include "_ufuncs_extra_code_common.pxi"
+include "_ufuncs_extra_code.pxi"
+__all__ = ['agm', 'bdtr', 'bdtrc', 'bdtri', 'bdtrik', 'bdtrin', 'betainc', 'betaincc', 'betainccinv', 'betaincinv', 'boxcox', 'boxcox1p', 'btdtria', 'btdtrib', 'chdtr', 'chdtrc', 'chdtri', 'chdtriv', 'chndtr', 'chndtridf', 'chndtrinc', 'chndtrix', 'dawsn', 'elliprc', 'elliprd', 'elliprf', 'elliprg', 'elliprj', 'entr', 'erf', 'erfc', 'erfcinv', 'erfcx', 'erfi', 'erfinv', 'eval_chebyc', 'eval_chebys', 'eval_chebyt', 'eval_chebyu', 'eval_gegenbauer', 'eval_genlaguerre', 'eval_hermite', 'eval_hermitenorm', 'eval_jacobi', 'eval_laguerre', 'eval_legendre', 'eval_sh_chebyt', 'eval_sh_chebyu', 'eval_sh_jacobi', 'eval_sh_legendre', 'exp10', 'exp2', 'expm1', 'expn', 'fdtr', 'fdtrc', 'fdtri', 'fdtridfd', 'gdtr', 'gdtrc', 'gdtria', 'gdtrib', 'gdtrix', 'huber', 'hyp0f1', 'hyp1f1', 'hyperu', 'inv_boxcox', 'inv_boxcox1p', 'kl_div', 'kn', 'kolmogi', 'kolmogorov', 'log1p', 'log_ndtr', 'lpmv', 'nbdtr', 'nbdtrc', 'nbdtri', 'nbdtrik', 'nbdtrin', 'ncfdtr', 'ncfdtri', 'ncfdtridfd', 'ncfdtridfn', 'ncfdtrinc', 'nctdtr', 'nctdtridf', 'nctdtrinc', 'nctdtrit', 'ndtr', 'ndtri', 'ndtri_exp', 'nrdtrimn', 'nrdtrisd', 'owens_t', 'pdtr', 'pdtrc', 'pdtri', 'pdtrik', 'poch', 'powm1', 'pseudo_huber', 'rel_entr', 'round', 'shichi', 'sici', 'smirnov', 'smirnovi', 'spence', 'stdtr', 'stdtridf', 'stdtrit', 'tklmbda', 'voigt_profile', 'wofz', 'wrightomega', 'xlog1py', 'xlogy', 'yn', 'geterr', 'seterr', 'errstate', 'jn', 'airy', 'airye', 'bei', 'beip', 'ber', 'berp', 'binom', 'exp1', 'expi', 'expit', 'exprel', 'gamma', 'gammaln', 'hankel1', 'hankel1e', 'hankel2', 'hankel2e', 'hyp2f1', 'it2i0k0', 'it2j0y0', 'it2struve0', 'itairy', 'iti0k0', 'itj0y0', 'itmodstruve0', 'itstruve0', 'iv', 'ive', 'jv', 'jve', 'kei', 'keip', 'kelvin', 'ker', 'kerp', 'kv', 'kve', 'log_expit', 'log_wright_bessel', 'loggamma', 'logit', 'mathieu_a', 'mathieu_b', 'mathieu_cem', 'mathieu_modcem1', 'mathieu_modcem2', 'mathieu_modsem1', 'mathieu_modsem2', 'mathieu_sem', 'modfresnelm', 'modfresnelp', 'obl_ang1', 'obl_ang1_cv', 'obl_cv', 'obl_rad1', 'obl_rad1_cv', 'obl_rad2', 'obl_rad2_cv', 'pbdv', 'pbvv', 'pbwa', 'pro_ang1', 'pro_ang1_cv', 'pro_cv', 'pro_rad1', 'pro_rad1_cv', 'pro_rad2', 'pro_rad2_cv', 'psi', 'rgamma', 'sph_harm', 'wright_bessel', 'yv', 'yve', 'zetac', 'sindg', 'cosdg', 'tandg', 'cotdg', 'i0', 'i0e', 'i1', 'i1e', 'k0', 'k0e', 'k1', 'k1e', 'y0', 'y1', 'j0', 'j1', 'struve', 'modstruve', 'beta', 'betaln', 'besselpoly', 'gammaln', 'gammasgn', 'cbrt', 'radian', 'cosm1', 'gammainc', 'gammaincinv', 'gammaincc', 'gammainccinv', 'fresnel', 'ellipe', 'ellipeinc', 'ellipk', 'ellipkinc', 'ellipkm1', 'ellipj']
+cdef void loop_D_DDDD__As_DDDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDDD__As_FFFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDD__As_DDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDD__As_FFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DD__As_DD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DD__As_FF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_D__As_D_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_D__As_F_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dD__As_dD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dD__As_fF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_ddD__As_ddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_ddD__As_ffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dddD__As_dddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dddD__As_fffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_d__As_d_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_d__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dd__As_dd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dd__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddd__As_ddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddd__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dddd__As_dddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dddd__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddddddd__As_ddddddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddddddd__As_fffffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddiiddd__As_ddllddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        if (ip2)[0] == (ip2)[0] and (ip3)[0] == (ip3)[0]:
+            ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        else:
+            sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument")
+            ov0 = NAN
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddp_d_As_ddp_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef char *op1 = args[4]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+        op1 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dpd__As_dpd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pd__As_pd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pdd__As_pdd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pddd__As_pddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ppd__As_ppd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_f__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_ff__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_fff__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_ffff__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_D_DD_As_D_DD(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double complex ov0
+    cdef double complex ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_D_DD_As_F_FF(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double complex ov0
+    cdef double complex ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_d_dd_As_d_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_d_dd_As_f_ff(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_i__As_l_l(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef int ov0
+    for i in range(n):
+        if (ip0)[0] == (ip0)[0]:
+            ov0 = (func)((ip0)[0])
+        else:
+            sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument")
+            ov0 = 0xbad0bad0
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cosine_cdf "cosine_cdf"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cosine_invcdf "cosine_invcdf"(double) noexcept nogil
+from ._ellip_harm cimport ellip_harmonic as _func_ellip_harmonic
+ctypedef double _proto_ellip_harmonic_t(double, double, int, int, double, double, double) noexcept nogil
+cdef _proto_ellip_harmonic_t *_proto_ellip_harmonic_t_var = &_func_ellip_harmonic
+from ._legacy cimport ellip_harmonic_unsafe as _func_ellip_harmonic_unsafe
+ctypedef double _proto_ellip_harmonic_unsafe_t(double, double, double, double, double, double, double) noexcept nogil
+cdef _proto_ellip_harmonic_unsafe_t *_proto_ellip_harmonic_unsafe_t_var = &_func_ellip_harmonic_unsafe
+from ._factorial cimport _factorial as _func__factorial
+ctypedef double _proto__factorial_t(double) noexcept nogil
+cdef _proto__factorial_t *_proto__factorial_t_var = &_func__factorial
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_igam_fac "cephes_igam_fac"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogc "xsf_kolmogc"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogci "xsf_kolmogci"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogp "xsf_kolmogp"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_lanczos_sum_expg_scaled "cephes_lanczos_sum_expg_scaled"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_lgam1p "cephes_lgam1p"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_log1pmx "cephes_log1pmx"(double) noexcept nogil
+from .sf_error cimport _sf_error_test_function as _func__sf_error_test_function
+ctypedef int _proto__sf_error_test_function_t(int) noexcept nogil
+cdef _proto__sf_error_test_function_t *_proto__sf_error_test_function_t_var = &_func__sf_error_test_function
+from ._legacy cimport smirnovc_unsafe as _func_smirnovc_unsafe
+ctypedef double _proto_smirnovc_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovc_unsafe_t *_proto_smirnovc_unsafe_t_var = &_func_smirnovc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovc_wrap "cephes_smirnovc_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovci_unsafe as _func_smirnovci_unsafe
+ctypedef double _proto_smirnovci_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovci_unsafe_t *_proto_smirnovci_unsafe_t_var = &_func_smirnovci_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovci_wrap "cephes_smirnovci_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovp_unsafe as _func_smirnovp_unsafe
+ctypedef double _proto_smirnovp_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovp_unsafe_t *_proto_smirnovp_unsafe_t_var = &_func_smirnovp_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovp_wrap "cephes_smirnovp_wrap"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_asymp_large_z "cephes__struve_asymp_large_z"(double, double, Py_ssize_t, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_bessel_series "cephes__struve_bessel_series"(double, double, Py_ssize_t, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_power_series "cephes__struve_power_series"(double, double, Py_ssize_t, double *) noexcept nogil
+from ._agm cimport agm as _func_agm
+ctypedef double _proto_agm_t(double, double) noexcept nogil
+cdef _proto_agm_t *_proto_agm_t_var = &_func_agm
+from ._legacy cimport bdtr_unsafe as _func_bdtr_unsafe
+ctypedef double _proto_bdtr_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtr_unsafe_t *_proto_bdtr_unsafe_t_var = &_func_bdtr_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtr_wrap "cephes_bdtr_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport bdtrc_unsafe as _func_bdtrc_unsafe
+ctypedef double _proto_bdtrc_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtrc_unsafe_t *_proto_bdtrc_unsafe_t_var = &_func_bdtrc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtrc_wrap "cephes_bdtrc_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport bdtri_unsafe as _func_bdtri_unsafe
+ctypedef double _proto_bdtri_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtri_unsafe_t *_proto_bdtri_unsafe_t_var = &_func_bdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtri_wrap "cephes_bdtri_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport bdtrik as _func_bdtrik
+ctypedef double _proto_bdtrik_t(double, double, double) noexcept nogil
+cdef _proto_bdtrik_t *_proto_bdtrik_t_var = &_func_bdtrik
+from ._cdflib_wrappers cimport bdtrin as _func_bdtrin
+ctypedef double _proto_bdtrin_t(double, double, double) noexcept nogil
+cdef _proto_bdtrin_t *_proto_bdtrin_t_var = &_func_bdtrin
+from ._boxcox cimport boxcox as _func_boxcox
+ctypedef double _proto_boxcox_t(double, double) noexcept nogil
+cdef _proto_boxcox_t *_proto_boxcox_t_var = &_func_boxcox
+from ._boxcox cimport boxcox1p as _func_boxcox1p
+ctypedef double _proto_boxcox1p_t(double, double) noexcept nogil
+cdef _proto_boxcox1p_t *_proto_boxcox1p_t_var = &_func_boxcox1p
+from ._cdflib_wrappers cimport btdtria as _func_btdtria
+ctypedef double _proto_btdtria_t(double, double, double) noexcept nogil
+cdef _proto_btdtria_t *_proto_btdtria_t_var = &_func_btdtria
+from ._cdflib_wrappers cimport btdtrib as _func_btdtrib
+ctypedef double _proto_btdtrib_t(double, double, double) noexcept nogil
+cdef _proto_btdtrib_t *_proto_btdtrib_t_var = &_func_btdtrib
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtr "xsf_chdtr"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtrc "xsf_chdtrc"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtri "xsf_chdtri"(double, double) noexcept nogil
+from ._cdflib_wrappers cimport chdtriv as _func_chdtriv
+ctypedef double _proto_chdtriv_t(double, double) noexcept nogil
+cdef _proto_chdtriv_t *_proto_chdtriv_t_var = &_func_chdtriv
+from ._cdflib_wrappers cimport chndtr as _func_chndtr
+ctypedef double _proto_chndtr_t(double, double, double) noexcept nogil
+cdef _proto_chndtr_t *_proto_chndtr_t_var = &_func_chndtr
+from ._cdflib_wrappers cimport chndtridf as _func_chndtridf
+ctypedef double _proto_chndtridf_t(double, double, double) noexcept nogil
+cdef _proto_chndtridf_t *_proto_chndtridf_t_var = &_func_chndtridf
+from ._cdflib_wrappers cimport chndtrinc as _func_chndtrinc
+ctypedef double _proto_chndtrinc_t(double, double, double) noexcept nogil
+cdef _proto_chndtrinc_t *_proto_chndtrinc_t_var = &_func_chndtrinc
+from ._cdflib_wrappers cimport chndtrix as _func_chndtrix
+ctypedef double _proto_chndtrix_t(double, double, double) noexcept nogil
+cdef _proto_chndtrix_t *_proto_chndtrix_t_var = &_func_chndtrix
+from ._convex_analysis cimport entr as _func_entr
+ctypedef double _proto_entr_t(double) noexcept nogil
+cdef _proto_entr_t *_proto_entr_t_var = &_func_entr
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erf "cephes_erf"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erfc "cephes_erfc"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erfcinv "cephes_erfcinv"(double) noexcept nogil
+from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc
+ctypedef double complex _proto_eval_chebyc_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyc_double_complex__t *_proto_eval_chebyc_double_complex__t_var = &_func_eval_chebyc[double_complex]
+from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc
+ctypedef double _proto_eval_chebyc_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyc_double__t *_proto_eval_chebyc_double__t_var = &_func_eval_chebyc[double]
+from .orthogonal_eval cimport eval_chebyc_l as _func_eval_chebyc_l
+ctypedef double _proto_eval_chebyc_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyc_l_t *_proto_eval_chebyc_l_t_var = &_func_eval_chebyc_l
+from .orthogonal_eval cimport eval_chebys as _func_eval_chebys
+ctypedef double complex _proto_eval_chebys_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebys_double_complex__t *_proto_eval_chebys_double_complex__t_var = &_func_eval_chebys[double_complex]
+from .orthogonal_eval cimport eval_chebys as _func_eval_chebys
+ctypedef double _proto_eval_chebys_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebys_double__t *_proto_eval_chebys_double__t_var = &_func_eval_chebys[double]
+from .orthogonal_eval cimport eval_chebys_l as _func_eval_chebys_l
+ctypedef double _proto_eval_chebys_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebys_l_t *_proto_eval_chebys_l_t_var = &_func_eval_chebys_l
+from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt
+ctypedef double complex _proto_eval_chebyt_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyt_double_complex__t *_proto_eval_chebyt_double_complex__t_var = &_func_eval_chebyt[double_complex]
+from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt
+ctypedef double _proto_eval_chebyt_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyt_double__t *_proto_eval_chebyt_double__t_var = &_func_eval_chebyt[double]
+from .orthogonal_eval cimport eval_chebyt_l as _func_eval_chebyt_l
+ctypedef double _proto_eval_chebyt_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyt_l_t *_proto_eval_chebyt_l_t_var = &_func_eval_chebyt_l
+from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu
+ctypedef double complex _proto_eval_chebyu_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyu_double_complex__t *_proto_eval_chebyu_double_complex__t_var = &_func_eval_chebyu[double_complex]
+from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu
+ctypedef double _proto_eval_chebyu_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyu_double__t *_proto_eval_chebyu_double__t_var = &_func_eval_chebyu[double]
+from .orthogonal_eval cimport eval_chebyu_l as _func_eval_chebyu_l
+ctypedef double _proto_eval_chebyu_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyu_l_t *_proto_eval_chebyu_l_t_var = &_func_eval_chebyu_l
+from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer
+ctypedef double complex _proto_eval_gegenbauer_double_complex__t(double, double, double complex) noexcept nogil
+cdef _proto_eval_gegenbauer_double_complex__t *_proto_eval_gegenbauer_double_complex__t_var = &_func_eval_gegenbauer[double_complex]
+from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer
+ctypedef double _proto_eval_gegenbauer_double__t(double, double, double) noexcept nogil
+cdef _proto_eval_gegenbauer_double__t *_proto_eval_gegenbauer_double__t_var = &_func_eval_gegenbauer[double]
+from .orthogonal_eval cimport eval_gegenbauer_l as _func_eval_gegenbauer_l
+ctypedef double _proto_eval_gegenbauer_l_t(Py_ssize_t, double, double) noexcept nogil
+cdef _proto_eval_gegenbauer_l_t *_proto_eval_gegenbauer_l_t_var = &_func_eval_gegenbauer_l
+from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre
+ctypedef double complex _proto_eval_genlaguerre_double_complex__t(double, double, double complex) noexcept nogil
+cdef _proto_eval_genlaguerre_double_complex__t *_proto_eval_genlaguerre_double_complex__t_var = &_func_eval_genlaguerre[double_complex]
+from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre
+ctypedef double _proto_eval_genlaguerre_double__t(double, double, double) noexcept nogil
+cdef _proto_eval_genlaguerre_double__t *_proto_eval_genlaguerre_double__t_var = &_func_eval_genlaguerre[double]
+from .orthogonal_eval cimport eval_genlaguerre_l as _func_eval_genlaguerre_l
+ctypedef double _proto_eval_genlaguerre_l_t(Py_ssize_t, double, double) noexcept nogil
+cdef _proto_eval_genlaguerre_l_t *_proto_eval_genlaguerre_l_t_var = &_func_eval_genlaguerre_l
+from .orthogonal_eval cimport eval_hermite as _func_eval_hermite
+ctypedef double _proto_eval_hermite_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_hermite_t *_proto_eval_hermite_t_var = &_func_eval_hermite
+from .orthogonal_eval cimport eval_hermitenorm as _func_eval_hermitenorm
+ctypedef double _proto_eval_hermitenorm_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_hermitenorm_t *_proto_eval_hermitenorm_t_var = &_func_eval_hermitenorm
+from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi
+ctypedef double complex _proto_eval_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil
+cdef _proto_eval_jacobi_double_complex__t *_proto_eval_jacobi_double_complex__t_var = &_func_eval_jacobi[double_complex]
+from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi
+ctypedef double _proto_eval_jacobi_double__t(double, double, double, double) noexcept nogil
+cdef _proto_eval_jacobi_double__t *_proto_eval_jacobi_double__t_var = &_func_eval_jacobi[double]
+from .orthogonal_eval cimport eval_jacobi_l as _func_eval_jacobi_l
+ctypedef double _proto_eval_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil
+cdef _proto_eval_jacobi_l_t *_proto_eval_jacobi_l_t_var = &_func_eval_jacobi_l
+from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre
+ctypedef double complex _proto_eval_laguerre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_laguerre_double_complex__t *_proto_eval_laguerre_double_complex__t_var = &_func_eval_laguerre[double_complex]
+from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre
+ctypedef double _proto_eval_laguerre_double__t(double, double) noexcept nogil
+cdef _proto_eval_laguerre_double__t *_proto_eval_laguerre_double__t_var = &_func_eval_laguerre[double]
+from .orthogonal_eval cimport eval_laguerre_l as _func_eval_laguerre_l
+ctypedef double _proto_eval_laguerre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_laguerre_l_t *_proto_eval_laguerre_l_t_var = &_func_eval_laguerre_l
+from .orthogonal_eval cimport eval_legendre as _func_eval_legendre
+ctypedef double complex _proto_eval_legendre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_legendre_double_complex__t *_proto_eval_legendre_double_complex__t_var = &_func_eval_legendre[double_complex]
+from .orthogonal_eval cimport eval_legendre as _func_eval_legendre
+ctypedef double _proto_eval_legendre_double__t(double, double) noexcept nogil
+cdef _proto_eval_legendre_double__t *_proto_eval_legendre_double__t_var = &_func_eval_legendre[double]
+from .orthogonal_eval cimport eval_legendre_l as _func_eval_legendre_l
+ctypedef double _proto_eval_legendre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_legendre_l_t *_proto_eval_legendre_l_t_var = &_func_eval_legendre_l
+from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt
+ctypedef double complex _proto_eval_sh_chebyt_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_chebyt_double_complex__t *_proto_eval_sh_chebyt_double_complex__t_var = &_func_eval_sh_chebyt[double_complex]
+from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt
+ctypedef double _proto_eval_sh_chebyt_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_chebyt_double__t *_proto_eval_sh_chebyt_double__t_var = &_func_eval_sh_chebyt[double]
+from .orthogonal_eval cimport eval_sh_chebyt_l as _func_eval_sh_chebyt_l
+ctypedef double _proto_eval_sh_chebyt_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_chebyt_l_t *_proto_eval_sh_chebyt_l_t_var = &_func_eval_sh_chebyt_l
+from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu
+ctypedef double complex _proto_eval_sh_chebyu_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_chebyu_double_complex__t *_proto_eval_sh_chebyu_double_complex__t_var = &_func_eval_sh_chebyu[double_complex]
+from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu
+ctypedef double _proto_eval_sh_chebyu_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_chebyu_double__t *_proto_eval_sh_chebyu_double__t_var = &_func_eval_sh_chebyu[double]
+from .orthogonal_eval cimport eval_sh_chebyu_l as _func_eval_sh_chebyu_l
+ctypedef double _proto_eval_sh_chebyu_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_chebyu_l_t *_proto_eval_sh_chebyu_l_t_var = &_func_eval_sh_chebyu_l
+from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi
+ctypedef double complex _proto_eval_sh_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil
+cdef _proto_eval_sh_jacobi_double_complex__t *_proto_eval_sh_jacobi_double_complex__t_var = &_func_eval_sh_jacobi[double_complex]
+from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi
+ctypedef double _proto_eval_sh_jacobi_double__t(double, double, double, double) noexcept nogil
+cdef _proto_eval_sh_jacobi_double__t *_proto_eval_sh_jacobi_double__t_var = &_func_eval_sh_jacobi[double]
+from .orthogonal_eval cimport eval_sh_jacobi_l as _func_eval_sh_jacobi_l
+ctypedef double _proto_eval_sh_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil
+cdef _proto_eval_sh_jacobi_l_t *_proto_eval_sh_jacobi_l_t_var = &_func_eval_sh_jacobi_l
+from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre
+ctypedef double complex _proto_eval_sh_legendre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_legendre_double_complex__t *_proto_eval_sh_legendre_double_complex__t_var = &_func_eval_sh_legendre[double_complex]
+from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre
+ctypedef double _proto_eval_sh_legendre_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_legendre_double__t *_proto_eval_sh_legendre_double__t_var = &_func_eval_sh_legendre[double]
+from .orthogonal_eval cimport eval_sh_legendre_l as _func_eval_sh_legendre_l
+ctypedef double _proto_eval_sh_legendre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_legendre_l_t *_proto_eval_sh_legendre_l_t_var = &_func_eval_sh_legendre_l
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_exp10 "cephes_exp10"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_exp2 "cephes_exp2"(double) noexcept nogil
+from ._cunity cimport cexpm1 as _func_cexpm1
+ctypedef double complex _proto_cexpm1_t(double complex) noexcept nogil
+cdef _proto_cexpm1_t *_proto_cexpm1_t_var = &_func_cexpm1
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_expm1 "cephes_expm1"(double) noexcept nogil
+from ._legacy cimport expn_unsafe as _func_expn_unsafe
+ctypedef double _proto_expn_unsafe_t(double, double) noexcept nogil
+cdef _proto_expn_unsafe_t *_proto_expn_unsafe_t_var = &_func_expn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_expn_wrap "cephes_expn_wrap"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtr "xsf_fdtr"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtrc "xsf_fdtrc"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtri "xsf_fdtri"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport fdtridfd as _func_fdtridfd
+ctypedef double _proto_fdtridfd_t(double, double, double) noexcept nogil
+cdef _proto_fdtridfd_t *_proto_fdtridfd_t_var = &_func_fdtridfd
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtr "xsf_gdtr"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtrc "xsf_gdtrc"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport gdtria as _func_gdtria
+ctypedef double _proto_gdtria_t(double, double, double) noexcept nogil
+cdef _proto_gdtria_t *_proto_gdtria_t_var = &_func_gdtria
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtrib "xsf_gdtrib"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport gdtrix as _func_gdtrix
+ctypedef double _proto_gdtrix_t(double, double, double) noexcept nogil
+cdef _proto_gdtrix_t *_proto_gdtrix_t_var = &_func_gdtrix
+from ._convex_analysis cimport huber as _func_huber
+ctypedef double _proto_huber_t(double, double) noexcept nogil
+cdef _proto_huber_t *_proto_huber_t_var = &_func_huber
+from ._hyp0f1 cimport _hyp0f1_cmplx as _func__hyp0f1_cmplx
+ctypedef double complex _proto__hyp0f1_cmplx_t(double, double complex) noexcept nogil
+cdef _proto__hyp0f1_cmplx_t *_proto__hyp0f1_cmplx_t_var = &_func__hyp0f1_cmplx
+from ._hyp0f1 cimport _hyp0f1_real as _func__hyp0f1_real
+ctypedef double _proto__hyp0f1_real_t(double, double) noexcept nogil
+cdef _proto__hyp0f1_real_t *_proto__hyp0f1_real_t_var = &_func__hyp0f1_real
+cdef extern from r"_ufuncs_defs.h":
+    cdef double complex _func_chyp1f1_wrap "chyp1f1_wrap"(double, double, double complex) noexcept nogil
+from ._hypergeometric cimport hyperu as _func_hyperu
+ctypedef double _proto_hyperu_t(double, double, double) noexcept nogil
+cdef _proto_hyperu_t *_proto_hyperu_t_var = &_func_hyperu
+from ._boxcox cimport inv_boxcox as _func_inv_boxcox
+ctypedef double _proto_inv_boxcox_t(double, double) noexcept nogil
+cdef _proto_inv_boxcox_t *_proto_inv_boxcox_t_var = &_func_inv_boxcox
+from ._boxcox cimport inv_boxcox1p as _func_inv_boxcox1p
+ctypedef double _proto_inv_boxcox1p_t(double, double) noexcept nogil
+cdef _proto_inv_boxcox1p_t *_proto_inv_boxcox1p_t_var = &_func_inv_boxcox1p
+from ._convex_analysis cimport kl_div as _func_kl_div
+ctypedef double _proto_kl_div_t(double, double) noexcept nogil
+cdef _proto_kl_div_t *_proto_kl_div_t_var = &_func_kl_div
+from ._legacy cimport kn_unsafe as _func_kn_unsafe
+ctypedef double _proto_kn_unsafe_t(double, double) noexcept nogil
+cdef _proto_kn_unsafe_t *_proto_kn_unsafe_t_var = &_func_kn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_special_cyl_bessel_k_int "special_cyl_bessel_k_int"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogi "xsf_kolmogi"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogorov "xsf_kolmogorov"(double) noexcept nogil
+from ._cunity cimport clog1p as _func_clog1p
+ctypedef double complex _proto_clog1p_t(double complex) noexcept nogil
+cdef _proto_clog1p_t *_proto_clog1p_t_var = &_func_clog1p
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_log1p "cephes_log1p"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_pmv_wrap "pmv_wrap"(double, double, double) noexcept nogil
+from ._legacy cimport nbdtr_unsafe as _func_nbdtr_unsafe
+ctypedef double _proto_nbdtr_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtr_unsafe_t *_proto_nbdtr_unsafe_t_var = &_func_nbdtr_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtr_wrap "cephes_nbdtr_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport nbdtrc_unsafe as _func_nbdtrc_unsafe
+ctypedef double _proto_nbdtrc_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrc_unsafe_t *_proto_nbdtrc_unsafe_t_var = &_func_nbdtrc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtrc_wrap "cephes_nbdtrc_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport nbdtri_unsafe as _func_nbdtri_unsafe
+ctypedef double _proto_nbdtri_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtri_unsafe_t *_proto_nbdtri_unsafe_t_var = &_func_nbdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtri_wrap "cephes_nbdtri_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport nbdtrik as _func_nbdtrik
+ctypedef double _proto_nbdtrik_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrik_t *_proto_nbdtrik_t_var = &_func_nbdtrik
+from ._cdflib_wrappers cimport nbdtrin as _func_nbdtrin
+ctypedef double _proto_nbdtrin_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrin_t *_proto_nbdtrin_t_var = &_func_nbdtrin
+from ._cdflib_wrappers cimport ncfdtridfd as _func_ncfdtridfd
+ctypedef double _proto_ncfdtridfd_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtridfd_t *_proto_ncfdtridfd_t_var = &_func_ncfdtridfd
+from ._cdflib_wrappers cimport ncfdtridfn as _func_ncfdtridfn
+ctypedef double _proto_ncfdtridfn_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtridfn_t *_proto_ncfdtridfn_t_var = &_func_ncfdtridfn
+from ._cdflib_wrappers cimport ncfdtrinc as _func_ncfdtrinc
+ctypedef double _proto_ncfdtrinc_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtrinc_t *_proto_ncfdtrinc_t_var = &_func_ncfdtrinc
+from ._cdflib_wrappers cimport nctdtridf as _func_nctdtridf
+ctypedef double _proto_nctdtridf_t(double, double, double) noexcept nogil
+cdef _proto_nctdtridf_t *_proto_nctdtridf_t_var = &_func_nctdtridf
+from ._cdflib_wrappers cimport nctdtrinc as _func_nctdtrinc
+ctypedef double _proto_nctdtrinc_t(double, double, double) noexcept nogil
+cdef _proto_nctdtrinc_t *_proto_nctdtrinc_t_var = &_func_nctdtrinc
+from ._cdflib_wrappers cimport nctdtrit as _func_nctdtrit
+ctypedef double _proto_nctdtrit_t(double, double, double) noexcept nogil
+cdef _proto_nctdtrit_t *_proto_nctdtrit_t_var = &_func_nctdtrit
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_ndtr "xsf_ndtr"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_ndtri "xsf_ndtri"(double) noexcept nogil
+from ._ndtri_exp cimport ndtri_exp as _func_ndtri_exp
+ctypedef double _proto_ndtri_exp_t(double) noexcept nogil
+cdef _proto_ndtri_exp_t *_proto_ndtri_exp_t_var = &_func_ndtri_exp
+from ._cdflib_wrappers cimport nrdtrimn as _func_nrdtrimn
+ctypedef double _proto_nrdtrimn_t(double, double, double) noexcept nogil
+cdef _proto_nrdtrimn_t *_proto_nrdtrimn_t_var = &_func_nrdtrimn
+from ._cdflib_wrappers cimport nrdtrisd as _func_nrdtrisd
+ctypedef double _proto_nrdtrisd_t(double, double, double) noexcept nogil
+cdef _proto_nrdtrisd_t *_proto_nrdtrisd_t_var = &_func_nrdtrisd
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_owens_t "xsf_owens_t"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_pdtr "xsf_pdtr"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_pdtrc "xsf_pdtrc"(double, double) noexcept nogil
+from ._legacy cimport pdtri_unsafe as _func_pdtri_unsafe
+ctypedef double _proto_pdtri_unsafe_t(double, double) noexcept nogil
+cdef _proto_pdtri_unsafe_t *_proto_pdtri_unsafe_t_var = &_func_pdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_pdtri_wrap "cephes_pdtri_wrap"(Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport pdtrik as _func_pdtrik
+ctypedef double _proto_pdtrik_t(double, double) noexcept nogil
+cdef _proto_pdtrik_t *_proto_pdtrik_t_var = &_func_pdtrik
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_poch "cephes_poch"(double, double) noexcept nogil
+from ._convex_analysis cimport pseudo_huber as _func_pseudo_huber
+ctypedef double _proto_pseudo_huber_t(double, double) noexcept nogil
+cdef _proto_pseudo_huber_t *_proto_pseudo_huber_t_var = &_func_pseudo_huber
+from ._convex_analysis cimport rel_entr as _func_rel_entr
+ctypedef double _proto_rel_entr_t(double, double) noexcept nogil
+cdef _proto_rel_entr_t *_proto_rel_entr_t_var = &_func_rel_entr
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_round "cephes_round"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_cshichi "xsf_cshichi"(double complex, double complex *, double complex *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_shichi "xsf_shichi"(double, double *, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_csici "xsf_csici"(double complex, double complex *, double complex *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_sici "xsf_sici"(double, double *, double *) noexcept nogil
+from ._legacy cimport smirnov_unsafe as _func_smirnov_unsafe
+ctypedef double _proto_smirnov_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnov_unsafe_t *_proto_smirnov_unsafe_t_var = &_func_smirnov_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnov_wrap "cephes_smirnov_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovi_unsafe as _func_smirnovi_unsafe
+ctypedef double _proto_smirnovi_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovi_unsafe_t *_proto_smirnovi_unsafe_t_var = &_func_smirnovi_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovi_wrap "cephes_smirnovi_wrap"(Py_ssize_t, double) noexcept nogil
+from ._spence cimport cspence as _func_cspence
+ctypedef double complex _proto_cspence_t(double complex) noexcept nogil
+cdef _proto_cspence_t *_proto_cspence_t_var = &_func_cspence
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_spence "cephes_spence"(double) noexcept nogil
+from ._cdflib_wrappers cimport stdtr as _func_stdtr
+ctypedef double _proto_stdtr_t(double, double) noexcept nogil
+cdef _proto_stdtr_t *_proto_stdtr_t_var = &_func_stdtr
+from ._cdflib_wrappers cimport stdtridf as _func_stdtridf
+ctypedef double _proto_stdtridf_t(double, double) noexcept nogil
+cdef _proto_stdtridf_t *_proto_stdtridf_t_var = &_func_stdtridf
+from ._cdflib_wrappers cimport stdtrit as _func_stdtrit
+ctypedef double _proto_stdtrit_t(double, double) noexcept nogil
+cdef _proto_stdtrit_t *_proto_stdtrit_t_var = &_func_stdtrit
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_tukeylambdacdf "xsf_tukeylambdacdf"(double, double) noexcept nogil
+from ._xlogy cimport xlog1py as _func_xlog1py
+ctypedef double _proto_xlog1py_double__t(double, double) noexcept nogil
+cdef _proto_xlog1py_double__t *_proto_xlog1py_double__t_var = &_func_xlog1py[double]
+from ._xlogy cimport xlog1py as _func_xlog1py
+ctypedef double complex _proto_xlog1py_double_complex__t(double complex, double complex) noexcept nogil
+cdef _proto_xlog1py_double_complex__t *_proto_xlog1py_double_complex__t_var = &_func_xlog1py[double_complex]
+from ._xlogy cimport xlogy as _func_xlogy
+ctypedef double _proto_xlogy_double__t(double, double) noexcept nogil
+cdef _proto_xlogy_double__t *_proto_xlogy_double__t_var = &_func_xlogy[double]
+from ._xlogy cimport xlogy as _func_xlogy
+ctypedef double complex _proto_xlogy_double_complex__t(double complex, double complex) noexcept nogil
+cdef _proto_xlogy_double_complex__t *_proto_xlogy_double_complex__t_var = &_func_xlogy[double_complex]
+from ._legacy cimport yn_unsafe as _func_yn_unsafe
+ctypedef double _proto_yn_unsafe_t(double, double) noexcept nogil
+cdef _proto_yn_unsafe_t *_proto_yn_unsafe_t_var = &_func_yn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_yn_wrap "cephes_yn_wrap"(Py_ssize_t, double) noexcept nogil
+cdef np.PyUFuncGenericFunction ufunc__beta_pdf_loops[2]
+cdef void *ufunc__beta_pdf_ptr[4]
+cdef void *ufunc__beta_pdf_data[2]
+cdef char ufunc__beta_pdf_types[8]
+cdef char *ufunc__beta_pdf_doc = (
+    "_beta_pdf(x, a, b)\n"
+    "\n"
+    "Probability density function of beta distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__beta_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__beta_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__beta_pdf_types[0] = NPY_FLOAT
+ufunc__beta_pdf_types[1] = NPY_FLOAT
+ufunc__beta_pdf_types[2] = NPY_FLOAT
+ufunc__beta_pdf_types[3] = NPY_FLOAT
+ufunc__beta_pdf_types[4] = NPY_DOUBLE
+ufunc__beta_pdf_types[5] = NPY_DOUBLE
+ufunc__beta_pdf_types[6] = NPY_DOUBLE
+ufunc__beta_pdf_types[7] = NPY_DOUBLE
+ufunc__beta_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_pdf_float
+ufunc__beta_pdf_ptr[2*0+1] = ("_beta_pdf")
+ufunc__beta_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_pdf_double
+ufunc__beta_pdf_ptr[2*1+1] = ("_beta_pdf")
+ufunc__beta_pdf_data[0] = &ufunc__beta_pdf_ptr[2*0]
+ufunc__beta_pdf_data[1] = &ufunc__beta_pdf_ptr[2*1]
+_beta_pdf = np.PyUFunc_FromFuncAndData(ufunc__beta_pdf_loops, ufunc__beta_pdf_data, ufunc__beta_pdf_types, 2, 3, 1, 0, "_beta_pdf", ufunc__beta_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__beta_ppf_loops[2]
+cdef void *ufunc__beta_ppf_ptr[4]
+cdef void *ufunc__beta_ppf_data[2]
+cdef char ufunc__beta_ppf_types[8]
+cdef char *ufunc__beta_ppf_doc = (
+    "_beta_ppf(x, a, b)\n"
+    "\n"
+    "Percent point function of beta distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__beta_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__beta_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__beta_ppf_types[0] = NPY_FLOAT
+ufunc__beta_ppf_types[1] = NPY_FLOAT
+ufunc__beta_ppf_types[2] = NPY_FLOAT
+ufunc__beta_ppf_types[3] = NPY_FLOAT
+ufunc__beta_ppf_types[4] = NPY_DOUBLE
+ufunc__beta_ppf_types[5] = NPY_DOUBLE
+ufunc__beta_ppf_types[6] = NPY_DOUBLE
+ufunc__beta_ppf_types[7] = NPY_DOUBLE
+ufunc__beta_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_ppf_float
+ufunc__beta_ppf_ptr[2*0+1] = ("_beta_ppf")
+ufunc__beta_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_ppf_double
+ufunc__beta_ppf_ptr[2*1+1] = ("_beta_ppf")
+ufunc__beta_ppf_data[0] = &ufunc__beta_ppf_ptr[2*0]
+ufunc__beta_ppf_data[1] = &ufunc__beta_ppf_ptr[2*1]
+_beta_ppf = np.PyUFunc_FromFuncAndData(ufunc__beta_ppf_loops, ufunc__beta_ppf_data, ufunc__beta_ppf_types, 2, 3, 1, 0, "_beta_ppf", ufunc__beta_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_cdf_loops[2]
+cdef void *ufunc__binom_cdf_ptr[4]
+cdef void *ufunc__binom_cdf_data[2]
+cdef char ufunc__binom_cdf_types[8]
+cdef char *ufunc__binom_cdf_doc = (
+    "_binom_cdf(x, n, p)\n"
+    "\n"
+    "Cumulative density function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_cdf_types[0] = NPY_FLOAT
+ufunc__binom_cdf_types[1] = NPY_FLOAT
+ufunc__binom_cdf_types[2] = NPY_FLOAT
+ufunc__binom_cdf_types[3] = NPY_FLOAT
+ufunc__binom_cdf_types[4] = NPY_DOUBLE
+ufunc__binom_cdf_types[5] = NPY_DOUBLE
+ufunc__binom_cdf_types[6] = NPY_DOUBLE
+ufunc__binom_cdf_types[7] = NPY_DOUBLE
+ufunc__binom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_cdf_float
+ufunc__binom_cdf_ptr[2*0+1] = ("_binom_cdf")
+ufunc__binom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_cdf_double
+ufunc__binom_cdf_ptr[2*1+1] = ("_binom_cdf")
+ufunc__binom_cdf_data[0] = &ufunc__binom_cdf_ptr[2*0]
+ufunc__binom_cdf_data[1] = &ufunc__binom_cdf_ptr[2*1]
+_binom_cdf = np.PyUFunc_FromFuncAndData(ufunc__binom_cdf_loops, ufunc__binom_cdf_data, ufunc__binom_cdf_types, 2, 3, 1, 0, "_binom_cdf", ufunc__binom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_isf_loops[2]
+cdef void *ufunc__binom_isf_ptr[4]
+cdef void *ufunc__binom_isf_data[2]
+cdef char ufunc__binom_isf_types[8]
+cdef char *ufunc__binom_isf_doc = (
+    "_binom_isf(x, n, p)\n"
+    "\n"
+    "Inverse survival function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_isf_types[0] = NPY_FLOAT
+ufunc__binom_isf_types[1] = NPY_FLOAT
+ufunc__binom_isf_types[2] = NPY_FLOAT
+ufunc__binom_isf_types[3] = NPY_FLOAT
+ufunc__binom_isf_types[4] = NPY_DOUBLE
+ufunc__binom_isf_types[5] = NPY_DOUBLE
+ufunc__binom_isf_types[6] = NPY_DOUBLE
+ufunc__binom_isf_types[7] = NPY_DOUBLE
+ufunc__binom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_isf_float
+ufunc__binom_isf_ptr[2*0+1] = ("_binom_isf")
+ufunc__binom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_isf_double
+ufunc__binom_isf_ptr[2*1+1] = ("_binom_isf")
+ufunc__binom_isf_data[0] = &ufunc__binom_isf_ptr[2*0]
+ufunc__binom_isf_data[1] = &ufunc__binom_isf_ptr[2*1]
+_binom_isf = np.PyUFunc_FromFuncAndData(ufunc__binom_isf_loops, ufunc__binom_isf_data, ufunc__binom_isf_types, 2, 3, 1, 0, "_binom_isf", ufunc__binom_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_pmf_loops[2]
+cdef void *ufunc__binom_pmf_ptr[4]
+cdef void *ufunc__binom_pmf_data[2]
+cdef char ufunc__binom_pmf_types[8]
+cdef char *ufunc__binom_pmf_doc = (
+    "_binom_pmf(x, n, p)\n"
+    "\n"
+    "Probability mass function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_pmf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_pmf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_pmf_types[0] = NPY_FLOAT
+ufunc__binom_pmf_types[1] = NPY_FLOAT
+ufunc__binom_pmf_types[2] = NPY_FLOAT
+ufunc__binom_pmf_types[3] = NPY_FLOAT
+ufunc__binom_pmf_types[4] = NPY_DOUBLE
+ufunc__binom_pmf_types[5] = NPY_DOUBLE
+ufunc__binom_pmf_types[6] = NPY_DOUBLE
+ufunc__binom_pmf_types[7] = NPY_DOUBLE
+ufunc__binom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_pmf_float
+ufunc__binom_pmf_ptr[2*0+1] = ("_binom_pmf")
+ufunc__binom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_pmf_double
+ufunc__binom_pmf_ptr[2*1+1] = ("_binom_pmf")
+ufunc__binom_pmf_data[0] = &ufunc__binom_pmf_ptr[2*0]
+ufunc__binom_pmf_data[1] = &ufunc__binom_pmf_ptr[2*1]
+_binom_pmf = np.PyUFunc_FromFuncAndData(ufunc__binom_pmf_loops, ufunc__binom_pmf_data, ufunc__binom_pmf_types, 2, 3, 1, 0, "_binom_pmf", ufunc__binom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_ppf_loops[2]
+cdef void *ufunc__binom_ppf_ptr[4]
+cdef void *ufunc__binom_ppf_data[2]
+cdef char ufunc__binom_ppf_types[8]
+cdef char *ufunc__binom_ppf_doc = (
+    "_binom_ppf(x, n, p)\n"
+    "\n"
+    "Percent point function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_ppf_types[0] = NPY_FLOAT
+ufunc__binom_ppf_types[1] = NPY_FLOAT
+ufunc__binom_ppf_types[2] = NPY_FLOAT
+ufunc__binom_ppf_types[3] = NPY_FLOAT
+ufunc__binom_ppf_types[4] = NPY_DOUBLE
+ufunc__binom_ppf_types[5] = NPY_DOUBLE
+ufunc__binom_ppf_types[6] = NPY_DOUBLE
+ufunc__binom_ppf_types[7] = NPY_DOUBLE
+ufunc__binom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_ppf_float
+ufunc__binom_ppf_ptr[2*0+1] = ("_binom_ppf")
+ufunc__binom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_ppf_double
+ufunc__binom_ppf_ptr[2*1+1] = ("_binom_ppf")
+ufunc__binom_ppf_data[0] = &ufunc__binom_ppf_ptr[2*0]
+ufunc__binom_ppf_data[1] = &ufunc__binom_ppf_ptr[2*1]
+_binom_ppf = np.PyUFunc_FromFuncAndData(ufunc__binom_ppf_loops, ufunc__binom_ppf_data, ufunc__binom_ppf_types, 2, 3, 1, 0, "_binom_ppf", ufunc__binom_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_sf_loops[2]
+cdef void *ufunc__binom_sf_ptr[4]
+cdef void *ufunc__binom_sf_data[2]
+cdef char ufunc__binom_sf_types[8]
+cdef char *ufunc__binom_sf_doc = (
+    "_binom_sf(x, n, p)\n"
+    "\n"
+    "Survival function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_sf_types[0] = NPY_FLOAT
+ufunc__binom_sf_types[1] = NPY_FLOAT
+ufunc__binom_sf_types[2] = NPY_FLOAT
+ufunc__binom_sf_types[3] = NPY_FLOAT
+ufunc__binom_sf_types[4] = NPY_DOUBLE
+ufunc__binom_sf_types[5] = NPY_DOUBLE
+ufunc__binom_sf_types[6] = NPY_DOUBLE
+ufunc__binom_sf_types[7] = NPY_DOUBLE
+ufunc__binom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_sf_float
+ufunc__binom_sf_ptr[2*0+1] = ("_binom_sf")
+ufunc__binom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_sf_double
+ufunc__binom_sf_ptr[2*1+1] = ("_binom_sf")
+ufunc__binom_sf_data[0] = &ufunc__binom_sf_ptr[2*0]
+ufunc__binom_sf_data[1] = &ufunc__binom_sf_ptr[2*1]
+_binom_sf = np.PyUFunc_FromFuncAndData(ufunc__binom_sf_loops, ufunc__binom_sf_data, ufunc__binom_sf_types, 2, 3, 1, 0, "_binom_sf", ufunc__binom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cauchy_isf_loops[2]
+cdef void *ufunc__cauchy_isf_ptr[4]
+cdef void *ufunc__cauchy_isf_data[2]
+cdef char ufunc__cauchy_isf_types[8]
+cdef char *ufunc__cauchy_isf_doc = (
+    "_cauchy_isf(p, loc, scale)\n"
+    "\n"
+    "Inverse survival function of the Cauchy distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probabilities\n"
+    "loc : array_like\n"
+    "    Location parameter of the distribution.\n"
+    "scale : array_like\n"
+    "    Scale parameter of the distribution.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__cauchy_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__cauchy_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__cauchy_isf_types[0] = NPY_FLOAT
+ufunc__cauchy_isf_types[1] = NPY_FLOAT
+ufunc__cauchy_isf_types[2] = NPY_FLOAT
+ufunc__cauchy_isf_types[3] = NPY_FLOAT
+ufunc__cauchy_isf_types[4] = NPY_DOUBLE
+ufunc__cauchy_isf_types[5] = NPY_DOUBLE
+ufunc__cauchy_isf_types[6] = NPY_DOUBLE
+ufunc__cauchy_isf_types[7] = NPY_DOUBLE
+ufunc__cauchy_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_isf_float
+ufunc__cauchy_isf_ptr[2*0+1] = ("_cauchy_isf")
+ufunc__cauchy_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_isf_double
+ufunc__cauchy_isf_ptr[2*1+1] = ("_cauchy_isf")
+ufunc__cauchy_isf_data[0] = &ufunc__cauchy_isf_ptr[2*0]
+ufunc__cauchy_isf_data[1] = &ufunc__cauchy_isf_ptr[2*1]
+_cauchy_isf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_isf_loops, ufunc__cauchy_isf_data, ufunc__cauchy_isf_types, 2, 3, 1, 0, "_cauchy_isf", ufunc__cauchy_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cauchy_ppf_loops[2]
+cdef void *ufunc__cauchy_ppf_ptr[4]
+cdef void *ufunc__cauchy_ppf_data[2]
+cdef char ufunc__cauchy_ppf_types[8]
+cdef char *ufunc__cauchy_ppf_doc = (
+    "_cauchy_ppf(p, loc, scale)\n"
+    "\n"
+    "Percent point function (i.e. quantile) of the Cauchy distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probabilities\n"
+    "loc : array_like\n"
+    "    Location parameter of the distribution.\n"
+    "scale : array_like\n"
+    "    Scale parameter of the distribution.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__cauchy_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__cauchy_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__cauchy_ppf_types[0] = NPY_FLOAT
+ufunc__cauchy_ppf_types[1] = NPY_FLOAT
+ufunc__cauchy_ppf_types[2] = NPY_FLOAT
+ufunc__cauchy_ppf_types[3] = NPY_FLOAT
+ufunc__cauchy_ppf_types[4] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[5] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[6] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[7] = NPY_DOUBLE
+ufunc__cauchy_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_ppf_float
+ufunc__cauchy_ppf_ptr[2*0+1] = ("_cauchy_ppf")
+ufunc__cauchy_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_ppf_double
+ufunc__cauchy_ppf_ptr[2*1+1] = ("_cauchy_ppf")
+ufunc__cauchy_ppf_data[0] = &ufunc__cauchy_ppf_ptr[2*0]
+ufunc__cauchy_ppf_data[1] = &ufunc__cauchy_ppf_ptr[2*1]
+_cauchy_ppf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_ppf_loops, ufunc__cauchy_ppf_data, ufunc__cauchy_ppf_types, 2, 3, 1, 0, "_cauchy_ppf", ufunc__cauchy_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cosine_cdf_loops[2]
+cdef void *ufunc__cosine_cdf_ptr[4]
+cdef void *ufunc__cosine_cdf_data[2]
+cdef char ufunc__cosine_cdf_types[4]
+cdef char *ufunc__cosine_cdf_doc = (
+    "_cosine_cdf(x)\n"
+    "\n"
+    "Cumulative distribution function (CDF) of the cosine distribution::\n"
+    "\n"
+    "             {             0,              x < -pi\n"
+    "    cdf(x) = { (pi + x + sin(x))/(2*pi),   -pi <= x <= pi\n"
+    "             {             1,              x > pi\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The cosine distribution CDF evaluated at `x`.")
+ufunc__cosine_cdf_loops[0] = loop_d_d__As_f_f
+ufunc__cosine_cdf_loops[1] = loop_d_d__As_d_d
+ufunc__cosine_cdf_types[0] = NPY_FLOAT
+ufunc__cosine_cdf_types[1] = NPY_FLOAT
+ufunc__cosine_cdf_types[2] = NPY_DOUBLE
+ufunc__cosine_cdf_types[3] = NPY_DOUBLE
+ufunc__cosine_cdf_ptr[2*0] = _func_cosine_cdf
+ufunc__cosine_cdf_ptr[2*0+1] = ("_cosine_cdf")
+ufunc__cosine_cdf_ptr[2*1] = _func_cosine_cdf
+ufunc__cosine_cdf_ptr[2*1+1] = ("_cosine_cdf")
+ufunc__cosine_cdf_data[0] = &ufunc__cosine_cdf_ptr[2*0]
+ufunc__cosine_cdf_data[1] = &ufunc__cosine_cdf_ptr[2*1]
+_cosine_cdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_cdf_loops, ufunc__cosine_cdf_data, ufunc__cosine_cdf_types, 2, 1, 1, 0, "_cosine_cdf", ufunc__cosine_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cosine_invcdf_loops[2]
+cdef void *ufunc__cosine_invcdf_ptr[4]
+cdef void *ufunc__cosine_invcdf_data[2]
+cdef char ufunc__cosine_invcdf_types[4]
+cdef char *ufunc__cosine_invcdf_doc = (
+    "_cosine_invcdf(p)\n"
+    "\n"
+    "Inverse of the cumulative distribution function (CDF) of the cosine\n"
+    "distribution.\n"
+    "\n"
+    "The CDF of the cosine distribution is::\n"
+    "\n"
+    "    cdf(x) = (pi + x + sin(x))/(2*pi)\n"
+    "\n"
+    "This function computes the inverse of cdf(x).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    `p` must contain real numbers in the interval ``0 <= p <= 1``.\n"
+    "    `nan` is returned for values of `p` outside the interval [0, 1].\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The inverse of the cosine distribution CDF evaluated at `p`.")
+ufunc__cosine_invcdf_loops[0] = loop_d_d__As_f_f
+ufunc__cosine_invcdf_loops[1] = loop_d_d__As_d_d
+ufunc__cosine_invcdf_types[0] = NPY_FLOAT
+ufunc__cosine_invcdf_types[1] = NPY_FLOAT
+ufunc__cosine_invcdf_types[2] = NPY_DOUBLE
+ufunc__cosine_invcdf_types[3] = NPY_DOUBLE
+ufunc__cosine_invcdf_ptr[2*0] = _func_cosine_invcdf
+ufunc__cosine_invcdf_ptr[2*0+1] = ("_cosine_invcdf")
+ufunc__cosine_invcdf_ptr[2*1] = _func_cosine_invcdf
+ufunc__cosine_invcdf_ptr[2*1+1] = ("_cosine_invcdf")
+ufunc__cosine_invcdf_data[0] = &ufunc__cosine_invcdf_ptr[2*0]
+ufunc__cosine_invcdf_data[1] = &ufunc__cosine_invcdf_ptr[2*1]
+_cosine_invcdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_invcdf_loops, ufunc__cosine_invcdf_data, ufunc__cosine_invcdf_types, 2, 1, 1, 0, "_cosine_invcdf", ufunc__cosine_invcdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ellip_harm_loops[3]
+cdef void *ufunc__ellip_harm_ptr[6]
+cdef void *ufunc__ellip_harm_data[3]
+cdef char ufunc__ellip_harm_types[24]
+cdef char *ufunc__ellip_harm_doc = (
+    "Internal function, use `ellip_harm` instead.")
+ufunc__ellip_harm_loops[0] = loop_d_ddddddd__As_fffffff_f
+ufunc__ellip_harm_loops[1] = loop_d_ddiiddd__As_ddllddd_d
+ufunc__ellip_harm_loops[2] = loop_d_ddddddd__As_ddddddd_d
+ufunc__ellip_harm_types[0] = NPY_FLOAT
+ufunc__ellip_harm_types[1] = NPY_FLOAT
+ufunc__ellip_harm_types[2] = NPY_FLOAT
+ufunc__ellip_harm_types[3] = NPY_FLOAT
+ufunc__ellip_harm_types[4] = NPY_FLOAT
+ufunc__ellip_harm_types[5] = NPY_FLOAT
+ufunc__ellip_harm_types[6] = NPY_FLOAT
+ufunc__ellip_harm_types[7] = NPY_FLOAT
+ufunc__ellip_harm_types[8] = NPY_DOUBLE
+ufunc__ellip_harm_types[9] = NPY_DOUBLE
+ufunc__ellip_harm_types[10] = NPY_LONG
+ufunc__ellip_harm_types[11] = NPY_LONG
+ufunc__ellip_harm_types[12] = NPY_DOUBLE
+ufunc__ellip_harm_types[13] = NPY_DOUBLE
+ufunc__ellip_harm_types[14] = NPY_DOUBLE
+ufunc__ellip_harm_types[15] = NPY_DOUBLE
+ufunc__ellip_harm_types[16] = NPY_DOUBLE
+ufunc__ellip_harm_types[17] = NPY_DOUBLE
+ufunc__ellip_harm_types[18] = NPY_DOUBLE
+ufunc__ellip_harm_types[19] = NPY_DOUBLE
+ufunc__ellip_harm_types[20] = NPY_DOUBLE
+ufunc__ellip_harm_types[21] = NPY_DOUBLE
+ufunc__ellip_harm_types[22] = NPY_DOUBLE
+ufunc__ellip_harm_types[23] = NPY_DOUBLE
+ufunc__ellip_harm_ptr[2*0] = _func_ellip_harmonic_unsafe
+ufunc__ellip_harm_ptr[2*0+1] = ("_ellip_harm")
+ufunc__ellip_harm_ptr[2*1] = _func_ellip_harmonic
+ufunc__ellip_harm_ptr[2*1+1] = ("_ellip_harm")
+ufunc__ellip_harm_ptr[2*2] = _func_ellip_harmonic_unsafe
+ufunc__ellip_harm_ptr[2*2+1] = ("_ellip_harm")
+ufunc__ellip_harm_data[0] = &ufunc__ellip_harm_ptr[2*0]
+ufunc__ellip_harm_data[1] = &ufunc__ellip_harm_ptr[2*1]
+ufunc__ellip_harm_data[2] = &ufunc__ellip_harm_ptr[2*2]
+_ellip_harm = np.PyUFunc_FromFuncAndData(ufunc__ellip_harm_loops, ufunc__ellip_harm_data, ufunc__ellip_harm_types, 3, 7, 1, 0, "_ellip_harm", ufunc__ellip_harm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__factorial_loops[2]
+cdef void *ufunc__factorial_ptr[4]
+cdef void *ufunc__factorial_data[2]
+cdef char ufunc__factorial_types[4]
+cdef char *ufunc__factorial_doc = (
+    "Internal function, do not use.")
+ufunc__factorial_loops[0] = loop_d_d__As_f_f
+ufunc__factorial_loops[1] = loop_d_d__As_d_d
+ufunc__factorial_types[0] = NPY_FLOAT
+ufunc__factorial_types[1] = NPY_FLOAT
+ufunc__factorial_types[2] = NPY_DOUBLE
+ufunc__factorial_types[3] = NPY_DOUBLE
+ufunc__factorial_ptr[2*0] = _func__factorial
+ufunc__factorial_ptr[2*0+1] = ("_factorial")
+ufunc__factorial_ptr[2*1] = _func__factorial
+ufunc__factorial_ptr[2*1+1] = ("_factorial")
+ufunc__factorial_data[0] = &ufunc__factorial_ptr[2*0]
+ufunc__factorial_data[1] = &ufunc__factorial_ptr[2*1]
+_factorial = np.PyUFunc_FromFuncAndData(ufunc__factorial_loops, ufunc__factorial_data, ufunc__factorial_types, 2, 1, 1, 0, "_factorial", ufunc__factorial_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_cdf_loops[2]
+cdef void *ufunc__hypergeom_cdf_ptr[4]
+cdef void *ufunc__hypergeom_cdf_data[2]
+cdef char ufunc__hypergeom_cdf_types[10]
+cdef char *ufunc__hypergeom_cdf_doc = (
+    "_hypergeom_cdf(x, r, N, M)\n"
+    "\n"
+    "Cumulative density function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_cdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_cdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_cdf_types[0] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[1] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[2] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[3] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[4] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_float
+ufunc__hypergeom_cdf_ptr[2*0+1] = ("_hypergeom_cdf")
+ufunc__hypergeom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_double
+ufunc__hypergeom_cdf_ptr[2*1+1] = ("_hypergeom_cdf")
+ufunc__hypergeom_cdf_data[0] = &ufunc__hypergeom_cdf_ptr[2*0]
+ufunc__hypergeom_cdf_data[1] = &ufunc__hypergeom_cdf_ptr[2*1]
+_hypergeom_cdf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_cdf_loops, ufunc__hypergeom_cdf_data, ufunc__hypergeom_cdf_types, 2, 4, 1, 0, "_hypergeom_cdf", ufunc__hypergeom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_mean_loops[2]
+cdef void *ufunc__hypergeom_mean_ptr[4]
+cdef void *ufunc__hypergeom_mean_data[2]
+cdef char ufunc__hypergeom_mean_types[8]
+cdef char *ufunc__hypergeom_mean_doc = (
+    "_hypergeom_mean(r, N, M)\n"
+    "\n"
+    "Mean of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_mean_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_mean_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_mean_types[0] = NPY_FLOAT
+ufunc__hypergeom_mean_types[1] = NPY_FLOAT
+ufunc__hypergeom_mean_types[2] = NPY_FLOAT
+ufunc__hypergeom_mean_types[3] = NPY_FLOAT
+ufunc__hypergeom_mean_types[4] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[5] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[6] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[7] = NPY_DOUBLE
+ufunc__hypergeom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_mean_float
+ufunc__hypergeom_mean_ptr[2*0+1] = ("_hypergeom_mean")
+ufunc__hypergeom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_mean_double
+ufunc__hypergeom_mean_ptr[2*1+1] = ("_hypergeom_mean")
+ufunc__hypergeom_mean_data[0] = &ufunc__hypergeom_mean_ptr[2*0]
+ufunc__hypergeom_mean_data[1] = &ufunc__hypergeom_mean_ptr[2*1]
+_hypergeom_mean = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_mean_loops, ufunc__hypergeom_mean_data, ufunc__hypergeom_mean_types, 2, 3, 1, 0, "_hypergeom_mean", ufunc__hypergeom_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_pmf_loops[2]
+cdef void *ufunc__hypergeom_pmf_ptr[4]
+cdef void *ufunc__hypergeom_pmf_data[2]
+cdef char ufunc__hypergeom_pmf_types[10]
+cdef char *ufunc__hypergeom_pmf_doc = (
+    "_hypergeom_pmf(x, r, N, M)\n"
+    "\n"
+    "Probability mass function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_pmf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_pmf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_pmf_types[0] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[1] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[2] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[3] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[4] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_float
+ufunc__hypergeom_pmf_ptr[2*0+1] = ("_hypergeom_pmf")
+ufunc__hypergeom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_double
+ufunc__hypergeom_pmf_ptr[2*1+1] = ("_hypergeom_pmf")
+ufunc__hypergeom_pmf_data[0] = &ufunc__hypergeom_pmf_ptr[2*0]
+ufunc__hypergeom_pmf_data[1] = &ufunc__hypergeom_pmf_ptr[2*1]
+_hypergeom_pmf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_pmf_loops, ufunc__hypergeom_pmf_data, ufunc__hypergeom_pmf_types, 2, 4, 1, 0, "_hypergeom_pmf", ufunc__hypergeom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_sf_loops[2]
+cdef void *ufunc__hypergeom_sf_ptr[4]
+cdef void *ufunc__hypergeom_sf_data[2]
+cdef char ufunc__hypergeom_sf_types[10]
+cdef char *ufunc__hypergeom_sf_doc = (
+    "_hypergeom_sf(x, r, N, M)\n"
+    "\n"
+    "Survival function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_sf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_sf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_sf_types[0] = NPY_FLOAT
+ufunc__hypergeom_sf_types[1] = NPY_FLOAT
+ufunc__hypergeom_sf_types[2] = NPY_FLOAT
+ufunc__hypergeom_sf_types[3] = NPY_FLOAT
+ufunc__hypergeom_sf_types[4] = NPY_FLOAT
+ufunc__hypergeom_sf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_sf_float
+ufunc__hypergeom_sf_ptr[2*0+1] = ("_hypergeom_sf")
+ufunc__hypergeom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_sf_double
+ufunc__hypergeom_sf_ptr[2*1+1] = ("_hypergeom_sf")
+ufunc__hypergeom_sf_data[0] = &ufunc__hypergeom_sf_ptr[2*0]
+ufunc__hypergeom_sf_data[1] = &ufunc__hypergeom_sf_ptr[2*1]
+_hypergeom_sf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_sf_loops, ufunc__hypergeom_sf_data, ufunc__hypergeom_sf_types, 2, 4, 1, 0, "_hypergeom_sf", ufunc__hypergeom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_skewness_loops[2]
+cdef void *ufunc__hypergeom_skewness_ptr[4]
+cdef void *ufunc__hypergeom_skewness_data[2]
+cdef char ufunc__hypergeom_skewness_types[8]
+cdef char *ufunc__hypergeom_skewness_doc = (
+    "_hypergeom_skewness(r, N, M)\n"
+    "\n"
+    "Skewness of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_skewness_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_skewness_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_skewness_types[0] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[1] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[2] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[3] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[4] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[5] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[6] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[7] = NPY_DOUBLE
+ufunc__hypergeom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_float
+ufunc__hypergeom_skewness_ptr[2*0+1] = ("_hypergeom_skewness")
+ufunc__hypergeom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_double
+ufunc__hypergeom_skewness_ptr[2*1+1] = ("_hypergeom_skewness")
+ufunc__hypergeom_skewness_data[0] = &ufunc__hypergeom_skewness_ptr[2*0]
+ufunc__hypergeom_skewness_data[1] = &ufunc__hypergeom_skewness_ptr[2*1]
+_hypergeom_skewness = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_skewness_loops, ufunc__hypergeom_skewness_data, ufunc__hypergeom_skewness_types, 2, 3, 1, 0, "_hypergeom_skewness", ufunc__hypergeom_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_variance_loops[2]
+cdef void *ufunc__hypergeom_variance_ptr[4]
+cdef void *ufunc__hypergeom_variance_data[2]
+cdef char ufunc__hypergeom_variance_types[8]
+cdef char *ufunc__hypergeom_variance_doc = (
+    "_hypergeom_variance(r, N, M)\n"
+    "\n"
+    "Mean of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_variance_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_variance_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_variance_types[0] = NPY_FLOAT
+ufunc__hypergeom_variance_types[1] = NPY_FLOAT
+ufunc__hypergeom_variance_types[2] = NPY_FLOAT
+ufunc__hypergeom_variance_types[3] = NPY_FLOAT
+ufunc__hypergeom_variance_types[4] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[5] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[6] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[7] = NPY_DOUBLE
+ufunc__hypergeom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_variance_float
+ufunc__hypergeom_variance_ptr[2*0+1] = ("_hypergeom_variance")
+ufunc__hypergeom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_variance_double
+ufunc__hypergeom_variance_ptr[2*1+1] = ("_hypergeom_variance")
+ufunc__hypergeom_variance_data[0] = &ufunc__hypergeom_variance_ptr[2*0]
+ufunc__hypergeom_variance_data[1] = &ufunc__hypergeom_variance_ptr[2*1]
+_hypergeom_variance = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_variance_loops, ufunc__hypergeom_variance_data, ufunc__hypergeom_variance_types, 2, 3, 1, 0, "_hypergeom_variance", ufunc__hypergeom_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__igam_fac_loops[2]
+cdef void *ufunc__igam_fac_ptr[4]
+cdef void *ufunc__igam_fac_data[2]
+cdef char ufunc__igam_fac_types[6]
+cdef char *ufunc__igam_fac_doc = (
+    "Internal function, do not use.")
+ufunc__igam_fac_loops[0] = loop_d_dd__As_ff_f
+ufunc__igam_fac_loops[1] = loop_d_dd__As_dd_d
+ufunc__igam_fac_types[0] = NPY_FLOAT
+ufunc__igam_fac_types[1] = NPY_FLOAT
+ufunc__igam_fac_types[2] = NPY_FLOAT
+ufunc__igam_fac_types[3] = NPY_DOUBLE
+ufunc__igam_fac_types[4] = NPY_DOUBLE
+ufunc__igam_fac_types[5] = NPY_DOUBLE
+ufunc__igam_fac_ptr[2*0] = _func_cephes_igam_fac
+ufunc__igam_fac_ptr[2*0+1] = ("_igam_fac")
+ufunc__igam_fac_ptr[2*1] = _func_cephes_igam_fac
+ufunc__igam_fac_ptr[2*1+1] = ("_igam_fac")
+ufunc__igam_fac_data[0] = &ufunc__igam_fac_ptr[2*0]
+ufunc__igam_fac_data[1] = &ufunc__igam_fac_ptr[2*1]
+_igam_fac = np.PyUFunc_FromFuncAndData(ufunc__igam_fac_loops, ufunc__igam_fac_data, ufunc__igam_fac_types, 2, 2, 1, 0, "_igam_fac", ufunc__igam_fac_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__invgauss_isf_loops[2]
+cdef void *ufunc__invgauss_isf_ptr[4]
+cdef void *ufunc__invgauss_isf_data[2]
+cdef char ufunc__invgauss_isf_types[8]
+cdef char *ufunc__invgauss_isf_doc = (
+    "_invgauss_isf(x, mu, s)\n"
+    "\n"
+    "Inverse survival function of inverse gaussian distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "mu : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "s : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__invgauss_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__invgauss_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__invgauss_isf_types[0] = NPY_FLOAT
+ufunc__invgauss_isf_types[1] = NPY_FLOAT
+ufunc__invgauss_isf_types[2] = NPY_FLOAT
+ufunc__invgauss_isf_types[3] = NPY_FLOAT
+ufunc__invgauss_isf_types[4] = NPY_DOUBLE
+ufunc__invgauss_isf_types[5] = NPY_DOUBLE
+ufunc__invgauss_isf_types[6] = NPY_DOUBLE
+ufunc__invgauss_isf_types[7] = NPY_DOUBLE
+ufunc__invgauss_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_isf_float
+ufunc__invgauss_isf_ptr[2*0+1] = ("_invgauss_isf")
+ufunc__invgauss_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_isf_double
+ufunc__invgauss_isf_ptr[2*1+1] = ("_invgauss_isf")
+ufunc__invgauss_isf_data[0] = &ufunc__invgauss_isf_ptr[2*0]
+ufunc__invgauss_isf_data[1] = &ufunc__invgauss_isf_ptr[2*1]
+_invgauss_isf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_isf_loops, ufunc__invgauss_isf_data, ufunc__invgauss_isf_types, 2, 3, 1, 0, "_invgauss_isf", ufunc__invgauss_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__invgauss_ppf_loops[2]
+cdef void *ufunc__invgauss_ppf_ptr[4]
+cdef void *ufunc__invgauss_ppf_data[2]
+cdef char ufunc__invgauss_ppf_types[8]
+cdef char *ufunc__invgauss_ppf_doc = (
+    "_invgauss_ppf(x, mu)\n"
+    "\n"
+    "Percent point function of inverse gaussian distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "mu : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__invgauss_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__invgauss_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__invgauss_ppf_types[0] = NPY_FLOAT
+ufunc__invgauss_ppf_types[1] = NPY_FLOAT
+ufunc__invgauss_ppf_types[2] = NPY_FLOAT
+ufunc__invgauss_ppf_types[3] = NPY_FLOAT
+ufunc__invgauss_ppf_types[4] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[5] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[6] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[7] = NPY_DOUBLE
+ufunc__invgauss_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_ppf_float
+ufunc__invgauss_ppf_ptr[2*0+1] = ("_invgauss_ppf")
+ufunc__invgauss_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_ppf_double
+ufunc__invgauss_ppf_ptr[2*1+1] = ("_invgauss_ppf")
+ufunc__invgauss_ppf_data[0] = &ufunc__invgauss_ppf_ptr[2*0]
+ufunc__invgauss_ppf_data[1] = &ufunc__invgauss_ppf_ptr[2*1]
+_invgauss_ppf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_ppf_loops, ufunc__invgauss_ppf_data, ufunc__invgauss_ppf_types, 2, 3, 1, 0, "_invgauss_ppf", ufunc__invgauss_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogc_loops[2]
+cdef void *ufunc__kolmogc_ptr[4]
+cdef void *ufunc__kolmogc_data[2]
+cdef char ufunc__kolmogc_types[4]
+cdef char *ufunc__kolmogc_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogc_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogc_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogc_types[0] = NPY_FLOAT
+ufunc__kolmogc_types[1] = NPY_FLOAT
+ufunc__kolmogc_types[2] = NPY_DOUBLE
+ufunc__kolmogc_types[3] = NPY_DOUBLE
+ufunc__kolmogc_ptr[2*0] = _func_xsf_kolmogc
+ufunc__kolmogc_ptr[2*0+1] = ("_kolmogc")
+ufunc__kolmogc_ptr[2*1] = _func_xsf_kolmogc
+ufunc__kolmogc_ptr[2*1+1] = ("_kolmogc")
+ufunc__kolmogc_data[0] = &ufunc__kolmogc_ptr[2*0]
+ufunc__kolmogc_data[1] = &ufunc__kolmogc_ptr[2*1]
+_kolmogc = np.PyUFunc_FromFuncAndData(ufunc__kolmogc_loops, ufunc__kolmogc_data, ufunc__kolmogc_types, 2, 1, 1, 0, "_kolmogc", ufunc__kolmogc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogci_loops[2]
+cdef void *ufunc__kolmogci_ptr[4]
+cdef void *ufunc__kolmogci_data[2]
+cdef char ufunc__kolmogci_types[4]
+cdef char *ufunc__kolmogci_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogci_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogci_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogci_types[0] = NPY_FLOAT
+ufunc__kolmogci_types[1] = NPY_FLOAT
+ufunc__kolmogci_types[2] = NPY_DOUBLE
+ufunc__kolmogci_types[3] = NPY_DOUBLE
+ufunc__kolmogci_ptr[2*0] = _func_xsf_kolmogci
+ufunc__kolmogci_ptr[2*0+1] = ("_kolmogci")
+ufunc__kolmogci_ptr[2*1] = _func_xsf_kolmogci
+ufunc__kolmogci_ptr[2*1+1] = ("_kolmogci")
+ufunc__kolmogci_data[0] = &ufunc__kolmogci_ptr[2*0]
+ufunc__kolmogci_data[1] = &ufunc__kolmogci_ptr[2*1]
+_kolmogci = np.PyUFunc_FromFuncAndData(ufunc__kolmogci_loops, ufunc__kolmogci_data, ufunc__kolmogci_types, 2, 1, 1, 0, "_kolmogci", ufunc__kolmogci_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogp_loops[2]
+cdef void *ufunc__kolmogp_ptr[4]
+cdef void *ufunc__kolmogp_data[2]
+cdef char ufunc__kolmogp_types[4]
+cdef char *ufunc__kolmogp_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogp_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogp_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogp_types[0] = NPY_FLOAT
+ufunc__kolmogp_types[1] = NPY_FLOAT
+ufunc__kolmogp_types[2] = NPY_DOUBLE
+ufunc__kolmogp_types[3] = NPY_DOUBLE
+ufunc__kolmogp_ptr[2*0] = _func_xsf_kolmogp
+ufunc__kolmogp_ptr[2*0+1] = ("_kolmogp")
+ufunc__kolmogp_ptr[2*1] = _func_xsf_kolmogp
+ufunc__kolmogp_ptr[2*1+1] = ("_kolmogp")
+ufunc__kolmogp_data[0] = &ufunc__kolmogp_ptr[2*0]
+ufunc__kolmogp_data[1] = &ufunc__kolmogp_ptr[2*1]
+_kolmogp = np.PyUFunc_FromFuncAndData(ufunc__kolmogp_loops, ufunc__kolmogp_data, ufunc__kolmogp_types, 2, 1, 1, 0, "_kolmogp", ufunc__kolmogp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__lanczos_sum_expg_scaled_loops[2]
+cdef void *ufunc__lanczos_sum_expg_scaled_ptr[4]
+cdef void *ufunc__lanczos_sum_expg_scaled_data[2]
+cdef char ufunc__lanczos_sum_expg_scaled_types[4]
+cdef char *ufunc__lanczos_sum_expg_scaled_doc = (
+    "Internal function, do not use.")
+ufunc__lanczos_sum_expg_scaled_loops[0] = loop_d_d__As_f_f
+ufunc__lanczos_sum_expg_scaled_loops[1] = loop_d_d__As_d_d
+ufunc__lanczos_sum_expg_scaled_types[0] = NPY_FLOAT
+ufunc__lanczos_sum_expg_scaled_types[1] = NPY_FLOAT
+ufunc__lanczos_sum_expg_scaled_types[2] = NPY_DOUBLE
+ufunc__lanczos_sum_expg_scaled_types[3] = NPY_DOUBLE
+ufunc__lanczos_sum_expg_scaled_ptr[2*0] = _func_cephes_lanczos_sum_expg_scaled
+ufunc__lanczos_sum_expg_scaled_ptr[2*0+1] = ("_lanczos_sum_expg_scaled")
+ufunc__lanczos_sum_expg_scaled_ptr[2*1] = _func_cephes_lanczos_sum_expg_scaled
+ufunc__lanczos_sum_expg_scaled_ptr[2*1+1] = ("_lanczos_sum_expg_scaled")
+ufunc__lanczos_sum_expg_scaled_data[0] = &ufunc__lanczos_sum_expg_scaled_ptr[2*0]
+ufunc__lanczos_sum_expg_scaled_data[1] = &ufunc__lanczos_sum_expg_scaled_ptr[2*1]
+_lanczos_sum_expg_scaled = np.PyUFunc_FromFuncAndData(ufunc__lanczos_sum_expg_scaled_loops, ufunc__lanczos_sum_expg_scaled_data, ufunc__lanczos_sum_expg_scaled_types, 2, 1, 1, 0, "_lanczos_sum_expg_scaled", ufunc__lanczos_sum_expg_scaled_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_cdf_loops[2]
+cdef void *ufunc__landau_cdf_ptr[4]
+cdef void *ufunc__landau_cdf_data[2]
+cdef char ufunc__landau_cdf_types[8]
+cdef char *ufunc__landau_cdf_doc = (
+    "_landau_cdf(x, loc, scale)\n"
+    "\n"
+    "Cumulative distribution function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_cdf_types[0] = NPY_FLOAT
+ufunc__landau_cdf_types[1] = NPY_FLOAT
+ufunc__landau_cdf_types[2] = NPY_FLOAT
+ufunc__landau_cdf_types[3] = NPY_FLOAT
+ufunc__landau_cdf_types[4] = NPY_DOUBLE
+ufunc__landau_cdf_types[5] = NPY_DOUBLE
+ufunc__landau_cdf_types[6] = NPY_DOUBLE
+ufunc__landau_cdf_types[7] = NPY_DOUBLE
+ufunc__landau_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_cdf_float
+ufunc__landau_cdf_ptr[2*0+1] = ("_landau_cdf")
+ufunc__landau_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_cdf_double
+ufunc__landau_cdf_ptr[2*1+1] = ("_landau_cdf")
+ufunc__landau_cdf_data[0] = &ufunc__landau_cdf_ptr[2*0]
+ufunc__landau_cdf_data[1] = &ufunc__landau_cdf_ptr[2*1]
+_landau_cdf = np.PyUFunc_FromFuncAndData(ufunc__landau_cdf_loops, ufunc__landau_cdf_data, ufunc__landau_cdf_types, 2, 3, 1, 0, "_landau_cdf", ufunc__landau_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_isf_loops[2]
+cdef void *ufunc__landau_isf_ptr[4]
+cdef void *ufunc__landau_isf_data[2]
+cdef char ufunc__landau_isf_types[8]
+cdef char *ufunc__landau_isf_doc = (
+    "_landau_isf(p, loc, scale)\n"
+    "\n"
+    "Inverse survival function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Real-valued argument between 0 and 1\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_isf_types[0] = NPY_FLOAT
+ufunc__landau_isf_types[1] = NPY_FLOAT
+ufunc__landau_isf_types[2] = NPY_FLOAT
+ufunc__landau_isf_types[3] = NPY_FLOAT
+ufunc__landau_isf_types[4] = NPY_DOUBLE
+ufunc__landau_isf_types[5] = NPY_DOUBLE
+ufunc__landau_isf_types[6] = NPY_DOUBLE
+ufunc__landau_isf_types[7] = NPY_DOUBLE
+ufunc__landau_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_isf_float
+ufunc__landau_isf_ptr[2*0+1] = ("_landau_isf")
+ufunc__landau_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_isf_double
+ufunc__landau_isf_ptr[2*1+1] = ("_landau_isf")
+ufunc__landau_isf_data[0] = &ufunc__landau_isf_ptr[2*0]
+ufunc__landau_isf_data[1] = &ufunc__landau_isf_ptr[2*1]
+_landau_isf = np.PyUFunc_FromFuncAndData(ufunc__landau_isf_loops, ufunc__landau_isf_data, ufunc__landau_isf_types, 2, 3, 1, 0, "_landau_isf", ufunc__landau_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_pdf_loops[2]
+cdef void *ufunc__landau_pdf_ptr[4]
+cdef void *ufunc__landau_pdf_data[2]
+cdef char ufunc__landau_pdf_types[8]
+cdef char *ufunc__landau_pdf_doc = (
+    "_landau_pdf(x, loc, scale)\n"
+    "\n"
+    "Probability density function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_pdf_types[0] = NPY_FLOAT
+ufunc__landau_pdf_types[1] = NPY_FLOAT
+ufunc__landau_pdf_types[2] = NPY_FLOAT
+ufunc__landau_pdf_types[3] = NPY_FLOAT
+ufunc__landau_pdf_types[4] = NPY_DOUBLE
+ufunc__landau_pdf_types[5] = NPY_DOUBLE
+ufunc__landau_pdf_types[6] = NPY_DOUBLE
+ufunc__landau_pdf_types[7] = NPY_DOUBLE
+ufunc__landau_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_pdf_float
+ufunc__landau_pdf_ptr[2*0+1] = ("_landau_pdf")
+ufunc__landau_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_pdf_double
+ufunc__landau_pdf_ptr[2*1+1] = ("_landau_pdf")
+ufunc__landau_pdf_data[0] = &ufunc__landau_pdf_ptr[2*0]
+ufunc__landau_pdf_data[1] = &ufunc__landau_pdf_ptr[2*1]
+_landau_pdf = np.PyUFunc_FromFuncAndData(ufunc__landau_pdf_loops, ufunc__landau_pdf_data, ufunc__landau_pdf_types, 2, 3, 1, 0, "_landau_pdf", ufunc__landau_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_ppf_loops[2]
+cdef void *ufunc__landau_ppf_ptr[4]
+cdef void *ufunc__landau_ppf_data[2]
+cdef char ufunc__landau_ppf_types[8]
+cdef char *ufunc__landau_ppf_doc = (
+    "_landau_ppf(p, loc, scale)\n"
+    "\n"
+    "Percent point function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Real-valued argument between 0 and 1\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_ppf_types[0] = NPY_FLOAT
+ufunc__landau_ppf_types[1] = NPY_FLOAT
+ufunc__landau_ppf_types[2] = NPY_FLOAT
+ufunc__landau_ppf_types[3] = NPY_FLOAT
+ufunc__landau_ppf_types[4] = NPY_DOUBLE
+ufunc__landau_ppf_types[5] = NPY_DOUBLE
+ufunc__landau_ppf_types[6] = NPY_DOUBLE
+ufunc__landau_ppf_types[7] = NPY_DOUBLE
+ufunc__landau_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_ppf_float
+ufunc__landau_ppf_ptr[2*0+1] = ("_landau_ppf")
+ufunc__landau_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_ppf_double
+ufunc__landau_ppf_ptr[2*1+1] = ("_landau_ppf")
+ufunc__landau_ppf_data[0] = &ufunc__landau_ppf_ptr[2*0]
+ufunc__landau_ppf_data[1] = &ufunc__landau_ppf_ptr[2*1]
+_landau_ppf = np.PyUFunc_FromFuncAndData(ufunc__landau_ppf_loops, ufunc__landau_ppf_data, ufunc__landau_ppf_types, 2, 3, 1, 0, "_landau_ppf", ufunc__landau_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_sf_loops[2]
+cdef void *ufunc__landau_sf_ptr[4]
+cdef void *ufunc__landau_sf_data[2]
+cdef char ufunc__landau_sf_types[8]
+cdef char *ufunc__landau_sf_doc = (
+    "_landau_sf(x, loc, scale)\n"
+    "\n"
+    "Survival function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_sf_types[0] = NPY_FLOAT
+ufunc__landau_sf_types[1] = NPY_FLOAT
+ufunc__landau_sf_types[2] = NPY_FLOAT
+ufunc__landau_sf_types[3] = NPY_FLOAT
+ufunc__landau_sf_types[4] = NPY_DOUBLE
+ufunc__landau_sf_types[5] = NPY_DOUBLE
+ufunc__landau_sf_types[6] = NPY_DOUBLE
+ufunc__landau_sf_types[7] = NPY_DOUBLE
+ufunc__landau_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_sf_float
+ufunc__landau_sf_ptr[2*0+1] = ("_landau_sf")
+ufunc__landau_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_sf_double
+ufunc__landau_sf_ptr[2*1+1] = ("_landau_sf")
+ufunc__landau_sf_data[0] = &ufunc__landau_sf_ptr[2*0]
+ufunc__landau_sf_data[1] = &ufunc__landau_sf_ptr[2*1]
+_landau_sf = np.PyUFunc_FromFuncAndData(ufunc__landau_sf_loops, ufunc__landau_sf_data, ufunc__landau_sf_types, 2, 3, 1, 0, "_landau_sf", ufunc__landau_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__lgam1p_loops[2]
+cdef void *ufunc__lgam1p_ptr[4]
+cdef void *ufunc__lgam1p_data[2]
+cdef char ufunc__lgam1p_types[4]
+cdef char *ufunc__lgam1p_doc = (
+    "Internal function, do not use.")
+ufunc__lgam1p_loops[0] = loop_d_d__As_f_f
+ufunc__lgam1p_loops[1] = loop_d_d__As_d_d
+ufunc__lgam1p_types[0] = NPY_FLOAT
+ufunc__lgam1p_types[1] = NPY_FLOAT
+ufunc__lgam1p_types[2] = NPY_DOUBLE
+ufunc__lgam1p_types[3] = NPY_DOUBLE
+ufunc__lgam1p_ptr[2*0] = _func_cephes_lgam1p
+ufunc__lgam1p_ptr[2*0+1] = ("_lgam1p")
+ufunc__lgam1p_ptr[2*1] = _func_cephes_lgam1p
+ufunc__lgam1p_ptr[2*1+1] = ("_lgam1p")
+ufunc__lgam1p_data[0] = &ufunc__lgam1p_ptr[2*0]
+ufunc__lgam1p_data[1] = &ufunc__lgam1p_ptr[2*1]
+_lgam1p = np.PyUFunc_FromFuncAndData(ufunc__lgam1p_loops, ufunc__lgam1p_data, ufunc__lgam1p_types, 2, 1, 1, 0, "_lgam1p", ufunc__lgam1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__log1pmx_loops[2]
+cdef void *ufunc__log1pmx_ptr[4]
+cdef void *ufunc__log1pmx_data[2]
+cdef char ufunc__log1pmx_types[4]
+cdef char *ufunc__log1pmx_doc = (
+    "Internal function, do not use.")
+ufunc__log1pmx_loops[0] = loop_d_d__As_f_f
+ufunc__log1pmx_loops[1] = loop_d_d__As_d_d
+ufunc__log1pmx_types[0] = NPY_FLOAT
+ufunc__log1pmx_types[1] = NPY_FLOAT
+ufunc__log1pmx_types[2] = NPY_DOUBLE
+ufunc__log1pmx_types[3] = NPY_DOUBLE
+ufunc__log1pmx_ptr[2*0] = _func_cephes_log1pmx
+ufunc__log1pmx_ptr[2*0+1] = ("_log1pmx")
+ufunc__log1pmx_ptr[2*1] = _func_cephes_log1pmx
+ufunc__log1pmx_ptr[2*1+1] = ("_log1pmx")
+ufunc__log1pmx_data[0] = &ufunc__log1pmx_ptr[2*0]
+ufunc__log1pmx_data[1] = &ufunc__log1pmx_ptr[2*1]
+_log1pmx = np.PyUFunc_FromFuncAndData(ufunc__log1pmx_loops, ufunc__log1pmx_data, ufunc__log1pmx_types, 2, 1, 1, 0, "_log1pmx", ufunc__log1pmx_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_cdf_loops[2]
+cdef void *ufunc__nbinom_cdf_ptr[4]
+cdef void *ufunc__nbinom_cdf_data[2]
+cdef char ufunc__nbinom_cdf_types[8]
+cdef char *ufunc__nbinom_cdf_doc = (
+    "_nbinom_cdf(x, r, p)\n"
+    "\n"
+    "Cumulative density function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_cdf_types[0] = NPY_FLOAT
+ufunc__nbinom_cdf_types[1] = NPY_FLOAT
+ufunc__nbinom_cdf_types[2] = NPY_FLOAT
+ufunc__nbinom_cdf_types[3] = NPY_FLOAT
+ufunc__nbinom_cdf_types[4] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[5] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[6] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[7] = NPY_DOUBLE
+ufunc__nbinom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_cdf_float
+ufunc__nbinom_cdf_ptr[2*0+1] = ("_nbinom_cdf")
+ufunc__nbinom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_cdf_double
+ufunc__nbinom_cdf_ptr[2*1+1] = ("_nbinom_cdf")
+ufunc__nbinom_cdf_data[0] = &ufunc__nbinom_cdf_ptr[2*0]
+ufunc__nbinom_cdf_data[1] = &ufunc__nbinom_cdf_ptr[2*1]
+_nbinom_cdf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_cdf_loops, ufunc__nbinom_cdf_data, ufunc__nbinom_cdf_types, 2, 3, 1, 0, "_nbinom_cdf", ufunc__nbinom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_isf_loops[2]
+cdef void *ufunc__nbinom_isf_ptr[4]
+cdef void *ufunc__nbinom_isf_data[2]
+cdef char ufunc__nbinom_isf_types[8]
+cdef char *ufunc__nbinom_isf_doc = (
+    "_nbinom_isf(x, r, p)\n"
+    "\n"
+    "Inverse survival function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_isf_types[0] = NPY_FLOAT
+ufunc__nbinom_isf_types[1] = NPY_FLOAT
+ufunc__nbinom_isf_types[2] = NPY_FLOAT
+ufunc__nbinom_isf_types[3] = NPY_FLOAT
+ufunc__nbinom_isf_types[4] = NPY_DOUBLE
+ufunc__nbinom_isf_types[5] = NPY_DOUBLE
+ufunc__nbinom_isf_types[6] = NPY_DOUBLE
+ufunc__nbinom_isf_types[7] = NPY_DOUBLE
+ufunc__nbinom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_isf_float
+ufunc__nbinom_isf_ptr[2*0+1] = ("_nbinom_isf")
+ufunc__nbinom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_isf_double
+ufunc__nbinom_isf_ptr[2*1+1] = ("_nbinom_isf")
+ufunc__nbinom_isf_data[0] = &ufunc__nbinom_isf_ptr[2*0]
+ufunc__nbinom_isf_data[1] = &ufunc__nbinom_isf_ptr[2*1]
+_nbinom_isf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_isf_loops, ufunc__nbinom_isf_data, ufunc__nbinom_isf_types, 2, 3, 1, 0, "_nbinom_isf", ufunc__nbinom_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_kurtosis_excess_loops[2]
+cdef void *ufunc__nbinom_kurtosis_excess_ptr[4]
+cdef void *ufunc__nbinom_kurtosis_excess_data[2]
+cdef char ufunc__nbinom_kurtosis_excess_types[6]
+cdef char *ufunc__nbinom_kurtosis_excess_doc = (
+    "_nbinom_kurtosis_excess(r, p)\n"
+    "\n"
+    "Kurtosis excess of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[3] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_float
+ufunc__nbinom_kurtosis_excess_ptr[2*0+1] = ("_nbinom_kurtosis_excess")
+ufunc__nbinom_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_double
+ufunc__nbinom_kurtosis_excess_ptr[2*1+1] = ("_nbinom_kurtosis_excess")
+ufunc__nbinom_kurtosis_excess_data[0] = &ufunc__nbinom_kurtosis_excess_ptr[2*0]
+ufunc__nbinom_kurtosis_excess_data[1] = &ufunc__nbinom_kurtosis_excess_ptr[2*1]
+_nbinom_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nbinom_kurtosis_excess_loops, ufunc__nbinom_kurtosis_excess_data, ufunc__nbinom_kurtosis_excess_types, 2, 2, 1, 0, "_nbinom_kurtosis_excess", ufunc__nbinom_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_mean_loops[2]
+cdef void *ufunc__nbinom_mean_ptr[4]
+cdef void *ufunc__nbinom_mean_data[2]
+cdef char ufunc__nbinom_mean_types[6]
+cdef char *ufunc__nbinom_mean_doc = (
+    "_nbinom_mean(r, p)\n"
+    "\n"
+    "Mean of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_mean_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_mean_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_mean_types[0] = NPY_FLOAT
+ufunc__nbinom_mean_types[1] = NPY_FLOAT
+ufunc__nbinom_mean_types[2] = NPY_FLOAT
+ufunc__nbinom_mean_types[3] = NPY_DOUBLE
+ufunc__nbinom_mean_types[4] = NPY_DOUBLE
+ufunc__nbinom_mean_types[5] = NPY_DOUBLE
+ufunc__nbinom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_mean_float
+ufunc__nbinom_mean_ptr[2*0+1] = ("_nbinom_mean")
+ufunc__nbinom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_mean_double
+ufunc__nbinom_mean_ptr[2*1+1] = ("_nbinom_mean")
+ufunc__nbinom_mean_data[0] = &ufunc__nbinom_mean_ptr[2*0]
+ufunc__nbinom_mean_data[1] = &ufunc__nbinom_mean_ptr[2*1]
+_nbinom_mean = np.PyUFunc_FromFuncAndData(ufunc__nbinom_mean_loops, ufunc__nbinom_mean_data, ufunc__nbinom_mean_types, 2, 2, 1, 0, "_nbinom_mean", ufunc__nbinom_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_pmf_loops[2]
+cdef void *ufunc__nbinom_pmf_ptr[4]
+cdef void *ufunc__nbinom_pmf_data[2]
+cdef char ufunc__nbinom_pmf_types[8]
+cdef char *ufunc__nbinom_pmf_doc = (
+    "_nbinom_pmf(x, r, p)\n"
+    "\n"
+    "Probability mass function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_pmf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_pmf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_pmf_types[0] = NPY_FLOAT
+ufunc__nbinom_pmf_types[1] = NPY_FLOAT
+ufunc__nbinom_pmf_types[2] = NPY_FLOAT
+ufunc__nbinom_pmf_types[3] = NPY_FLOAT
+ufunc__nbinom_pmf_types[4] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[5] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[6] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[7] = NPY_DOUBLE
+ufunc__nbinom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_pmf_float
+ufunc__nbinom_pmf_ptr[2*0+1] = ("_nbinom_pmf")
+ufunc__nbinom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_pmf_double
+ufunc__nbinom_pmf_ptr[2*1+1] = ("_nbinom_pmf")
+ufunc__nbinom_pmf_data[0] = &ufunc__nbinom_pmf_ptr[2*0]
+ufunc__nbinom_pmf_data[1] = &ufunc__nbinom_pmf_ptr[2*1]
+_nbinom_pmf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_pmf_loops, ufunc__nbinom_pmf_data, ufunc__nbinom_pmf_types, 2, 3, 1, 0, "_nbinom_pmf", ufunc__nbinom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_ppf_loops[2]
+cdef void *ufunc__nbinom_ppf_ptr[4]
+cdef void *ufunc__nbinom_ppf_data[2]
+cdef char ufunc__nbinom_ppf_types[8]
+cdef char *ufunc__nbinom_ppf_doc = (
+    "_nbinom_ppf(x, r, p)\n"
+    "\n"
+    "Percent point function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_ppf_types[0] = NPY_FLOAT
+ufunc__nbinom_ppf_types[1] = NPY_FLOAT
+ufunc__nbinom_ppf_types[2] = NPY_FLOAT
+ufunc__nbinom_ppf_types[3] = NPY_FLOAT
+ufunc__nbinom_ppf_types[4] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[5] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[6] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[7] = NPY_DOUBLE
+ufunc__nbinom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_ppf_float
+ufunc__nbinom_ppf_ptr[2*0+1] = ("_nbinom_ppf")
+ufunc__nbinom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_ppf_double
+ufunc__nbinom_ppf_ptr[2*1+1] = ("_nbinom_ppf")
+ufunc__nbinom_ppf_data[0] = &ufunc__nbinom_ppf_ptr[2*0]
+ufunc__nbinom_ppf_data[1] = &ufunc__nbinom_ppf_ptr[2*1]
+_nbinom_ppf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_ppf_loops, ufunc__nbinom_ppf_data, ufunc__nbinom_ppf_types, 2, 3, 1, 0, "_nbinom_ppf", ufunc__nbinom_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_sf_loops[2]
+cdef void *ufunc__nbinom_sf_ptr[4]
+cdef void *ufunc__nbinom_sf_data[2]
+cdef char ufunc__nbinom_sf_types[8]
+cdef char *ufunc__nbinom_sf_doc = (
+    "_nbinom_sf(x, r, p)\n"
+    "\n"
+    "Survival function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_sf_types[0] = NPY_FLOAT
+ufunc__nbinom_sf_types[1] = NPY_FLOAT
+ufunc__nbinom_sf_types[2] = NPY_FLOAT
+ufunc__nbinom_sf_types[3] = NPY_FLOAT
+ufunc__nbinom_sf_types[4] = NPY_DOUBLE
+ufunc__nbinom_sf_types[5] = NPY_DOUBLE
+ufunc__nbinom_sf_types[6] = NPY_DOUBLE
+ufunc__nbinom_sf_types[7] = NPY_DOUBLE
+ufunc__nbinom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_sf_float
+ufunc__nbinom_sf_ptr[2*0+1] = ("_nbinom_sf")
+ufunc__nbinom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_sf_double
+ufunc__nbinom_sf_ptr[2*1+1] = ("_nbinom_sf")
+ufunc__nbinom_sf_data[0] = &ufunc__nbinom_sf_ptr[2*0]
+ufunc__nbinom_sf_data[1] = &ufunc__nbinom_sf_ptr[2*1]
+_nbinom_sf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_sf_loops, ufunc__nbinom_sf_data, ufunc__nbinom_sf_types, 2, 3, 1, 0, "_nbinom_sf", ufunc__nbinom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_skewness_loops[2]
+cdef void *ufunc__nbinom_skewness_ptr[4]
+cdef void *ufunc__nbinom_skewness_data[2]
+cdef char ufunc__nbinom_skewness_types[6]
+cdef char *ufunc__nbinom_skewness_doc = (
+    "_nbinom_skewness(r, p)\n"
+    "\n"
+    "Skewness of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_skewness_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_skewness_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_skewness_types[0] = NPY_FLOAT
+ufunc__nbinom_skewness_types[1] = NPY_FLOAT
+ufunc__nbinom_skewness_types[2] = NPY_FLOAT
+ufunc__nbinom_skewness_types[3] = NPY_DOUBLE
+ufunc__nbinom_skewness_types[4] = NPY_DOUBLE
+ufunc__nbinom_skewness_types[5] = NPY_DOUBLE
+ufunc__nbinom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_skewness_float
+ufunc__nbinom_skewness_ptr[2*0+1] = ("_nbinom_skewness")
+ufunc__nbinom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_skewness_double
+ufunc__nbinom_skewness_ptr[2*1+1] = ("_nbinom_skewness")
+ufunc__nbinom_skewness_data[0] = &ufunc__nbinom_skewness_ptr[2*0]
+ufunc__nbinom_skewness_data[1] = &ufunc__nbinom_skewness_ptr[2*1]
+_nbinom_skewness = np.PyUFunc_FromFuncAndData(ufunc__nbinom_skewness_loops, ufunc__nbinom_skewness_data, ufunc__nbinom_skewness_types, 2, 2, 1, 0, "_nbinom_skewness", ufunc__nbinom_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_variance_loops[2]
+cdef void *ufunc__nbinom_variance_ptr[4]
+cdef void *ufunc__nbinom_variance_data[2]
+cdef char ufunc__nbinom_variance_types[6]
+cdef char *ufunc__nbinom_variance_doc = (
+    "_nbinom_variance(r, p)\n"
+    "\n"
+    "Variance of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_variance_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_variance_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_variance_types[0] = NPY_FLOAT
+ufunc__nbinom_variance_types[1] = NPY_FLOAT
+ufunc__nbinom_variance_types[2] = NPY_FLOAT
+ufunc__nbinom_variance_types[3] = NPY_DOUBLE
+ufunc__nbinom_variance_types[4] = NPY_DOUBLE
+ufunc__nbinom_variance_types[5] = NPY_DOUBLE
+ufunc__nbinom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_variance_float
+ufunc__nbinom_variance_ptr[2*0+1] = ("_nbinom_variance")
+ufunc__nbinom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_variance_double
+ufunc__nbinom_variance_ptr[2*1+1] = ("_nbinom_variance")
+ufunc__nbinom_variance_data[0] = &ufunc__nbinom_variance_ptr[2*0]
+ufunc__nbinom_variance_data[1] = &ufunc__nbinom_variance_ptr[2*1]
+_nbinom_variance = np.PyUFunc_FromFuncAndData(ufunc__nbinom_variance_loops, ufunc__nbinom_variance_data, ufunc__nbinom_variance_types, 2, 2, 1, 0, "_nbinom_variance", ufunc__nbinom_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_isf_loops[2]
+cdef void *ufunc__ncf_isf_ptr[4]
+cdef void *ufunc__ncf_isf_data[2]
+cdef char ufunc__ncf_isf_types[10]
+cdef char *ufunc__ncf_isf_doc = (
+    "_ncf_isf(x, v1, v2, l)\n"
+    "\n"
+    "Inverse survival function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_isf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_isf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_isf_types[0] = NPY_FLOAT
+ufunc__ncf_isf_types[1] = NPY_FLOAT
+ufunc__ncf_isf_types[2] = NPY_FLOAT
+ufunc__ncf_isf_types[3] = NPY_FLOAT
+ufunc__ncf_isf_types[4] = NPY_FLOAT
+ufunc__ncf_isf_types[5] = NPY_DOUBLE
+ufunc__ncf_isf_types[6] = NPY_DOUBLE
+ufunc__ncf_isf_types[7] = NPY_DOUBLE
+ufunc__ncf_isf_types[8] = NPY_DOUBLE
+ufunc__ncf_isf_types[9] = NPY_DOUBLE
+ufunc__ncf_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_isf_float
+ufunc__ncf_isf_ptr[2*0+1] = ("_ncf_isf")
+ufunc__ncf_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_isf_double
+ufunc__ncf_isf_ptr[2*1+1] = ("_ncf_isf")
+ufunc__ncf_isf_data[0] = &ufunc__ncf_isf_ptr[2*0]
+ufunc__ncf_isf_data[1] = &ufunc__ncf_isf_ptr[2*1]
+_ncf_isf = np.PyUFunc_FromFuncAndData(ufunc__ncf_isf_loops, ufunc__ncf_isf_data, ufunc__ncf_isf_types, 2, 4, 1, 0, "_ncf_isf", ufunc__ncf_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_kurtosis_excess_loops[2]
+cdef void *ufunc__ncf_kurtosis_excess_ptr[4]
+cdef void *ufunc__ncf_kurtosis_excess_data[2]
+cdef char ufunc__ncf_kurtosis_excess_types[8]
+cdef char *ufunc__ncf_kurtosis_excess_doc = (
+    "_ncf_kurtosis_excess(v1, v2, l)\n"
+    "\n"
+    "Kurtosis excess of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_kurtosis_excess_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_kurtosis_excess_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[3] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[6] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[7] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_float
+ufunc__ncf_kurtosis_excess_ptr[2*0+1] = ("_ncf_kurtosis_excess")
+ufunc__ncf_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_double
+ufunc__ncf_kurtosis_excess_ptr[2*1+1] = ("_ncf_kurtosis_excess")
+ufunc__ncf_kurtosis_excess_data[0] = &ufunc__ncf_kurtosis_excess_ptr[2*0]
+ufunc__ncf_kurtosis_excess_data[1] = &ufunc__ncf_kurtosis_excess_ptr[2*1]
+_ncf_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__ncf_kurtosis_excess_loops, ufunc__ncf_kurtosis_excess_data, ufunc__ncf_kurtosis_excess_types, 2, 3, 1, 0, "_ncf_kurtosis_excess", ufunc__ncf_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_mean_loops[2]
+cdef void *ufunc__ncf_mean_ptr[4]
+cdef void *ufunc__ncf_mean_data[2]
+cdef char ufunc__ncf_mean_types[8]
+cdef char *ufunc__ncf_mean_doc = (
+    "_ncf_mean(v1, v2, l)\n"
+    "\n"
+    "Mean of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_mean_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_mean_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_mean_types[0] = NPY_FLOAT
+ufunc__ncf_mean_types[1] = NPY_FLOAT
+ufunc__ncf_mean_types[2] = NPY_FLOAT
+ufunc__ncf_mean_types[3] = NPY_FLOAT
+ufunc__ncf_mean_types[4] = NPY_DOUBLE
+ufunc__ncf_mean_types[5] = NPY_DOUBLE
+ufunc__ncf_mean_types[6] = NPY_DOUBLE
+ufunc__ncf_mean_types[7] = NPY_DOUBLE
+ufunc__ncf_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_mean_float
+ufunc__ncf_mean_ptr[2*0+1] = ("_ncf_mean")
+ufunc__ncf_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_mean_double
+ufunc__ncf_mean_ptr[2*1+1] = ("_ncf_mean")
+ufunc__ncf_mean_data[0] = &ufunc__ncf_mean_ptr[2*0]
+ufunc__ncf_mean_data[1] = &ufunc__ncf_mean_ptr[2*1]
+_ncf_mean = np.PyUFunc_FromFuncAndData(ufunc__ncf_mean_loops, ufunc__ncf_mean_data, ufunc__ncf_mean_types, 2, 3, 1, 0, "_ncf_mean", ufunc__ncf_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_pdf_loops[2]
+cdef void *ufunc__ncf_pdf_ptr[4]
+cdef void *ufunc__ncf_pdf_data[2]
+cdef char ufunc__ncf_pdf_types[10]
+cdef char *ufunc__ncf_pdf_doc = (
+    "_ncf_pdf(x, v1, v2, l)\n"
+    "\n"
+    "Probability density function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_pdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_pdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_pdf_types[0] = NPY_FLOAT
+ufunc__ncf_pdf_types[1] = NPY_FLOAT
+ufunc__ncf_pdf_types[2] = NPY_FLOAT
+ufunc__ncf_pdf_types[3] = NPY_FLOAT
+ufunc__ncf_pdf_types[4] = NPY_FLOAT
+ufunc__ncf_pdf_types[5] = NPY_DOUBLE
+ufunc__ncf_pdf_types[6] = NPY_DOUBLE
+ufunc__ncf_pdf_types[7] = NPY_DOUBLE
+ufunc__ncf_pdf_types[8] = NPY_DOUBLE
+ufunc__ncf_pdf_types[9] = NPY_DOUBLE
+ufunc__ncf_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_pdf_float
+ufunc__ncf_pdf_ptr[2*0+1] = ("_ncf_pdf")
+ufunc__ncf_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_pdf_double
+ufunc__ncf_pdf_ptr[2*1+1] = ("_ncf_pdf")
+ufunc__ncf_pdf_data[0] = &ufunc__ncf_pdf_ptr[2*0]
+ufunc__ncf_pdf_data[1] = &ufunc__ncf_pdf_ptr[2*1]
+_ncf_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncf_pdf_loops, ufunc__ncf_pdf_data, ufunc__ncf_pdf_types, 2, 4, 1, 0, "_ncf_pdf", ufunc__ncf_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_sf_loops[2]
+cdef void *ufunc__ncf_sf_ptr[4]
+cdef void *ufunc__ncf_sf_data[2]
+cdef char ufunc__ncf_sf_types[10]
+cdef char *ufunc__ncf_sf_doc = (
+    "_ncf_sf(x, v1, v2, l)\n"
+    "\n"
+    "Survival function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_sf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_sf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_sf_types[0] = NPY_FLOAT
+ufunc__ncf_sf_types[1] = NPY_FLOAT
+ufunc__ncf_sf_types[2] = NPY_FLOAT
+ufunc__ncf_sf_types[3] = NPY_FLOAT
+ufunc__ncf_sf_types[4] = NPY_FLOAT
+ufunc__ncf_sf_types[5] = NPY_DOUBLE
+ufunc__ncf_sf_types[6] = NPY_DOUBLE
+ufunc__ncf_sf_types[7] = NPY_DOUBLE
+ufunc__ncf_sf_types[8] = NPY_DOUBLE
+ufunc__ncf_sf_types[9] = NPY_DOUBLE
+ufunc__ncf_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_sf_float
+ufunc__ncf_sf_ptr[2*0+1] = ("_ncf_sf")
+ufunc__ncf_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_sf_double
+ufunc__ncf_sf_ptr[2*1+1] = ("_ncf_sf")
+ufunc__ncf_sf_data[0] = &ufunc__ncf_sf_ptr[2*0]
+ufunc__ncf_sf_data[1] = &ufunc__ncf_sf_ptr[2*1]
+_ncf_sf = np.PyUFunc_FromFuncAndData(ufunc__ncf_sf_loops, ufunc__ncf_sf_data, ufunc__ncf_sf_types, 2, 4, 1, 0, "_ncf_sf", ufunc__ncf_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_skewness_loops[2]
+cdef void *ufunc__ncf_skewness_ptr[4]
+cdef void *ufunc__ncf_skewness_data[2]
+cdef char ufunc__ncf_skewness_types[8]
+cdef char *ufunc__ncf_skewness_doc = (
+    "_ncf_skewness(v1, v2, l)\n"
+    "\n"
+    "Skewness of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_skewness_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_skewness_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_skewness_types[0] = NPY_FLOAT
+ufunc__ncf_skewness_types[1] = NPY_FLOAT
+ufunc__ncf_skewness_types[2] = NPY_FLOAT
+ufunc__ncf_skewness_types[3] = NPY_FLOAT
+ufunc__ncf_skewness_types[4] = NPY_DOUBLE
+ufunc__ncf_skewness_types[5] = NPY_DOUBLE
+ufunc__ncf_skewness_types[6] = NPY_DOUBLE
+ufunc__ncf_skewness_types[7] = NPY_DOUBLE
+ufunc__ncf_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_skewness_float
+ufunc__ncf_skewness_ptr[2*0+1] = ("_ncf_skewness")
+ufunc__ncf_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_skewness_double
+ufunc__ncf_skewness_ptr[2*1+1] = ("_ncf_skewness")
+ufunc__ncf_skewness_data[0] = &ufunc__ncf_skewness_ptr[2*0]
+ufunc__ncf_skewness_data[1] = &ufunc__ncf_skewness_ptr[2*1]
+_ncf_skewness = np.PyUFunc_FromFuncAndData(ufunc__ncf_skewness_loops, ufunc__ncf_skewness_data, ufunc__ncf_skewness_types, 2, 3, 1, 0, "_ncf_skewness", ufunc__ncf_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_variance_loops[2]
+cdef void *ufunc__ncf_variance_ptr[4]
+cdef void *ufunc__ncf_variance_data[2]
+cdef char ufunc__ncf_variance_types[8]
+cdef char *ufunc__ncf_variance_doc = (
+    "_ncf_variance(v1, v2, l)\n"
+    "\n"
+    "Variance of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_variance_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_variance_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_variance_types[0] = NPY_FLOAT
+ufunc__ncf_variance_types[1] = NPY_FLOAT
+ufunc__ncf_variance_types[2] = NPY_FLOAT
+ufunc__ncf_variance_types[3] = NPY_FLOAT
+ufunc__ncf_variance_types[4] = NPY_DOUBLE
+ufunc__ncf_variance_types[5] = NPY_DOUBLE
+ufunc__ncf_variance_types[6] = NPY_DOUBLE
+ufunc__ncf_variance_types[7] = NPY_DOUBLE
+ufunc__ncf_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_variance_float
+ufunc__ncf_variance_ptr[2*0+1] = ("_ncf_variance")
+ufunc__ncf_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_variance_double
+ufunc__ncf_variance_ptr[2*1+1] = ("_ncf_variance")
+ufunc__ncf_variance_data[0] = &ufunc__ncf_variance_ptr[2*0]
+ufunc__ncf_variance_data[1] = &ufunc__ncf_variance_ptr[2*1]
+_ncf_variance = np.PyUFunc_FromFuncAndData(ufunc__ncf_variance_loops, ufunc__ncf_variance_data, ufunc__ncf_variance_types, 2, 3, 1, 0, "_ncf_variance", ufunc__ncf_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_isf_loops[2]
+cdef void *ufunc__nct_isf_ptr[4]
+cdef void *ufunc__nct_isf_data[2]
+cdef char ufunc__nct_isf_types[8]
+cdef char *ufunc__nct_isf_doc = (
+    "_nct_isf(x, v, l)\n"
+    "\n"
+    "Inverse survival function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_isf_types[0] = NPY_FLOAT
+ufunc__nct_isf_types[1] = NPY_FLOAT
+ufunc__nct_isf_types[2] = NPY_FLOAT
+ufunc__nct_isf_types[3] = NPY_FLOAT
+ufunc__nct_isf_types[4] = NPY_DOUBLE
+ufunc__nct_isf_types[5] = NPY_DOUBLE
+ufunc__nct_isf_types[6] = NPY_DOUBLE
+ufunc__nct_isf_types[7] = NPY_DOUBLE
+ufunc__nct_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_isf_float
+ufunc__nct_isf_ptr[2*0+1] = ("_nct_isf")
+ufunc__nct_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_isf_double
+ufunc__nct_isf_ptr[2*1+1] = ("_nct_isf")
+ufunc__nct_isf_data[0] = &ufunc__nct_isf_ptr[2*0]
+ufunc__nct_isf_data[1] = &ufunc__nct_isf_ptr[2*1]
+_nct_isf = np.PyUFunc_FromFuncAndData(ufunc__nct_isf_loops, ufunc__nct_isf_data, ufunc__nct_isf_types, 2, 3, 1, 0, "_nct_isf", ufunc__nct_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_kurtosis_excess_loops[2]
+cdef void *ufunc__nct_kurtosis_excess_ptr[4]
+cdef void *ufunc__nct_kurtosis_excess_data[2]
+cdef char ufunc__nct_kurtosis_excess_types[6]
+cdef char *ufunc__nct_kurtosis_excess_doc = (
+    "_nct_kurtosis_excess(v, l)\n"
+    "\n"
+    "Kurtosis excess of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[3] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_float
+ufunc__nct_kurtosis_excess_ptr[2*0+1] = ("_nct_kurtosis_excess")
+ufunc__nct_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_double
+ufunc__nct_kurtosis_excess_ptr[2*1+1] = ("_nct_kurtosis_excess")
+ufunc__nct_kurtosis_excess_data[0] = &ufunc__nct_kurtosis_excess_ptr[2*0]
+ufunc__nct_kurtosis_excess_data[1] = &ufunc__nct_kurtosis_excess_ptr[2*1]
+_nct_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nct_kurtosis_excess_loops, ufunc__nct_kurtosis_excess_data, ufunc__nct_kurtosis_excess_types, 2, 2, 1, 0, "_nct_kurtosis_excess", ufunc__nct_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_mean_loops[2]
+cdef void *ufunc__nct_mean_ptr[4]
+cdef void *ufunc__nct_mean_data[2]
+cdef char ufunc__nct_mean_types[6]
+cdef char *ufunc__nct_mean_doc = (
+    "_nct_mean(v, l)\n"
+    "\n"
+    "Mean of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_mean_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_mean_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_mean_types[0] = NPY_FLOAT
+ufunc__nct_mean_types[1] = NPY_FLOAT
+ufunc__nct_mean_types[2] = NPY_FLOAT
+ufunc__nct_mean_types[3] = NPY_DOUBLE
+ufunc__nct_mean_types[4] = NPY_DOUBLE
+ufunc__nct_mean_types[5] = NPY_DOUBLE
+ufunc__nct_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_mean_float
+ufunc__nct_mean_ptr[2*0+1] = ("_nct_mean")
+ufunc__nct_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_mean_double
+ufunc__nct_mean_ptr[2*1+1] = ("_nct_mean")
+ufunc__nct_mean_data[0] = &ufunc__nct_mean_ptr[2*0]
+ufunc__nct_mean_data[1] = &ufunc__nct_mean_ptr[2*1]
+_nct_mean = np.PyUFunc_FromFuncAndData(ufunc__nct_mean_loops, ufunc__nct_mean_data, ufunc__nct_mean_types, 2, 2, 1, 0, "_nct_mean", ufunc__nct_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_pdf_loops[2]
+cdef void *ufunc__nct_pdf_ptr[4]
+cdef void *ufunc__nct_pdf_data[2]
+cdef char ufunc__nct_pdf_types[8]
+cdef char *ufunc__nct_pdf_doc = (
+    "_nct_pdf(x, v, l)\n"
+    "\n"
+    "Probability density function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_pdf_types[0] = NPY_FLOAT
+ufunc__nct_pdf_types[1] = NPY_FLOAT
+ufunc__nct_pdf_types[2] = NPY_FLOAT
+ufunc__nct_pdf_types[3] = NPY_FLOAT
+ufunc__nct_pdf_types[4] = NPY_DOUBLE
+ufunc__nct_pdf_types[5] = NPY_DOUBLE
+ufunc__nct_pdf_types[6] = NPY_DOUBLE
+ufunc__nct_pdf_types[7] = NPY_DOUBLE
+ufunc__nct_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_pdf_float
+ufunc__nct_pdf_ptr[2*0+1] = ("_nct_pdf")
+ufunc__nct_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_pdf_double
+ufunc__nct_pdf_ptr[2*1+1] = ("_nct_pdf")
+ufunc__nct_pdf_data[0] = &ufunc__nct_pdf_ptr[2*0]
+ufunc__nct_pdf_data[1] = &ufunc__nct_pdf_ptr[2*1]
+_nct_pdf = np.PyUFunc_FromFuncAndData(ufunc__nct_pdf_loops, ufunc__nct_pdf_data, ufunc__nct_pdf_types, 2, 3, 1, 0, "_nct_pdf", ufunc__nct_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_ppf_loops[2]
+cdef void *ufunc__nct_ppf_ptr[4]
+cdef void *ufunc__nct_ppf_data[2]
+cdef char ufunc__nct_ppf_types[8]
+cdef char *ufunc__nct_ppf_doc = (
+    "_nct_ppf(x, v, l)\n"
+    "\n"
+    "Percent point function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_ppf_types[0] = NPY_FLOAT
+ufunc__nct_ppf_types[1] = NPY_FLOAT
+ufunc__nct_ppf_types[2] = NPY_FLOAT
+ufunc__nct_ppf_types[3] = NPY_FLOAT
+ufunc__nct_ppf_types[4] = NPY_DOUBLE
+ufunc__nct_ppf_types[5] = NPY_DOUBLE
+ufunc__nct_ppf_types[6] = NPY_DOUBLE
+ufunc__nct_ppf_types[7] = NPY_DOUBLE
+ufunc__nct_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_ppf_float
+ufunc__nct_ppf_ptr[2*0+1] = ("_nct_ppf")
+ufunc__nct_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_ppf_double
+ufunc__nct_ppf_ptr[2*1+1] = ("_nct_ppf")
+ufunc__nct_ppf_data[0] = &ufunc__nct_ppf_ptr[2*0]
+ufunc__nct_ppf_data[1] = &ufunc__nct_ppf_ptr[2*1]
+_nct_ppf = np.PyUFunc_FromFuncAndData(ufunc__nct_ppf_loops, ufunc__nct_ppf_data, ufunc__nct_ppf_types, 2, 3, 1, 0, "_nct_ppf", ufunc__nct_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_sf_loops[2]
+cdef void *ufunc__nct_sf_ptr[4]
+cdef void *ufunc__nct_sf_data[2]
+cdef char ufunc__nct_sf_types[8]
+cdef char *ufunc__nct_sf_doc = (
+    "_nct_sf(x, v, l)\n"
+    "\n"
+    "Survival function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_sf_types[0] = NPY_FLOAT
+ufunc__nct_sf_types[1] = NPY_FLOAT
+ufunc__nct_sf_types[2] = NPY_FLOAT
+ufunc__nct_sf_types[3] = NPY_FLOAT
+ufunc__nct_sf_types[4] = NPY_DOUBLE
+ufunc__nct_sf_types[5] = NPY_DOUBLE
+ufunc__nct_sf_types[6] = NPY_DOUBLE
+ufunc__nct_sf_types[7] = NPY_DOUBLE
+ufunc__nct_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_sf_float
+ufunc__nct_sf_ptr[2*0+1] = ("_nct_sf")
+ufunc__nct_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_sf_double
+ufunc__nct_sf_ptr[2*1+1] = ("_nct_sf")
+ufunc__nct_sf_data[0] = &ufunc__nct_sf_ptr[2*0]
+ufunc__nct_sf_data[1] = &ufunc__nct_sf_ptr[2*1]
+_nct_sf = np.PyUFunc_FromFuncAndData(ufunc__nct_sf_loops, ufunc__nct_sf_data, ufunc__nct_sf_types, 2, 3, 1, 0, "_nct_sf", ufunc__nct_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_skewness_loops[2]
+cdef void *ufunc__nct_skewness_ptr[4]
+cdef void *ufunc__nct_skewness_data[2]
+cdef char ufunc__nct_skewness_types[6]
+cdef char *ufunc__nct_skewness_doc = (
+    "_nct_skewness(v, l)\n"
+    "\n"
+    "Skewness of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_skewness_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_skewness_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_skewness_types[0] = NPY_FLOAT
+ufunc__nct_skewness_types[1] = NPY_FLOAT
+ufunc__nct_skewness_types[2] = NPY_FLOAT
+ufunc__nct_skewness_types[3] = NPY_DOUBLE
+ufunc__nct_skewness_types[4] = NPY_DOUBLE
+ufunc__nct_skewness_types[5] = NPY_DOUBLE
+ufunc__nct_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_skewness_float
+ufunc__nct_skewness_ptr[2*0+1] = ("_nct_skewness")
+ufunc__nct_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_skewness_double
+ufunc__nct_skewness_ptr[2*1+1] = ("_nct_skewness")
+ufunc__nct_skewness_data[0] = &ufunc__nct_skewness_ptr[2*0]
+ufunc__nct_skewness_data[1] = &ufunc__nct_skewness_ptr[2*1]
+_nct_skewness = np.PyUFunc_FromFuncAndData(ufunc__nct_skewness_loops, ufunc__nct_skewness_data, ufunc__nct_skewness_types, 2, 2, 1, 0, "_nct_skewness", ufunc__nct_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_variance_loops[2]
+cdef void *ufunc__nct_variance_ptr[4]
+cdef void *ufunc__nct_variance_data[2]
+cdef char ufunc__nct_variance_types[6]
+cdef char *ufunc__nct_variance_doc = (
+    "_nct_variance(v, l)\n"
+    "\n"
+    "Variance of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_variance_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_variance_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_variance_types[0] = NPY_FLOAT
+ufunc__nct_variance_types[1] = NPY_FLOAT
+ufunc__nct_variance_types[2] = NPY_FLOAT
+ufunc__nct_variance_types[3] = NPY_DOUBLE
+ufunc__nct_variance_types[4] = NPY_DOUBLE
+ufunc__nct_variance_types[5] = NPY_DOUBLE
+ufunc__nct_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_variance_float
+ufunc__nct_variance_ptr[2*0+1] = ("_nct_variance")
+ufunc__nct_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_variance_double
+ufunc__nct_variance_ptr[2*1+1] = ("_nct_variance")
+ufunc__nct_variance_data[0] = &ufunc__nct_variance_ptr[2*0]
+ufunc__nct_variance_data[1] = &ufunc__nct_variance_ptr[2*1]
+_nct_variance = np.PyUFunc_FromFuncAndData(ufunc__nct_variance_loops, ufunc__nct_variance_data, ufunc__nct_variance_types, 2, 2, 1, 0, "_nct_variance", ufunc__nct_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_cdf_loops[2]
+cdef void *ufunc__ncx2_cdf_ptr[4]
+cdef void *ufunc__ncx2_cdf_data[2]
+cdef char ufunc__ncx2_cdf_types[8]
+cdef char *ufunc__ncx2_cdf_doc = (
+    "_ncx2_cdf(x, k, l)\n"
+    "\n"
+    "Cumulative density function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_cdf_types[0] = NPY_FLOAT
+ufunc__ncx2_cdf_types[1] = NPY_FLOAT
+ufunc__ncx2_cdf_types[2] = NPY_FLOAT
+ufunc__ncx2_cdf_types[3] = NPY_FLOAT
+ufunc__ncx2_cdf_types[4] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[5] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[6] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[7] = NPY_DOUBLE
+ufunc__ncx2_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_cdf_float
+ufunc__ncx2_cdf_ptr[2*0+1] = ("_ncx2_cdf")
+ufunc__ncx2_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_cdf_double
+ufunc__ncx2_cdf_ptr[2*1+1] = ("_ncx2_cdf")
+ufunc__ncx2_cdf_data[0] = &ufunc__ncx2_cdf_ptr[2*0]
+ufunc__ncx2_cdf_data[1] = &ufunc__ncx2_cdf_ptr[2*1]
+_ncx2_cdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_cdf_loops, ufunc__ncx2_cdf_data, ufunc__ncx2_cdf_types, 2, 3, 1, 0, "_ncx2_cdf", ufunc__ncx2_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_isf_loops[2]
+cdef void *ufunc__ncx2_isf_ptr[4]
+cdef void *ufunc__ncx2_isf_data[2]
+cdef char ufunc__ncx2_isf_types[8]
+cdef char *ufunc__ncx2_isf_doc = (
+    "_ncx2_isf(x, k, l)\n"
+    "\n"
+    "Inverse survival function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_isf_types[0] = NPY_FLOAT
+ufunc__ncx2_isf_types[1] = NPY_FLOAT
+ufunc__ncx2_isf_types[2] = NPY_FLOAT
+ufunc__ncx2_isf_types[3] = NPY_FLOAT
+ufunc__ncx2_isf_types[4] = NPY_DOUBLE
+ufunc__ncx2_isf_types[5] = NPY_DOUBLE
+ufunc__ncx2_isf_types[6] = NPY_DOUBLE
+ufunc__ncx2_isf_types[7] = NPY_DOUBLE
+ufunc__ncx2_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_isf_float
+ufunc__ncx2_isf_ptr[2*0+1] = ("_ncx2_isf")
+ufunc__ncx2_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_isf_double
+ufunc__ncx2_isf_ptr[2*1+1] = ("_ncx2_isf")
+ufunc__ncx2_isf_data[0] = &ufunc__ncx2_isf_ptr[2*0]
+ufunc__ncx2_isf_data[1] = &ufunc__ncx2_isf_ptr[2*1]
+_ncx2_isf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_isf_loops, ufunc__ncx2_isf_data, ufunc__ncx2_isf_types, 2, 3, 1, 0, "_ncx2_isf", ufunc__ncx2_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_pdf_loops[2]
+cdef void *ufunc__ncx2_pdf_ptr[4]
+cdef void *ufunc__ncx2_pdf_data[2]
+cdef char ufunc__ncx2_pdf_types[8]
+cdef char *ufunc__ncx2_pdf_doc = (
+    "_ncx2_pdf(x, k, l)\n"
+    "\n"
+    "Probability density function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_pdf_types[0] = NPY_FLOAT
+ufunc__ncx2_pdf_types[1] = NPY_FLOAT
+ufunc__ncx2_pdf_types[2] = NPY_FLOAT
+ufunc__ncx2_pdf_types[3] = NPY_FLOAT
+ufunc__ncx2_pdf_types[4] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[5] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[6] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[7] = NPY_DOUBLE
+ufunc__ncx2_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_pdf_float
+ufunc__ncx2_pdf_ptr[2*0+1] = ("_ncx2_pdf")
+ufunc__ncx2_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_pdf_double
+ufunc__ncx2_pdf_ptr[2*1+1] = ("_ncx2_pdf")
+ufunc__ncx2_pdf_data[0] = &ufunc__ncx2_pdf_ptr[2*0]
+ufunc__ncx2_pdf_data[1] = &ufunc__ncx2_pdf_ptr[2*1]
+_ncx2_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_pdf_loops, ufunc__ncx2_pdf_data, ufunc__ncx2_pdf_types, 2, 3, 1, 0, "_ncx2_pdf", ufunc__ncx2_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_ppf_loops[2]
+cdef void *ufunc__ncx2_ppf_ptr[4]
+cdef void *ufunc__ncx2_ppf_data[2]
+cdef char ufunc__ncx2_ppf_types[8]
+cdef char *ufunc__ncx2_ppf_doc = (
+    "_ncx2_ppf(x, k, l)\n"
+    "\n"
+    "Percent point function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_ppf_types[0] = NPY_FLOAT
+ufunc__ncx2_ppf_types[1] = NPY_FLOAT
+ufunc__ncx2_ppf_types[2] = NPY_FLOAT
+ufunc__ncx2_ppf_types[3] = NPY_FLOAT
+ufunc__ncx2_ppf_types[4] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[5] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[6] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[7] = NPY_DOUBLE
+ufunc__ncx2_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_ppf_float
+ufunc__ncx2_ppf_ptr[2*0+1] = ("_ncx2_ppf")
+ufunc__ncx2_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_ppf_double
+ufunc__ncx2_ppf_ptr[2*1+1] = ("_ncx2_ppf")
+ufunc__ncx2_ppf_data[0] = &ufunc__ncx2_ppf_ptr[2*0]
+ufunc__ncx2_ppf_data[1] = &ufunc__ncx2_ppf_ptr[2*1]
+_ncx2_ppf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_ppf_loops, ufunc__ncx2_ppf_data, ufunc__ncx2_ppf_types, 2, 3, 1, 0, "_ncx2_ppf", ufunc__ncx2_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_sf_loops[2]
+cdef void *ufunc__ncx2_sf_ptr[4]
+cdef void *ufunc__ncx2_sf_data[2]
+cdef char ufunc__ncx2_sf_types[8]
+cdef char *ufunc__ncx2_sf_doc = (
+    "_ncx2_sf(x, k, l)\n"
+    "\n"
+    "Survival function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_sf_types[0] = NPY_FLOAT
+ufunc__ncx2_sf_types[1] = NPY_FLOAT
+ufunc__ncx2_sf_types[2] = NPY_FLOAT
+ufunc__ncx2_sf_types[3] = NPY_FLOAT
+ufunc__ncx2_sf_types[4] = NPY_DOUBLE
+ufunc__ncx2_sf_types[5] = NPY_DOUBLE
+ufunc__ncx2_sf_types[6] = NPY_DOUBLE
+ufunc__ncx2_sf_types[7] = NPY_DOUBLE
+ufunc__ncx2_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_sf_float
+ufunc__ncx2_sf_ptr[2*0+1] = ("_ncx2_sf")
+ufunc__ncx2_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_sf_double
+ufunc__ncx2_sf_ptr[2*1+1] = ("_ncx2_sf")
+ufunc__ncx2_sf_data[0] = &ufunc__ncx2_sf_ptr[2*0]
+ufunc__ncx2_sf_data[1] = &ufunc__ncx2_sf_ptr[2*1]
+_ncx2_sf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_sf_loops, ufunc__ncx2_sf_data, ufunc__ncx2_sf_types, 2, 3, 1, 0, "_ncx2_sf", ufunc__ncx2_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__sf_error_test_function_loops[1]
+cdef void *ufunc__sf_error_test_function_ptr[2]
+cdef void *ufunc__sf_error_test_function_data[1]
+cdef char ufunc__sf_error_test_function_types[2]
+cdef char *ufunc__sf_error_test_function_doc = (
+    "Private function; do not use.")
+ufunc__sf_error_test_function_loops[0] = loop_i_i__As_l_l
+ufunc__sf_error_test_function_types[0] = NPY_LONG
+ufunc__sf_error_test_function_types[1] = NPY_LONG
+ufunc__sf_error_test_function_ptr[2*0] = _func__sf_error_test_function
+ufunc__sf_error_test_function_ptr[2*0+1] = ("_sf_error_test_function")
+ufunc__sf_error_test_function_data[0] = &ufunc__sf_error_test_function_ptr[2*0]
+_sf_error_test_function = np.PyUFunc_FromFuncAndData(ufunc__sf_error_test_function_loops, ufunc__sf_error_test_function_data, ufunc__sf_error_test_function_types, 1, 1, 1, 0, "_sf_error_test_function", ufunc__sf_error_test_function_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_cdf_loops[2]
+cdef void *ufunc__skewnorm_cdf_ptr[4]
+cdef void *ufunc__skewnorm_cdf_data[2]
+cdef char ufunc__skewnorm_cdf_types[10]
+cdef char *ufunc__skewnorm_cdf_doc = (
+    "_skewnorm_cdf(x, l, sc, sh)\n"
+    "\n"
+    "Cumulative density function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_cdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_cdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_cdf_types[0] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[1] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[2] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[3] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[4] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_float
+ufunc__skewnorm_cdf_ptr[2*0+1] = ("_skewnorm_cdf")
+ufunc__skewnorm_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_double
+ufunc__skewnorm_cdf_ptr[2*1+1] = ("_skewnorm_cdf")
+ufunc__skewnorm_cdf_data[0] = &ufunc__skewnorm_cdf_ptr[2*0]
+ufunc__skewnorm_cdf_data[1] = &ufunc__skewnorm_cdf_ptr[2*1]
+_skewnorm_cdf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_cdf_loops, ufunc__skewnorm_cdf_data, ufunc__skewnorm_cdf_types, 2, 4, 1, 0, "_skewnorm_cdf", ufunc__skewnorm_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_isf_loops[2]
+cdef void *ufunc__skewnorm_isf_ptr[4]
+cdef void *ufunc__skewnorm_isf_data[2]
+cdef char ufunc__skewnorm_isf_types[10]
+cdef char *ufunc__skewnorm_isf_doc = (
+    "_skewnorm_isf(x, l, sc, sh)\n"
+    "\n"
+    "Inverse survival function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_isf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_isf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_isf_types[0] = NPY_FLOAT
+ufunc__skewnorm_isf_types[1] = NPY_FLOAT
+ufunc__skewnorm_isf_types[2] = NPY_FLOAT
+ufunc__skewnorm_isf_types[3] = NPY_FLOAT
+ufunc__skewnorm_isf_types[4] = NPY_FLOAT
+ufunc__skewnorm_isf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_isf_float
+ufunc__skewnorm_isf_ptr[2*0+1] = ("_skewnorm_isf")
+ufunc__skewnorm_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_isf_double
+ufunc__skewnorm_isf_ptr[2*1+1] = ("_skewnorm_isf")
+ufunc__skewnorm_isf_data[0] = &ufunc__skewnorm_isf_ptr[2*0]
+ufunc__skewnorm_isf_data[1] = &ufunc__skewnorm_isf_ptr[2*1]
+_skewnorm_isf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_isf_loops, ufunc__skewnorm_isf_data, ufunc__skewnorm_isf_types, 2, 4, 1, 0, "_skewnorm_isf", ufunc__skewnorm_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_ppf_loops[2]
+cdef void *ufunc__skewnorm_ppf_ptr[4]
+cdef void *ufunc__skewnorm_ppf_data[2]
+cdef char ufunc__skewnorm_ppf_types[10]
+cdef char *ufunc__skewnorm_ppf_doc = (
+    "_skewnorm_ppf(x, l, sc, sh)\n"
+    "\n"
+    "Percent point function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_ppf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_ppf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_ppf_types[0] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[1] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[2] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[3] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[4] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_float
+ufunc__skewnorm_ppf_ptr[2*0+1] = ("_skewnorm_ppf")
+ufunc__skewnorm_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_double
+ufunc__skewnorm_ppf_ptr[2*1+1] = ("_skewnorm_ppf")
+ufunc__skewnorm_ppf_data[0] = &ufunc__skewnorm_ppf_ptr[2*0]
+ufunc__skewnorm_ppf_data[1] = &ufunc__skewnorm_ppf_ptr[2*1]
+_skewnorm_ppf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_ppf_loops, ufunc__skewnorm_ppf_data, ufunc__skewnorm_ppf_types, 2, 4, 1, 0, "_skewnorm_ppf", ufunc__skewnorm_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovc_loops[3]
+cdef void *ufunc__smirnovc_ptr[6]
+cdef void *ufunc__smirnovc_data[3]
+cdef char ufunc__smirnovc_types[9]
+cdef char *ufunc__smirnovc_doc = (
+    "_smirnovc(n, d)\n"
+    " Internal function, do not use.")
+ufunc__smirnovc_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovc_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovc_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovc_types[0] = NPY_INTP
+ufunc__smirnovc_types[1] = NPY_DOUBLE
+ufunc__smirnovc_types[2] = NPY_DOUBLE
+ufunc__smirnovc_types[3] = NPY_FLOAT
+ufunc__smirnovc_types[4] = NPY_FLOAT
+ufunc__smirnovc_types[5] = NPY_FLOAT
+ufunc__smirnovc_types[6] = NPY_DOUBLE
+ufunc__smirnovc_types[7] = NPY_DOUBLE
+ufunc__smirnovc_types[8] = NPY_DOUBLE
+ufunc__smirnovc_ptr[2*0] = _func_cephes_smirnovc_wrap
+ufunc__smirnovc_ptr[2*0+1] = ("_smirnovc")
+ufunc__smirnovc_ptr[2*1] = _func_smirnovc_unsafe
+ufunc__smirnovc_ptr[2*1+1] = ("_smirnovc")
+ufunc__smirnovc_ptr[2*2] = _func_smirnovc_unsafe
+ufunc__smirnovc_ptr[2*2+1] = ("_smirnovc")
+ufunc__smirnovc_data[0] = &ufunc__smirnovc_ptr[2*0]
+ufunc__smirnovc_data[1] = &ufunc__smirnovc_ptr[2*1]
+ufunc__smirnovc_data[2] = &ufunc__smirnovc_ptr[2*2]
+_smirnovc = np.PyUFunc_FromFuncAndData(ufunc__smirnovc_loops, ufunc__smirnovc_data, ufunc__smirnovc_types, 3, 2, 1, 0, "_smirnovc", ufunc__smirnovc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovci_loops[3]
+cdef void *ufunc__smirnovci_ptr[6]
+cdef void *ufunc__smirnovci_data[3]
+cdef char ufunc__smirnovci_types[9]
+cdef char *ufunc__smirnovci_doc = (
+    "Internal function, do not use.")
+ufunc__smirnovci_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovci_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovci_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovci_types[0] = NPY_INTP
+ufunc__smirnovci_types[1] = NPY_DOUBLE
+ufunc__smirnovci_types[2] = NPY_DOUBLE
+ufunc__smirnovci_types[3] = NPY_FLOAT
+ufunc__smirnovci_types[4] = NPY_FLOAT
+ufunc__smirnovci_types[5] = NPY_FLOAT
+ufunc__smirnovci_types[6] = NPY_DOUBLE
+ufunc__smirnovci_types[7] = NPY_DOUBLE
+ufunc__smirnovci_types[8] = NPY_DOUBLE
+ufunc__smirnovci_ptr[2*0] = _func_cephes_smirnovci_wrap
+ufunc__smirnovci_ptr[2*0+1] = ("_smirnovci")
+ufunc__smirnovci_ptr[2*1] = _func_smirnovci_unsafe
+ufunc__smirnovci_ptr[2*1+1] = ("_smirnovci")
+ufunc__smirnovci_ptr[2*2] = _func_smirnovci_unsafe
+ufunc__smirnovci_ptr[2*2+1] = ("_smirnovci")
+ufunc__smirnovci_data[0] = &ufunc__smirnovci_ptr[2*0]
+ufunc__smirnovci_data[1] = &ufunc__smirnovci_ptr[2*1]
+ufunc__smirnovci_data[2] = &ufunc__smirnovci_ptr[2*2]
+_smirnovci = np.PyUFunc_FromFuncAndData(ufunc__smirnovci_loops, ufunc__smirnovci_data, ufunc__smirnovci_types, 3, 2, 1, 0, "_smirnovci", ufunc__smirnovci_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovp_loops[3]
+cdef void *ufunc__smirnovp_ptr[6]
+cdef void *ufunc__smirnovp_data[3]
+cdef char ufunc__smirnovp_types[9]
+cdef char *ufunc__smirnovp_doc = (
+    "_smirnovp(n, p)\n"
+    " Internal function, do not use.")
+ufunc__smirnovp_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovp_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovp_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovp_types[0] = NPY_INTP
+ufunc__smirnovp_types[1] = NPY_DOUBLE
+ufunc__smirnovp_types[2] = NPY_DOUBLE
+ufunc__smirnovp_types[3] = NPY_FLOAT
+ufunc__smirnovp_types[4] = NPY_FLOAT
+ufunc__smirnovp_types[5] = NPY_FLOAT
+ufunc__smirnovp_types[6] = NPY_DOUBLE
+ufunc__smirnovp_types[7] = NPY_DOUBLE
+ufunc__smirnovp_types[8] = NPY_DOUBLE
+ufunc__smirnovp_ptr[2*0] = _func_cephes_smirnovp_wrap
+ufunc__smirnovp_ptr[2*0+1] = ("_smirnovp")
+ufunc__smirnovp_ptr[2*1] = _func_smirnovp_unsafe
+ufunc__smirnovp_ptr[2*1+1] = ("_smirnovp")
+ufunc__smirnovp_ptr[2*2] = _func_smirnovp_unsafe
+ufunc__smirnovp_ptr[2*2+1] = ("_smirnovp")
+ufunc__smirnovp_data[0] = &ufunc__smirnovp_ptr[2*0]
+ufunc__smirnovp_data[1] = &ufunc__smirnovp_ptr[2*1]
+ufunc__smirnovp_data[2] = &ufunc__smirnovp_ptr[2*2]
+_smirnovp = np.PyUFunc_FromFuncAndData(ufunc__smirnovp_loops, ufunc__smirnovp_data, ufunc__smirnovp_types, 3, 2, 1, 0, "_smirnovp", ufunc__smirnovp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__stirling2_inexact_loops[2]
+cdef void *ufunc__stirling2_inexact_ptr[4]
+cdef void *ufunc__stirling2_inexact_data[2]
+cdef char ufunc__stirling2_inexact_types[6]
+cdef char *ufunc__stirling2_inexact_doc = (
+    "Internal function, do not use.")
+ufunc__stirling2_inexact_loops[0] = loop_d_dd__As_ff_f
+ufunc__stirling2_inexact_loops[1] = loop_d_dd__As_dd_d
+ufunc__stirling2_inexact_types[0] = NPY_FLOAT
+ufunc__stirling2_inexact_types[1] = NPY_FLOAT
+ufunc__stirling2_inexact_types[2] = NPY_FLOAT
+ufunc__stirling2_inexact_types[3] = NPY_DOUBLE
+ufunc__stirling2_inexact_types[4] = NPY_DOUBLE
+ufunc__stirling2_inexact_types[5] = NPY_DOUBLE
+ufunc__stirling2_inexact_ptr[2*0] = scipy.special._ufuncs_cxx._export__stirling2_inexact
+ufunc__stirling2_inexact_ptr[2*0+1] = ("_stirling2_inexact")
+ufunc__stirling2_inexact_ptr[2*1] = scipy.special._ufuncs_cxx._export__stirling2_inexact
+ufunc__stirling2_inexact_ptr[2*1+1] = ("_stirling2_inexact")
+ufunc__stirling2_inexact_data[0] = &ufunc__stirling2_inexact_ptr[2*0]
+ufunc__stirling2_inexact_data[1] = &ufunc__stirling2_inexact_ptr[2*1]
+_stirling2_inexact = np.PyUFunc_FromFuncAndData(ufunc__stirling2_inexact_loops, ufunc__stirling2_inexact_data, ufunc__stirling2_inexact_types, 2, 2, 1, 0, "_stirling2_inexact", ufunc__stirling2_inexact_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_asymp_large_z_loops[1]
+cdef void *ufunc__struve_asymp_large_z_ptr[2]
+cdef void *ufunc__struve_asymp_large_z_data[1]
+cdef char ufunc__struve_asymp_large_z_types[5]
+cdef char *ufunc__struve_asymp_large_z_doc = (
+    "_struve_asymp_large_z(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using asymptotic expansion\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_asymp_large_z_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_asymp_large_z_types[0] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[1] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[2] = NPY_INTP
+ufunc__struve_asymp_large_z_types[3] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[4] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_ptr[2*0] = _func_cephes__struve_asymp_large_z
+ufunc__struve_asymp_large_z_ptr[2*0+1] = ("_struve_asymp_large_z")
+ufunc__struve_asymp_large_z_data[0] = &ufunc__struve_asymp_large_z_ptr[2*0]
+_struve_asymp_large_z = np.PyUFunc_FromFuncAndData(ufunc__struve_asymp_large_z_loops, ufunc__struve_asymp_large_z_data, ufunc__struve_asymp_large_z_types, 1, 3, 2, 0, "_struve_asymp_large_z", ufunc__struve_asymp_large_z_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_bessel_series_loops[1]
+cdef void *ufunc__struve_bessel_series_ptr[2]
+cdef void *ufunc__struve_bessel_series_data[1]
+cdef char ufunc__struve_bessel_series_types[5]
+cdef char *ufunc__struve_bessel_series_doc = (
+    "_struve_bessel_series(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using Bessel function series\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_bessel_series_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_bessel_series_types[0] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[1] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[2] = NPY_INTP
+ufunc__struve_bessel_series_types[3] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[4] = NPY_DOUBLE
+ufunc__struve_bessel_series_ptr[2*0] = _func_cephes__struve_bessel_series
+ufunc__struve_bessel_series_ptr[2*0+1] = ("_struve_bessel_series")
+ufunc__struve_bessel_series_data[0] = &ufunc__struve_bessel_series_ptr[2*0]
+_struve_bessel_series = np.PyUFunc_FromFuncAndData(ufunc__struve_bessel_series_loops, ufunc__struve_bessel_series_data, ufunc__struve_bessel_series_types, 1, 3, 2, 0, "_struve_bessel_series", ufunc__struve_bessel_series_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_power_series_loops[1]
+cdef void *ufunc__struve_power_series_ptr[2]
+cdef void *ufunc__struve_power_series_data[1]
+cdef char ufunc__struve_power_series_types[5]
+cdef char *ufunc__struve_power_series_doc = (
+    "_struve_power_series(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using power series\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_power_series_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_power_series_types[0] = NPY_DOUBLE
+ufunc__struve_power_series_types[1] = NPY_DOUBLE
+ufunc__struve_power_series_types[2] = NPY_INTP
+ufunc__struve_power_series_types[3] = NPY_DOUBLE
+ufunc__struve_power_series_types[4] = NPY_DOUBLE
+ufunc__struve_power_series_ptr[2*0] = _func_cephes__struve_power_series
+ufunc__struve_power_series_ptr[2*0+1] = ("_struve_power_series")
+ufunc__struve_power_series_data[0] = &ufunc__struve_power_series_ptr[2*0]
+_struve_power_series = np.PyUFunc_FromFuncAndData(ufunc__struve_power_series_loops, ufunc__struve_power_series_data, ufunc__struve_power_series_types, 1, 3, 2, 0, "_struve_power_series", ufunc__struve_power_series_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_agm_loops[2]
+cdef void *ufunc_agm_ptr[4]
+cdef void *ufunc_agm_data[2]
+cdef char ufunc_agm_types[6]
+cdef char *ufunc_agm_doc = (
+    "agm(a, b, out=None)\n"
+    "\n"
+    "Compute the arithmetic-geometric mean of `a` and `b`.\n"
+    "\n"
+    "Start with a_0 = a and b_0 = b and iteratively compute::\n"
+    "\n"
+    "    a_{n+1} = (a_n + b_n)/2\n"
+    "    b_{n+1} = sqrt(a_n*b_n)\n"
+    "\n"
+    "a_n and b_n converge to the same limit as n increases; their common\n"
+    "limit is agm(a, b).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real values only. If the values are both negative, the result\n"
+    "    is negative. If one value is negative and the other is positive,\n"
+    "    `nan` is returned.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The arithmetic-geometric mean of `a` and `b`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import agm\n"
+    ">>> a, b = 24.0, 6.0\n"
+    ">>> agm(a, b)\n"
+    "13.458171481725614\n"
+    "\n"
+    "Compare that result to the iteration:\n"
+    "\n"
+    ">>> while a != b:\n"
+    "...     a, b = (a + b)/2, np.sqrt(a*b)\n"
+    "...     print(\"a = %19.16f  b=%19.16f\" % (a, b))\n"
+    "...\n"
+    "a = 15.0000000000000000  b=12.0000000000000000\n"
+    "a = 13.5000000000000000  b=13.4164078649987388\n"
+    "a = 13.4582039324993694  b=13.4581390309909850\n"
+    "a = 13.4581714817451772  b=13.4581714817060547\n"
+    "a = 13.4581714817256159  b=13.4581714817256159\n"
+    "\n"
+    "When array-like arguments are given, broadcasting applies:\n"
+    "\n"
+    ">>> a = np.array([[1.5], [3], [6]])  # a has shape (3, 1).\n"
+    ">>> b = np.array([6, 12, 24, 48])    # b has shape (4,).\n"
+    ">>> agm(a, b)\n"
+    "array([[  3.36454287,   5.42363427,   9.05798751,  15.53650756],\n"
+    "       [  4.37037309,   6.72908574,  10.84726853,  18.11597502],\n"
+    "       [  6.        ,   8.74074619,  13.45817148,  21.69453707]])")
+ufunc_agm_loops[0] = loop_d_dd__As_ff_f
+ufunc_agm_loops[1] = loop_d_dd__As_dd_d
+ufunc_agm_types[0] = NPY_FLOAT
+ufunc_agm_types[1] = NPY_FLOAT
+ufunc_agm_types[2] = NPY_FLOAT
+ufunc_agm_types[3] = NPY_DOUBLE
+ufunc_agm_types[4] = NPY_DOUBLE
+ufunc_agm_types[5] = NPY_DOUBLE
+ufunc_agm_ptr[2*0] = _func_agm
+ufunc_agm_ptr[2*0+1] = ("agm")
+ufunc_agm_ptr[2*1] = _func_agm
+ufunc_agm_ptr[2*1+1] = ("agm")
+ufunc_agm_data[0] = &ufunc_agm_ptr[2*0]
+ufunc_agm_data[1] = &ufunc_agm_ptr[2*1]
+agm = np.PyUFunc_FromFuncAndData(ufunc_agm_loops, ufunc_agm_data, ufunc_agm_types, 2, 2, 1, 0, "agm", ufunc_agm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtr_loops[3]
+cdef void *ufunc_bdtr_ptr[6]
+cdef void *ufunc_bdtr_data[3]
+cdef char ufunc_bdtr_types[12]
+cdef char *ufunc_bdtr_doc = (
+    "bdtr(k, n, p, out=None)\n"
+    "\n"
+    "Binomial distribution cumulative distribution function.\n"
+    "\n"
+    "Sum of the terms 0 through `floor(k)` of the Binomial probability density.\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtr}(k, n, p) =\n"
+    "    \\sum_{j=0}^{\\lfloor k \\rfloor} {{n}\\choose{j}} p^j (1-p)^{n-j}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (double), rounded down to the nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Probability of `floor(k)` or fewer successes in `n` independent events with\n"
+    "    success probabilities of `p`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtr}(k, n, p) =\n"
+    "    I_{1 - p}(n - \\lfloor k \\rfloor, \\lfloor k \\rfloor + 1).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtr`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtr_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtr_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtr_types[0] = NPY_FLOAT
+ufunc_bdtr_types[1] = NPY_FLOAT
+ufunc_bdtr_types[2] = NPY_FLOAT
+ufunc_bdtr_types[3] = NPY_FLOAT
+ufunc_bdtr_types[4] = NPY_DOUBLE
+ufunc_bdtr_types[5] = NPY_INTP
+ufunc_bdtr_types[6] = NPY_DOUBLE
+ufunc_bdtr_types[7] = NPY_DOUBLE
+ufunc_bdtr_types[8] = NPY_DOUBLE
+ufunc_bdtr_types[9] = NPY_DOUBLE
+ufunc_bdtr_types[10] = NPY_DOUBLE
+ufunc_bdtr_types[11] = NPY_DOUBLE
+ufunc_bdtr_ptr[2*0] = _func_bdtr_unsafe
+ufunc_bdtr_ptr[2*0+1] = ("bdtr")
+ufunc_bdtr_ptr[2*1] = _func_cephes_bdtr_wrap
+ufunc_bdtr_ptr[2*1+1] = ("bdtr")
+ufunc_bdtr_ptr[2*2] = _func_bdtr_unsafe
+ufunc_bdtr_ptr[2*2+1] = ("bdtr")
+ufunc_bdtr_data[0] = &ufunc_bdtr_ptr[2*0]
+ufunc_bdtr_data[1] = &ufunc_bdtr_ptr[2*1]
+ufunc_bdtr_data[2] = &ufunc_bdtr_ptr[2*2]
+bdtr = np.PyUFunc_FromFuncAndData(ufunc_bdtr_loops, ufunc_bdtr_data, ufunc_bdtr_types, 3, 3, 1, 0, "bdtr", ufunc_bdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrc_loops[3]
+cdef void *ufunc_bdtrc_ptr[6]
+cdef void *ufunc_bdtrc_data[3]
+cdef char ufunc_bdtrc_types[12]
+cdef char *ufunc_bdtrc_doc = (
+    "bdtrc(k, n, p, out=None)\n"
+    "\n"
+    "Binomial distribution survival function.\n"
+    "\n"
+    "Sum of the terms `floor(k) + 1` through `n` of the binomial probability\n"
+    "density,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtrc}(k, n, p) =\n"
+    "    \\sum_{j=\\lfloor k \\rfloor +1}^n {{n}\\choose{j}} p^j (1-p)^{n-j}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (double), rounded down to nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (int)\n"
+    "p : array_like\n"
+    "    Probability of success in a single event.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Probability of `floor(k) + 1` or more successes in `n` independent\n"
+    "    events with success probabilities of `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "betainc\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtrc}(k, n, p) = I_{p}(\\lfloor k \\rfloor + 1, n - \\lfloor k \\rfloor).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtrc`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrc_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtrc_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtrc_types[0] = NPY_FLOAT
+ufunc_bdtrc_types[1] = NPY_FLOAT
+ufunc_bdtrc_types[2] = NPY_FLOAT
+ufunc_bdtrc_types[3] = NPY_FLOAT
+ufunc_bdtrc_types[4] = NPY_DOUBLE
+ufunc_bdtrc_types[5] = NPY_INTP
+ufunc_bdtrc_types[6] = NPY_DOUBLE
+ufunc_bdtrc_types[7] = NPY_DOUBLE
+ufunc_bdtrc_types[8] = NPY_DOUBLE
+ufunc_bdtrc_types[9] = NPY_DOUBLE
+ufunc_bdtrc_types[10] = NPY_DOUBLE
+ufunc_bdtrc_types[11] = NPY_DOUBLE
+ufunc_bdtrc_ptr[2*0] = _func_bdtrc_unsafe
+ufunc_bdtrc_ptr[2*0+1] = ("bdtrc")
+ufunc_bdtrc_ptr[2*1] = _func_cephes_bdtrc_wrap
+ufunc_bdtrc_ptr[2*1+1] = ("bdtrc")
+ufunc_bdtrc_ptr[2*2] = _func_bdtrc_unsafe
+ufunc_bdtrc_ptr[2*2+1] = ("bdtrc")
+ufunc_bdtrc_data[0] = &ufunc_bdtrc_ptr[2*0]
+ufunc_bdtrc_data[1] = &ufunc_bdtrc_ptr[2*1]
+ufunc_bdtrc_data[2] = &ufunc_bdtrc_ptr[2*2]
+bdtrc = np.PyUFunc_FromFuncAndData(ufunc_bdtrc_loops, ufunc_bdtrc_data, ufunc_bdtrc_types, 3, 3, 1, 0, "bdtrc", ufunc_bdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtri_loops[3]
+cdef void *ufunc_bdtri_ptr[6]
+cdef void *ufunc_bdtri_data[3]
+cdef char ufunc_bdtri_types[12]
+cdef char *ufunc_bdtri_doc = (
+    "bdtri(k, n, y, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `p`.\n"
+    "\n"
+    "Finds the event probability `p` such that the sum of the terms 0 through\n"
+    "`k` of the binomial probability density is equal to the given cumulative\n"
+    "probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (float), rounded down to the nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (float)\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "p : scalar or ndarray\n"
+    "    The event probability such that `bdtr(\\lfloor k \\rfloor, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "betaincinv\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The computation is carried out using the inverse beta integral function\n"
+    "and the relation,::\n"
+    "\n"
+    "    1 - p = betaincinv(n - k, k + 1, y).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtri`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtri_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtri_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtri_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtri_types[0] = NPY_FLOAT
+ufunc_bdtri_types[1] = NPY_FLOAT
+ufunc_bdtri_types[2] = NPY_FLOAT
+ufunc_bdtri_types[3] = NPY_FLOAT
+ufunc_bdtri_types[4] = NPY_DOUBLE
+ufunc_bdtri_types[5] = NPY_INTP
+ufunc_bdtri_types[6] = NPY_DOUBLE
+ufunc_bdtri_types[7] = NPY_DOUBLE
+ufunc_bdtri_types[8] = NPY_DOUBLE
+ufunc_bdtri_types[9] = NPY_DOUBLE
+ufunc_bdtri_types[10] = NPY_DOUBLE
+ufunc_bdtri_types[11] = NPY_DOUBLE
+ufunc_bdtri_ptr[2*0] = _func_bdtri_unsafe
+ufunc_bdtri_ptr[2*0+1] = ("bdtri")
+ufunc_bdtri_ptr[2*1] = _func_cephes_bdtri_wrap
+ufunc_bdtri_ptr[2*1+1] = ("bdtri")
+ufunc_bdtri_ptr[2*2] = _func_bdtri_unsafe
+ufunc_bdtri_ptr[2*2+1] = ("bdtri")
+ufunc_bdtri_data[0] = &ufunc_bdtri_ptr[2*0]
+ufunc_bdtri_data[1] = &ufunc_bdtri_ptr[2*1]
+ufunc_bdtri_data[2] = &ufunc_bdtri_ptr[2*2]
+bdtri = np.PyUFunc_FromFuncAndData(ufunc_bdtri_loops, ufunc_bdtri_data, ufunc_bdtri_types, 3, 3, 1, 0, "bdtri", ufunc_bdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrik_loops[2]
+cdef void *ufunc_bdtrik_ptr[4]
+cdef void *ufunc_bdtrik_data[2]
+cdef char ufunc_bdtrik_types[8]
+cdef char *ufunc_bdtrik_doc = (
+    "bdtrik(y, n, p, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `k`.\n"
+    "\n"
+    "Finds the number of successes `k` such that the sum of the terms 0 through\n"
+    "`k` of the Binomial probability density for `n` events with probability\n"
+    "`p` is equal to the given cumulative probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "n : array_like\n"
+    "    Number of events (float).\n"
+    "p : array_like\n"
+    "    Success probability (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "k : scalar or ndarray\n"
+    "    The number of successes `k` such that `bdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n"
+    "cumulative incomplete beta distribution.\n"
+    "\n"
+    "Computation of `k` involves a search for a value that produces the desired\n"
+    "value of `y`. The search relies on the monotonicity of `y` with `k`.\n"
+    "\n"
+    "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.")
+ufunc_bdtrik_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrik_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_bdtrik_types[0] = NPY_FLOAT
+ufunc_bdtrik_types[1] = NPY_FLOAT
+ufunc_bdtrik_types[2] = NPY_FLOAT
+ufunc_bdtrik_types[3] = NPY_FLOAT
+ufunc_bdtrik_types[4] = NPY_DOUBLE
+ufunc_bdtrik_types[5] = NPY_DOUBLE
+ufunc_bdtrik_types[6] = NPY_DOUBLE
+ufunc_bdtrik_types[7] = NPY_DOUBLE
+ufunc_bdtrik_ptr[2*0] = _func_bdtrik
+ufunc_bdtrik_ptr[2*0+1] = ("bdtrik")
+ufunc_bdtrik_ptr[2*1] = _func_bdtrik
+ufunc_bdtrik_ptr[2*1+1] = ("bdtrik")
+ufunc_bdtrik_data[0] = &ufunc_bdtrik_ptr[2*0]
+ufunc_bdtrik_data[1] = &ufunc_bdtrik_ptr[2*1]
+bdtrik = np.PyUFunc_FromFuncAndData(ufunc_bdtrik_loops, ufunc_bdtrik_data, ufunc_bdtrik_types, 2, 3, 1, 0, "bdtrik", ufunc_bdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrin_loops[2]
+cdef void *ufunc_bdtrin_ptr[4]
+cdef void *ufunc_bdtrin_data[2]
+cdef char ufunc_bdtrin_types[8]
+cdef char *ufunc_bdtrin_doc = (
+    "bdtrin(k, y, p, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `n`.\n"
+    "\n"
+    "Finds the number of events `n` such that the sum of the terms 0 through\n"
+    "`k` of the Binomial probability density for events with probability `p` is\n"
+    "equal to the given cumulative probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (float).\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "p : array_like\n"
+    "    Success probability (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "n : scalar or ndarray\n"
+    "    The number of events `n` such that `bdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n"
+    "cumulative incomplete beta distribution.\n"
+    "\n"
+    "Computation of `n` involves a search for a value that produces the desired\n"
+    "value of `y`. The search relies on the monotonicity of `y` with `n`.\n"
+    "\n"
+    "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.")
+ufunc_bdtrin_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrin_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_bdtrin_types[0] = NPY_FLOAT
+ufunc_bdtrin_types[1] = NPY_FLOAT
+ufunc_bdtrin_types[2] = NPY_FLOAT
+ufunc_bdtrin_types[3] = NPY_FLOAT
+ufunc_bdtrin_types[4] = NPY_DOUBLE
+ufunc_bdtrin_types[5] = NPY_DOUBLE
+ufunc_bdtrin_types[6] = NPY_DOUBLE
+ufunc_bdtrin_types[7] = NPY_DOUBLE
+ufunc_bdtrin_ptr[2*0] = _func_bdtrin
+ufunc_bdtrin_ptr[2*0+1] = ("bdtrin")
+ufunc_bdtrin_ptr[2*1] = _func_bdtrin
+ufunc_bdtrin_ptr[2*1+1] = ("bdtrin")
+ufunc_bdtrin_data[0] = &ufunc_bdtrin_ptr[2*0]
+ufunc_bdtrin_data[1] = &ufunc_bdtrin_ptr[2*1]
+bdtrin = np.PyUFunc_FromFuncAndData(ufunc_bdtrin_loops, ufunc_bdtrin_data, ufunc_bdtrin_types, 2, 3, 1, 0, "bdtrin", ufunc_bdtrin_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betainc_loops[2]
+cdef void *ufunc_betainc_ptr[4]
+cdef void *ufunc_betainc_data[2]
+cdef char ufunc_betainc_types[8]
+cdef char *ufunc_betainc_doc = (
+    "betainc(a, b, x, out=None)\n"
+    "\n"
+    "Regularized incomplete beta function.\n"
+    "\n"
+    "Computes the regularized incomplete beta function, defined as [1]_:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n"
+    "    t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "for :math:`0 \\leq x \\leq 1`.\n"
+    "\n"
+    "This function is the cumulative distribution function for the beta\n"
+    "distribution; its range is [0, 1].\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "beta : beta function\n"
+    "betaincinv : inverse of the regularized incomplete beta function\n"
+    "betaincc : complement of the regularized incomplete beta function\n"
+    "scipy.stats.beta : beta distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The term *regularized* in the name of this function refers to the\n"
+    "scaling of the function by the gamma function terms shown in the\n"
+    "formula.  When not qualified as *regularized*, the name *incomplete\n"
+    "beta function* often refers to just the integral expression,\n"
+    "without the gamma terms.  One can use the function `beta` from\n"
+    "`scipy.special` to get this \"nonregularized\" incomplete beta\n"
+    "function by multiplying the result of ``betainc(a, b, x)`` by\n"
+    "``beta(a, b)``.\n"
+    "\n"
+    "This function wraps the ``ibeta`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "\n"
+    "Let :math:`B(a, b)` be the `beta` function.\n"
+    "\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "The coefficient in terms of `gamma` is equal to\n"
+    ":math:`1/B(a, b)`. Also, when :math:`x=1`\n"
+    "the integral is equal to :math:`B(a, b)`.\n"
+    "Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.\n"
+    "\n"
+    ">>> sc.betainc(0.2, 3.5, 1.0)\n"
+    "1.0\n"
+    "\n"
+    "It satisfies\n"
+    ":math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,\n"
+    "where :math:`F` is the hypergeometric function `hyp2f1`:\n"
+    "\n"
+    ">>> a, b, x = 1.4, 3.1, 0.5\n"
+    ">>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))\n"
+    "0.8148904036225295\n"
+    ">>> sc.betainc(a, b, x)\n"
+    "0.8148904036225296\n"
+    "\n"
+    "This functions satisfies the relationship\n"
+    ":math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:\n"
+    "\n"
+    ">>> sc.betainc(2.2, 3.1, 0.4)\n"
+    "0.49339638807619446\n"
+    ">>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)\n"
+    "0.49339638807619446")
+ufunc_betainc_loops[0] = loop_f_fff__As_fff_f
+ufunc_betainc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betainc_types[0] = NPY_FLOAT
+ufunc_betainc_types[1] = NPY_FLOAT
+ufunc_betainc_types[2] = NPY_FLOAT
+ufunc_betainc_types[3] = NPY_FLOAT
+ufunc_betainc_types[4] = NPY_DOUBLE
+ufunc_betainc_types[5] = NPY_DOUBLE
+ufunc_betainc_types[6] = NPY_DOUBLE
+ufunc_betainc_types[7] = NPY_DOUBLE
+ufunc_betainc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_float
+ufunc_betainc_ptr[2*0+1] = ("betainc")
+ufunc_betainc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_double
+ufunc_betainc_ptr[2*1+1] = ("betainc")
+ufunc_betainc_data[0] = &ufunc_betainc_ptr[2*0]
+ufunc_betainc_data[1] = &ufunc_betainc_ptr[2*1]
+betainc = np.PyUFunc_FromFuncAndData(ufunc_betainc_loops, ufunc_betainc_data, ufunc_betainc_types, 2, 3, 1, 0, "betainc", ufunc_betainc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betaincc_loops[2]
+cdef void *ufunc_betaincc_ptr[4]
+cdef void *ufunc_betaincc_data[2]
+cdef char ufunc_betaincc_types[8]
+cdef char *ufunc_betaincc_doc = (
+    "betaincc(a, b, x, out=None)\n"
+    "\n"
+    "Complement of the regularized incomplete beta function.\n"
+    "\n"
+    "Computes the complement of the regularized incomplete beta function,\n"
+    "defined as [1]_:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\bar{I}_x(a, b) = 1 - I_x(a, b)\n"
+    "                    = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n"
+    "                              t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "for :math:`0 \\leq x \\leq 1`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "betaincinv : inverse of the regularized incomplete beta function\n"
+    "betainccinv :\n"
+    "    inverse of the complement of the regularized incomplete beta function\n"
+    "beta : beta function\n"
+    "scipy.stats.beta : beta distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.11.0\n"
+    "\n"
+    "This function wraps the ``ibetac`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import betaincc, betainc\n"
+    "\n"
+    "The naive calculation ``1 - betainc(a, b, x)`` loses precision when\n"
+    "the values of ``betainc(a, b, x)`` are close to 1:\n"
+    "\n"
+    ">>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])\n"
+    "array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])\n"
+    "\n"
+    "By using ``betaincc``, we get the correct values:\n"
+    "\n"
+    ">>> betaincc(0.5, 8, [0.9, 0.99, 0.999])\n"
+    "array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])")
+ufunc_betaincc_loops[0] = loop_f_fff__As_fff_f
+ufunc_betaincc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betaincc_types[0] = NPY_FLOAT
+ufunc_betaincc_types[1] = NPY_FLOAT
+ufunc_betaincc_types[2] = NPY_FLOAT
+ufunc_betaincc_types[3] = NPY_FLOAT
+ufunc_betaincc_types[4] = NPY_DOUBLE
+ufunc_betaincc_types[5] = NPY_DOUBLE
+ufunc_betaincc_types[6] = NPY_DOUBLE
+ufunc_betaincc_types[7] = NPY_DOUBLE
+ufunc_betaincc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_float
+ufunc_betaincc_ptr[2*0+1] = ("betaincc")
+ufunc_betaincc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_double
+ufunc_betaincc_ptr[2*1+1] = ("betaincc")
+ufunc_betaincc_data[0] = &ufunc_betaincc_ptr[2*0]
+ufunc_betaincc_data[1] = &ufunc_betaincc_ptr[2*1]
+betaincc = np.PyUFunc_FromFuncAndData(ufunc_betaincc_loops, ufunc_betaincc_data, ufunc_betaincc_types, 2, 3, 1, 0, "betaincc", ufunc_betaincc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betainccinv_loops[2]
+cdef void *ufunc_betainccinv_ptr[4]
+cdef void *ufunc_betainccinv_data[2]
+cdef char ufunc_betainccinv_types[8]
+cdef char *ufunc_betainccinv_doc = (
+    "betainccinv(a, b, y, out=None)\n"
+    "\n"
+    "Inverse of the complemented regularized incomplete beta function.\n"
+    "\n"
+    "Computes :math:`x` such that:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    y = 1 - I_x(a, b) = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n"
+    "    \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "where :math:`I_x` is the normalized incomplete beta function `betainc`\n"
+    "and :math:`\\Gamma` is the `gamma` function [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "y : array_like\n"
+    "    Real-valued input\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the inverse of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "betaincc : complement of the regularized incomplete beta function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.11.0\n"
+    "\n"
+    "This function wraps the ``ibetac_inv`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import betainccinv, betaincc\n"
+    "\n"
+    "This function is the inverse of `betaincc` for fixed\n"
+    "values of :math:`a` and :math:`b`.\n"
+    "\n"
+    ">>> a, b = 1.2, 3.1\n"
+    ">>> y = betaincc(a, b, 0.2)\n"
+    ">>> betainccinv(a, b, y)\n"
+    "0.2\n"
+    "\n"
+    ">>> a, b = 7, 2.5\n"
+    ">>> x = betainccinv(a, b, 0.875)\n"
+    ">>> betaincc(a, b, x)\n"
+    "0.875")
+ufunc_betainccinv_loops[0] = loop_f_fff__As_fff_f
+ufunc_betainccinv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betainccinv_types[0] = NPY_FLOAT
+ufunc_betainccinv_types[1] = NPY_FLOAT
+ufunc_betainccinv_types[2] = NPY_FLOAT
+ufunc_betainccinv_types[3] = NPY_FLOAT
+ufunc_betainccinv_types[4] = NPY_DOUBLE
+ufunc_betainccinv_types[5] = NPY_DOUBLE
+ufunc_betainccinv_types[6] = NPY_DOUBLE
+ufunc_betainccinv_types[7] = NPY_DOUBLE
+ufunc_betainccinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_inv_float
+ufunc_betainccinv_ptr[2*0+1] = ("betainccinv")
+ufunc_betainccinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_inv_double
+ufunc_betainccinv_ptr[2*1+1] = ("betainccinv")
+ufunc_betainccinv_data[0] = &ufunc_betainccinv_ptr[2*0]
+ufunc_betainccinv_data[1] = &ufunc_betainccinv_ptr[2*1]
+betainccinv = np.PyUFunc_FromFuncAndData(ufunc_betainccinv_loops, ufunc_betainccinv_data, ufunc_betainccinv_types, 2, 3, 1, 0, "betainccinv", ufunc_betainccinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betaincinv_loops[2]
+cdef void *ufunc_betaincinv_ptr[4]
+cdef void *ufunc_betaincinv_data[2]
+cdef char ufunc_betaincinv_types[8]
+cdef char *ufunc_betaincinv_doc = (
+    "betaincinv(a, b, y, out=None)\n"
+    "\n"
+    "Inverse of the regularized incomplete beta function.\n"
+    "\n"
+    "Computes :math:`x` such that:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    y = I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n"
+    "    \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "where :math:`I_x` is the normalized incomplete beta function `betainc`\n"
+    "and :math:`\\Gamma` is the `gamma` function [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "y : array_like\n"
+    "    Real-valued input\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the inverse of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "gamma : gamma function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function wraps the ``ibeta_inv`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "This function is the inverse of `betainc` for fixed\n"
+    "values of :math:`a` and :math:`b`.\n"
+    "\n"
+    ">>> a, b = 1.2, 3.1\n"
+    ">>> y = sc.betainc(a, b, 0.2)\n"
+    ">>> sc.betaincinv(a, b, y)\n"
+    "0.2\n"
+    ">>>\n"
+    ">>> a, b = 7.5, 0.4\n"
+    ">>> x = sc.betaincinv(a, b, 0.5)\n"
+    ">>> sc.betainc(a, b, x)\n"
+    "0.5")
+ufunc_betaincinv_loops[0] = loop_f_fff__As_fff_f
+ufunc_betaincinv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betaincinv_types[0] = NPY_FLOAT
+ufunc_betaincinv_types[1] = NPY_FLOAT
+ufunc_betaincinv_types[2] = NPY_FLOAT
+ufunc_betaincinv_types[3] = NPY_FLOAT
+ufunc_betaincinv_types[4] = NPY_DOUBLE
+ufunc_betaincinv_types[5] = NPY_DOUBLE
+ufunc_betaincinv_types[6] = NPY_DOUBLE
+ufunc_betaincinv_types[7] = NPY_DOUBLE
+ufunc_betaincinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_inv_float
+ufunc_betaincinv_ptr[2*0+1] = ("betaincinv")
+ufunc_betaincinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_inv_double
+ufunc_betaincinv_ptr[2*1+1] = ("betaincinv")
+ufunc_betaincinv_data[0] = &ufunc_betaincinv_ptr[2*0]
+ufunc_betaincinv_data[1] = &ufunc_betaincinv_ptr[2*1]
+betaincinv = np.PyUFunc_FromFuncAndData(ufunc_betaincinv_loops, ufunc_betaincinv_data, ufunc_betaincinv_types, 2, 3, 1, 0, "betaincinv", ufunc_betaincinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_boxcox_loops[2]
+cdef void *ufunc_boxcox_ptr[4]
+cdef void *ufunc_boxcox_data[2]
+cdef char ufunc_boxcox_types[6]
+cdef char *ufunc_boxcox_doc = (
+    "boxcox(x, lmbda, out=None)\n"
+    "\n"
+    "Compute the Box-Cox transformation.\n"
+    "\n"
+    "The Box-Cox transformation is::\n"
+    "\n"
+    "    y = (x**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(x)                  if lmbda == 0\n"
+    "\n"
+    "Returns `nan` if ``x < 0``.\n"
+    "Returns `-inf` if ``x == 0`` and ``lmbda < 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.14.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox\n"
+    ">>> boxcox([1, 4, 10], 2.5)\n"
+    "array([   0.        ,   12.4       ,  126.09110641])\n"
+    ">>> boxcox(2, [0, 1, 2])\n"
+    "array([ 0.69314718,  1.        ,  1.5       ])")
+ufunc_boxcox_loops[0] = loop_d_dd__As_ff_f
+ufunc_boxcox_loops[1] = loop_d_dd__As_dd_d
+ufunc_boxcox_types[0] = NPY_FLOAT
+ufunc_boxcox_types[1] = NPY_FLOAT
+ufunc_boxcox_types[2] = NPY_FLOAT
+ufunc_boxcox_types[3] = NPY_DOUBLE
+ufunc_boxcox_types[4] = NPY_DOUBLE
+ufunc_boxcox_types[5] = NPY_DOUBLE
+ufunc_boxcox_ptr[2*0] = _func_boxcox
+ufunc_boxcox_ptr[2*0+1] = ("boxcox")
+ufunc_boxcox_ptr[2*1] = _func_boxcox
+ufunc_boxcox_ptr[2*1+1] = ("boxcox")
+ufunc_boxcox_data[0] = &ufunc_boxcox_ptr[2*0]
+ufunc_boxcox_data[1] = &ufunc_boxcox_ptr[2*1]
+boxcox = np.PyUFunc_FromFuncAndData(ufunc_boxcox_loops, ufunc_boxcox_data, ufunc_boxcox_types, 2, 2, 1, 0, "boxcox", ufunc_boxcox_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_boxcox1p_loops[2]
+cdef void *ufunc_boxcox1p_ptr[4]
+cdef void *ufunc_boxcox1p_data[2]
+cdef char ufunc_boxcox1p_types[6]
+cdef char *ufunc_boxcox1p_doc = (
+    "boxcox1p(x, lmbda, out=None)\n"
+    "\n"
+    "Compute the Box-Cox transformation of 1 + `x`.\n"
+    "\n"
+    "The Box-Cox transformation computed by `boxcox1p` is::\n"
+    "\n"
+    "    y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(1+x)                    if lmbda == 0\n"
+    "\n"
+    "Returns `nan` if ``x < -1``.\n"
+    "Returns `-inf` if ``x == -1`` and ``lmbda < 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.14.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox1p\n"
+    ">>> boxcox1p(1e-4, [0, 0.5, 1])\n"
+    "array([  9.99950003e-05,   9.99975001e-05,   1.00000000e-04])\n"
+    ">>> boxcox1p([0.01, 0.1], 0.25)\n"
+    "array([ 0.00996272,  0.09645476])")
+ufunc_boxcox1p_loops[0] = loop_d_dd__As_ff_f
+ufunc_boxcox1p_loops[1] = loop_d_dd__As_dd_d
+ufunc_boxcox1p_types[0] = NPY_FLOAT
+ufunc_boxcox1p_types[1] = NPY_FLOAT
+ufunc_boxcox1p_types[2] = NPY_FLOAT
+ufunc_boxcox1p_types[3] = NPY_DOUBLE
+ufunc_boxcox1p_types[4] = NPY_DOUBLE
+ufunc_boxcox1p_types[5] = NPY_DOUBLE
+ufunc_boxcox1p_ptr[2*0] = _func_boxcox1p
+ufunc_boxcox1p_ptr[2*0+1] = ("boxcox1p")
+ufunc_boxcox1p_ptr[2*1] = _func_boxcox1p
+ufunc_boxcox1p_ptr[2*1+1] = ("boxcox1p")
+ufunc_boxcox1p_data[0] = &ufunc_boxcox1p_ptr[2*0]
+ufunc_boxcox1p_data[1] = &ufunc_boxcox1p_ptr[2*1]
+boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_boxcox1p_loops, ufunc_boxcox1p_data, ufunc_boxcox1p_types, 2, 2, 1, 0, "boxcox1p", ufunc_boxcox1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_btdtria_loops[2]
+cdef void *ufunc_btdtria_ptr[4]
+cdef void *ufunc_btdtria_data[2]
+cdef char ufunc_btdtria_types[8]
+cdef char *ufunc_btdtria_doc = (
+    "btdtria(p, b, x, out=None)\n"
+    "\n"
+    "Inverse of `betainc` with respect to `a`.\n"
+    "\n"
+    "This is the inverse of the beta cumulative distribution function, `betainc`,\n"
+    "considered as a function of `a`, returning the value of `a` for which\n"
+    "`betainc(a, b, x) = p`, or\n"
+    "\n"
+    ".. math::\n"
+    "    p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "b : array_like\n"
+    "    Shape parameter (`b` > 0).\n"
+    "x : array_like\n"
+    "    The quantile, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "a : scalar or ndarray\n"
+    "    The value of the shape parameter `a` such that `betainc(a, b, x) = p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `a`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Algorithm 708: Significant Digit Computation of the Incomplete Beta\n"
+    "       Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.")
+ufunc_btdtria_loops[0] = loop_d_ddd__As_fff_f
+ufunc_btdtria_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_btdtria_types[0] = NPY_FLOAT
+ufunc_btdtria_types[1] = NPY_FLOAT
+ufunc_btdtria_types[2] = NPY_FLOAT
+ufunc_btdtria_types[3] = NPY_FLOAT
+ufunc_btdtria_types[4] = NPY_DOUBLE
+ufunc_btdtria_types[5] = NPY_DOUBLE
+ufunc_btdtria_types[6] = NPY_DOUBLE
+ufunc_btdtria_types[7] = NPY_DOUBLE
+ufunc_btdtria_ptr[2*0] = _func_btdtria
+ufunc_btdtria_ptr[2*0+1] = ("btdtria")
+ufunc_btdtria_ptr[2*1] = _func_btdtria
+ufunc_btdtria_ptr[2*1+1] = ("btdtria")
+ufunc_btdtria_data[0] = &ufunc_btdtria_ptr[2*0]
+ufunc_btdtria_data[1] = &ufunc_btdtria_ptr[2*1]
+btdtria = np.PyUFunc_FromFuncAndData(ufunc_btdtria_loops, ufunc_btdtria_data, ufunc_btdtria_types, 2, 3, 1, 0, "btdtria", ufunc_btdtria_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_btdtrib_loops[2]
+cdef void *ufunc_btdtrib_ptr[4]
+cdef void *ufunc_btdtrib_data[2]
+cdef char ufunc_btdtrib_types[8]
+cdef char *ufunc_btdtrib_doc = (
+    "btdtria(a, p, x, out=None)\n"
+    "\n"
+    "Inverse of `betainc` with respect to `b`.\n"
+    "\n"
+    "This is the inverse of the beta cumulative distribution function, `betainc`,\n"
+    "considered as a function of `b`, returning the value of `b` for which\n"
+    "`betainc(a, b, x) = p`, or\n"
+    "\n"
+    ".. math::\n"
+    "    p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    Shape parameter (`a` > 0).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "x : array_like\n"
+    "    The quantile, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "b : scalar or ndarray\n"
+    "    The value of the shape parameter `b` such that `betainc(a, b, x) = p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `b` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `b`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Algorithm 708: Significant Digit Computation of the Incomplete Beta\n"
+    "       Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.")
+ufunc_btdtrib_loops[0] = loop_d_ddd__As_fff_f
+ufunc_btdtrib_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_btdtrib_types[0] = NPY_FLOAT
+ufunc_btdtrib_types[1] = NPY_FLOAT
+ufunc_btdtrib_types[2] = NPY_FLOAT
+ufunc_btdtrib_types[3] = NPY_FLOAT
+ufunc_btdtrib_types[4] = NPY_DOUBLE
+ufunc_btdtrib_types[5] = NPY_DOUBLE
+ufunc_btdtrib_types[6] = NPY_DOUBLE
+ufunc_btdtrib_types[7] = NPY_DOUBLE
+ufunc_btdtrib_ptr[2*0] = _func_btdtrib
+ufunc_btdtrib_ptr[2*0+1] = ("btdtrib")
+ufunc_btdtrib_ptr[2*1] = _func_btdtrib
+ufunc_btdtrib_ptr[2*1+1] = ("btdtrib")
+ufunc_btdtrib_data[0] = &ufunc_btdtrib_ptr[2*0]
+ufunc_btdtrib_data[1] = &ufunc_btdtrib_ptr[2*1]
+btdtrib = np.PyUFunc_FromFuncAndData(ufunc_btdtrib_loops, ufunc_btdtrib_data, ufunc_btdtrib_types, 2, 3, 1, 0, "btdtrib", ufunc_btdtrib_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtr_loops[2]
+cdef void *ufunc_chdtr_ptr[4]
+cdef void *ufunc_chdtr_data[2]
+cdef char ufunc_chdtr_types[6]
+cdef char *ufunc_chdtr_doc = (
+    "chdtr(v, x, out=None)\n"
+    "\n"
+    "Chi square cumulative distribution function.\n"
+    "\n"
+    "Returns the area under the left tail (from 0 to `x`) of the Chi\n"
+    "square probability density function with `v` degrees of freedom:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_0^x t^{v/2 - 1} e^{-t/2} dt\n"
+    "\n"
+    "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n"
+    "integral can be expressed in terms of the regularized lower\n"
+    "incomplete gamma function `gammainc` as\n"
+    "``gammainc(v / 2, x / 2)``. [1]_\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "x : array_like\n"
+    "    Upper bound of the integral.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the cumulative distribution function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtrc, chdtri, chdtriv, gammainc\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It can be expressed in terms of the regularized lower incomplete\n"
+    "gamma function.\n"
+    "\n"
+    ">>> v = 1\n"
+    ">>> x = np.arange(4)\n"
+    ">>> sc.chdtr(v, x)\n"
+    "array([0.        , 0.68268949, 0.84270079, 0.91673548])\n"
+    ">>> sc.gammainc(v / 2, x / 2)\n"
+    "array([0.        , 0.68268949, 0.84270079, 0.91673548])")
+ufunc_chdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtr_types[0] = NPY_FLOAT
+ufunc_chdtr_types[1] = NPY_FLOAT
+ufunc_chdtr_types[2] = NPY_FLOAT
+ufunc_chdtr_types[3] = NPY_DOUBLE
+ufunc_chdtr_types[4] = NPY_DOUBLE
+ufunc_chdtr_types[5] = NPY_DOUBLE
+ufunc_chdtr_ptr[2*0] = _func_xsf_chdtr
+ufunc_chdtr_ptr[2*0+1] = ("chdtr")
+ufunc_chdtr_ptr[2*1] = _func_xsf_chdtr
+ufunc_chdtr_ptr[2*1+1] = ("chdtr")
+ufunc_chdtr_data[0] = &ufunc_chdtr_ptr[2*0]
+ufunc_chdtr_data[1] = &ufunc_chdtr_ptr[2*1]
+chdtr = np.PyUFunc_FromFuncAndData(ufunc_chdtr_loops, ufunc_chdtr_data, ufunc_chdtr_types, 2, 2, 1, 0, "chdtr", ufunc_chdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtrc_loops[2]
+cdef void *ufunc_chdtrc_ptr[4]
+cdef void *ufunc_chdtrc_data[2]
+cdef char ufunc_chdtrc_types[6]
+cdef char *ufunc_chdtrc_doc = (
+    "chdtrc(v, x, out=None)\n"
+    "\n"
+    "Chi square survival function.\n"
+    "\n"
+    "Returns the area under the right hand tail (from `x` to infinity)\n"
+    "of the Chi square probability density function with `v` degrees of\n"
+    "freedom:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_x^\\infty t^{v/2 - 1} e^{-t/2} dt\n"
+    "\n"
+    "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n"
+    "integral can be expressed in terms of the regularized upper\n"
+    "incomplete gamma function `gammaincc` as\n"
+    "``gammaincc(v / 2, x / 2)``. [1]_\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "x : array_like\n"
+    "    Lower bound of the integral.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the survival function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtr, chdtri, chdtriv, gammaincc\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It can be expressed in terms of the regularized upper incomplete\n"
+    "gamma function.\n"
+    "\n"
+    ">>> v = 1\n"
+    ">>> x = np.arange(4)\n"
+    ">>> sc.chdtrc(v, x)\n"
+    "array([1.        , 0.31731051, 0.15729921, 0.08326452])\n"
+    ">>> sc.gammaincc(v / 2, x / 2)\n"
+    "array([1.        , 0.31731051, 0.15729921, 0.08326452])")
+ufunc_chdtrc_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtrc_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtrc_types[0] = NPY_FLOAT
+ufunc_chdtrc_types[1] = NPY_FLOAT
+ufunc_chdtrc_types[2] = NPY_FLOAT
+ufunc_chdtrc_types[3] = NPY_DOUBLE
+ufunc_chdtrc_types[4] = NPY_DOUBLE
+ufunc_chdtrc_types[5] = NPY_DOUBLE
+ufunc_chdtrc_ptr[2*0] = _func_xsf_chdtrc
+ufunc_chdtrc_ptr[2*0+1] = ("chdtrc")
+ufunc_chdtrc_ptr[2*1] = _func_xsf_chdtrc
+ufunc_chdtrc_ptr[2*1+1] = ("chdtrc")
+ufunc_chdtrc_data[0] = &ufunc_chdtrc_ptr[2*0]
+ufunc_chdtrc_data[1] = &ufunc_chdtrc_ptr[2*1]
+chdtrc = np.PyUFunc_FromFuncAndData(ufunc_chdtrc_loops, ufunc_chdtrc_data, ufunc_chdtrc_types, 2, 2, 1, 0, "chdtrc", ufunc_chdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtri_loops[2]
+cdef void *ufunc_chdtri_ptr[4]
+cdef void *ufunc_chdtri_data[2]
+cdef char ufunc_chdtri_types[6]
+cdef char *ufunc_chdtri_doc = (
+    "chdtri(v, p, out=None)\n"
+    "\n"
+    "Inverse to `chdtrc` with respect to `x`.\n"
+    "\n"
+    "Returns `x` such that ``chdtrc(v, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "p : array_like\n"
+    "    Probability.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value so that the probability a Chi square random variable\n"
+    "    with `v` degrees of freedom is greater than `x` equals `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtrc, chdtr, chdtriv\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It inverts `chdtrc`.\n"
+    "\n"
+    ">>> v, p = 1, 0.3\n"
+    ">>> sc.chdtrc(v, sc.chdtri(v, p))\n"
+    "0.3\n"
+    ">>> x = 1\n"
+    ">>> sc.chdtri(v, sc.chdtrc(v, x))\n"
+    "1.0")
+ufunc_chdtri_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtri_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtri_types[0] = NPY_FLOAT
+ufunc_chdtri_types[1] = NPY_FLOAT
+ufunc_chdtri_types[2] = NPY_FLOAT
+ufunc_chdtri_types[3] = NPY_DOUBLE
+ufunc_chdtri_types[4] = NPY_DOUBLE
+ufunc_chdtri_types[5] = NPY_DOUBLE
+ufunc_chdtri_ptr[2*0] = _func_xsf_chdtri
+ufunc_chdtri_ptr[2*0+1] = ("chdtri")
+ufunc_chdtri_ptr[2*1] = _func_xsf_chdtri
+ufunc_chdtri_ptr[2*1+1] = ("chdtri")
+ufunc_chdtri_data[0] = &ufunc_chdtri_ptr[2*0]
+ufunc_chdtri_data[1] = &ufunc_chdtri_ptr[2*1]
+chdtri = np.PyUFunc_FromFuncAndData(ufunc_chdtri_loops, ufunc_chdtri_data, ufunc_chdtri_types, 2, 2, 1, 0, "chdtri", ufunc_chdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtriv_loops[2]
+cdef void *ufunc_chdtriv_ptr[4]
+cdef void *ufunc_chdtriv_data[2]
+cdef char ufunc_chdtriv_types[6]
+cdef char *ufunc_chdtriv_doc = (
+    "chdtriv(p, x, out=None)\n"
+    "\n"
+    "Inverse to `chdtr` with respect to `v`.\n"
+    "\n"
+    "Returns `v` such that ``chdtr(v, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability that the Chi square random variable is less than\n"
+    "    or equal to `x`.\n"
+    "x : array_like\n"
+    "    Nonnegative input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Degrees of freedom.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtr, chdtrc, chdtri\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It inverts `chdtr`.\n"
+    "\n"
+    ">>> p, x = 0.5, 1\n"
+    ">>> sc.chdtr(sc.chdtriv(p, x), x)\n"
+    "0.5000000000202172\n"
+    ">>> v = 1\n"
+    ">>> sc.chdtriv(sc.chdtr(v, x), v)\n"
+    "1.0000000000000013")
+ufunc_chdtriv_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtriv_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtriv_types[0] = NPY_FLOAT
+ufunc_chdtriv_types[1] = NPY_FLOAT
+ufunc_chdtriv_types[2] = NPY_FLOAT
+ufunc_chdtriv_types[3] = NPY_DOUBLE
+ufunc_chdtriv_types[4] = NPY_DOUBLE
+ufunc_chdtriv_types[5] = NPY_DOUBLE
+ufunc_chdtriv_ptr[2*0] = _func_chdtriv
+ufunc_chdtriv_ptr[2*0+1] = ("chdtriv")
+ufunc_chdtriv_ptr[2*1] = _func_chdtriv
+ufunc_chdtriv_ptr[2*1+1] = ("chdtriv")
+ufunc_chdtriv_data[0] = &ufunc_chdtriv_ptr[2*0]
+ufunc_chdtriv_data[1] = &ufunc_chdtriv_ptr[2*1]
+chdtriv = np.PyUFunc_FromFuncAndData(ufunc_chdtriv_loops, ufunc_chdtriv_data, ufunc_chdtriv_types, 2, 2, 1, 0, "chdtriv", ufunc_chdtriv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtr_loops[2]
+cdef void *ufunc_chndtr_ptr[4]
+cdef void *ufunc_chndtr_data[2]
+cdef char ufunc_chndtr_types[8]
+cdef char *ufunc_chndtr_doc = (
+    "chndtr(x, df, nc, out=None)\n"
+    "\n"
+    "Non-central chi square cumulative distribution function\n"
+    "\n"
+    "The cumulative distribution function is given by:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P(\\chi^{\\prime 2} \\vert \\nu, \\lambda) =\\sum_{j=0}^{\\infty}\n"
+    "    e^{-\\lambda /2}\n"
+    "    \\frac{(\\lambda /2)^j}{j!} P(\\chi^{\\prime 2} \\vert \\nu + 2j),\n"
+    "\n"
+    "where :math:`\\nu > 0` is the degrees of freedom (``df``) and\n"
+    ":math:`\\lambda \\geq 0` is the non-centrality parameter (``nc``).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value of the non-central chi square cumulative distribution function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtrix, chndtridf, chndtrinc")
+ufunc_chndtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtr_types[0] = NPY_FLOAT
+ufunc_chndtr_types[1] = NPY_FLOAT
+ufunc_chndtr_types[2] = NPY_FLOAT
+ufunc_chndtr_types[3] = NPY_FLOAT
+ufunc_chndtr_types[4] = NPY_DOUBLE
+ufunc_chndtr_types[5] = NPY_DOUBLE
+ufunc_chndtr_types[6] = NPY_DOUBLE
+ufunc_chndtr_types[7] = NPY_DOUBLE
+ufunc_chndtr_ptr[2*0] = _func_chndtr
+ufunc_chndtr_ptr[2*0+1] = ("chndtr")
+ufunc_chndtr_ptr[2*1] = _func_chndtr
+ufunc_chndtr_ptr[2*1+1] = ("chndtr")
+ufunc_chndtr_data[0] = &ufunc_chndtr_ptr[2*0]
+ufunc_chndtr_data[1] = &ufunc_chndtr_ptr[2*1]
+chndtr = np.PyUFunc_FromFuncAndData(ufunc_chndtr_loops, ufunc_chndtr_data, ufunc_chndtr_types, 2, 3, 1, 0, "chndtr", ufunc_chndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtridf_loops[2]
+cdef void *ufunc_chndtridf_ptr[4]
+cdef void *ufunc_chndtridf_data[2]
+cdef char ufunc_chndtridf_types[8]
+cdef char *ufunc_chndtridf_doc = (
+    "chndtridf(x, p, nc, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `df`\n"
+    "\n"
+    "Calculated using a search to find a value for `df` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    Degrees of freedom\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtrix, chndtrinc")
+ufunc_chndtridf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtridf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtridf_types[0] = NPY_FLOAT
+ufunc_chndtridf_types[1] = NPY_FLOAT
+ufunc_chndtridf_types[2] = NPY_FLOAT
+ufunc_chndtridf_types[3] = NPY_FLOAT
+ufunc_chndtridf_types[4] = NPY_DOUBLE
+ufunc_chndtridf_types[5] = NPY_DOUBLE
+ufunc_chndtridf_types[6] = NPY_DOUBLE
+ufunc_chndtridf_types[7] = NPY_DOUBLE
+ufunc_chndtridf_ptr[2*0] = _func_chndtridf
+ufunc_chndtridf_ptr[2*0+1] = ("chndtridf")
+ufunc_chndtridf_ptr[2*1] = _func_chndtridf
+ufunc_chndtridf_ptr[2*1+1] = ("chndtridf")
+ufunc_chndtridf_data[0] = &ufunc_chndtridf_ptr[2*0]
+ufunc_chndtridf_data[1] = &ufunc_chndtridf_ptr[2*1]
+chndtridf = np.PyUFunc_FromFuncAndData(ufunc_chndtridf_loops, ufunc_chndtridf_data, ufunc_chndtridf_types, 2, 3, 1, 0, "chndtridf", ufunc_chndtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtrinc_loops[2]
+cdef void *ufunc_chndtrinc_ptr[4]
+cdef void *ufunc_chndtrinc_data[2]
+cdef char ufunc_chndtrinc_types[8]
+cdef char *ufunc_chndtrinc_doc = (
+    "chndtrinc(x, df, p, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `nc`\n"
+    "\n"
+    "Calculated using a search to find a value for `df` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Non-centrality\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtrix, chndtrinc")
+ufunc_chndtrinc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtrinc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtrinc_types[0] = NPY_FLOAT
+ufunc_chndtrinc_types[1] = NPY_FLOAT
+ufunc_chndtrinc_types[2] = NPY_FLOAT
+ufunc_chndtrinc_types[3] = NPY_FLOAT
+ufunc_chndtrinc_types[4] = NPY_DOUBLE
+ufunc_chndtrinc_types[5] = NPY_DOUBLE
+ufunc_chndtrinc_types[6] = NPY_DOUBLE
+ufunc_chndtrinc_types[7] = NPY_DOUBLE
+ufunc_chndtrinc_ptr[2*0] = _func_chndtrinc
+ufunc_chndtrinc_ptr[2*0+1] = ("chndtrinc")
+ufunc_chndtrinc_ptr[2*1] = _func_chndtrinc
+ufunc_chndtrinc_ptr[2*1+1] = ("chndtrinc")
+ufunc_chndtrinc_data[0] = &ufunc_chndtrinc_ptr[2*0]
+ufunc_chndtrinc_data[1] = &ufunc_chndtrinc_ptr[2*1]
+chndtrinc = np.PyUFunc_FromFuncAndData(ufunc_chndtrinc_loops, ufunc_chndtrinc_data, ufunc_chndtrinc_types, 2, 3, 1, 0, "chndtrinc", ufunc_chndtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtrix_loops[2]
+cdef void *ufunc_chndtrix_ptr[4]
+cdef void *ufunc_chndtrix_data[2]
+cdef char ufunc_chndtrix_types[8]
+cdef char *ufunc_chndtrix_doc = (
+    "chndtrix(p, df, nc, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `x`\n"
+    "\n"
+    "Calculated using a search to find a value for `x` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value so that the probability a non-central Chi square random variable\n"
+    "    with `df` degrees of freedom and non-centrality, `nc`, is greater than\n"
+    "    `x` equals `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtridf, chndtrinc")
+ufunc_chndtrix_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtrix_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtrix_types[0] = NPY_FLOAT
+ufunc_chndtrix_types[1] = NPY_FLOAT
+ufunc_chndtrix_types[2] = NPY_FLOAT
+ufunc_chndtrix_types[3] = NPY_FLOAT
+ufunc_chndtrix_types[4] = NPY_DOUBLE
+ufunc_chndtrix_types[5] = NPY_DOUBLE
+ufunc_chndtrix_types[6] = NPY_DOUBLE
+ufunc_chndtrix_types[7] = NPY_DOUBLE
+ufunc_chndtrix_ptr[2*0] = _func_chndtrix
+ufunc_chndtrix_ptr[2*0+1] = ("chndtrix")
+ufunc_chndtrix_ptr[2*1] = _func_chndtrix
+ufunc_chndtrix_ptr[2*1+1] = ("chndtrix")
+ufunc_chndtrix_data[0] = &ufunc_chndtrix_ptr[2*0]
+ufunc_chndtrix_data[1] = &ufunc_chndtrix_ptr[2*1]
+chndtrix = np.PyUFunc_FromFuncAndData(ufunc_chndtrix_loops, ufunc_chndtrix_data, ufunc_chndtrix_types, 2, 3, 1, 0, "chndtrix", ufunc_chndtrix_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_dawsn_loops[4]
+cdef void *ufunc_dawsn_ptr[8]
+cdef void *ufunc_dawsn_data[4]
+cdef char ufunc_dawsn_types[8]
+cdef char *ufunc_dawsn_doc = (
+    "dawsn(x, out=None)\n"
+    "\n"
+    "Dawson's integral.\n"
+    "\n"
+    "Computes::\n"
+    "\n"
+    "    exp(-x**2) * integral(exp(t**2), t=0..x).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Function parameter.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Value of the integral.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "wofz, erf, erfc, erfcx, erfi\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-15, 15, num=1000)\n"
+    ">>> plt.plot(x, special.dawsn(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$dawsn(x)$')\n"
+    ">>> plt.show()")
+ufunc_dawsn_loops[0] = loop_d_d__As_f_f
+ufunc_dawsn_loops[1] = loop_d_d__As_d_d
+ufunc_dawsn_loops[2] = loop_D_D__As_F_F
+ufunc_dawsn_loops[3] = loop_D_D__As_D_D
+ufunc_dawsn_types[0] = NPY_FLOAT
+ufunc_dawsn_types[1] = NPY_FLOAT
+ufunc_dawsn_types[2] = NPY_DOUBLE
+ufunc_dawsn_types[3] = NPY_DOUBLE
+ufunc_dawsn_types[4] = NPY_CFLOAT
+ufunc_dawsn_types[5] = NPY_CFLOAT
+ufunc_dawsn_types[6] = NPY_CDOUBLE
+ufunc_dawsn_types[7] = NPY_CDOUBLE
+ufunc_dawsn_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn
+ufunc_dawsn_ptr[2*0+1] = ("dawsn")
+ufunc_dawsn_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn
+ufunc_dawsn_ptr[2*1+1] = ("dawsn")
+ufunc_dawsn_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex
+ufunc_dawsn_ptr[2*2+1] = ("dawsn")
+ufunc_dawsn_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex
+ufunc_dawsn_ptr[2*3+1] = ("dawsn")
+ufunc_dawsn_data[0] = &ufunc_dawsn_ptr[2*0]
+ufunc_dawsn_data[1] = &ufunc_dawsn_ptr[2*1]
+ufunc_dawsn_data[2] = &ufunc_dawsn_ptr[2*2]
+ufunc_dawsn_data[3] = &ufunc_dawsn_ptr[2*3]
+dawsn = np.PyUFunc_FromFuncAndData(ufunc_dawsn_loops, ufunc_dawsn_data, ufunc_dawsn_types, 4, 1, 1, 0, "dawsn", ufunc_dawsn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprc_loops[4]
+cdef void *ufunc_elliprc_ptr[8]
+cdef void *ufunc_elliprc_data[4]
+cdef char ufunc_elliprc_types[12]
+cdef char *ufunc_elliprc_doc = (
+    "elliprc(x, y, out=None)\n"
+    "\n"
+    "Degenerate symmetric elliptic integral.\n"
+    "\n"
+    "The function RC is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{C}}(x, y) =\n"
+    "       \\frac{1}{2} \\int_0^{+\\infty} (t + x)^{-1/2} (t + y)^{-1} dt\n"
+    "       = R_{\\mathrm{F}}(x, y, y)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Real or complex input parameters. `x` can be any number in the\n"
+    "    complex plane cut along the negative real axis. `y` must be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If `y` is real and negative, the Cauchy\n"
+    "    principal value is returned. If both of `x` and `y` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==\n"
+    "elliprf(x, y, y)``. It is an elementary function rather than an elliptic\n"
+    "integral.\n"
+    "\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E6\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprc\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprc(scale*x, scale*y)\n"
+    "(0.5484493976710874-0.4169557678995833j)\n"
+    "\n"
+    ">>> elliprc(x, y)/np.sqrt(scale)\n"
+    "(0.5484493976710874-0.41695576789958333j)\n"
+    "\n"
+    "When the two arguments coincide, the integral is particularly\n"
+    "simple:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprc(x, x)\n"
+    "(0.4299173120614631-0.3041729818745595j)\n"
+    "\n"
+    ">>> 1/np.sqrt(x)\n"
+    "(0.4299173120614631-0.30417298187455954j)\n"
+    "\n"
+    "Another simple case: the first argument vanishes:\n"
+    "\n"
+    ">>> y = 1.2 + 3.4j\n"
+    ">>> elliprc(0, y)\n"
+    "(0.6753125346116815-0.47779380263880866j)\n"
+    "\n"
+    ">>> np.pi/2/np.sqrt(y)\n"
+    "(0.6753125346116815-0.4777938026388088j)\n"
+    "\n"
+    "When `x` and `y` are both positive, we can express\n"
+    ":math:`R_C(x,y)` in terms of more elementary functions.  For the\n"
+    "case :math:`0 \\le x < y`,\n"
+    "\n"
+    ">>> x = 3.2\n"
+    ">>> y = 6.\n"
+    ">>> elliprc(x, y)\n"
+    "0.44942991498453444\n"
+    "\n"
+    ">>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)\n"
+    "0.44942991498453433\n"
+    "\n"
+    "And for the case :math:`0 \\le y < x`,\n"
+    "\n"
+    ">>> x = 6.\n"
+    ">>> y = 3.2\n"
+    ">>> elliprc(x,y)\n"
+    "0.4989837501576147\n"
+    "\n"
+    ">>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)\n"
+    "0.49898375015761476")
+ufunc_elliprc_loops[0] = loop_d_dd__As_ff_f
+ufunc_elliprc_loops[1] = loop_d_dd__As_dd_d
+ufunc_elliprc_loops[2] = loop_D_DD__As_FF_F
+ufunc_elliprc_loops[3] = loop_D_DD__As_DD_D
+ufunc_elliprc_types[0] = NPY_FLOAT
+ufunc_elliprc_types[1] = NPY_FLOAT
+ufunc_elliprc_types[2] = NPY_FLOAT
+ufunc_elliprc_types[3] = NPY_DOUBLE
+ufunc_elliprc_types[4] = NPY_DOUBLE
+ufunc_elliprc_types[5] = NPY_DOUBLE
+ufunc_elliprc_types[6] = NPY_CFLOAT
+ufunc_elliprc_types[7] = NPY_CFLOAT
+ufunc_elliprc_types[8] = NPY_CFLOAT
+ufunc_elliprc_types[9] = NPY_CDOUBLE
+ufunc_elliprc_types[10] = NPY_CDOUBLE
+ufunc_elliprc_types[11] = NPY_CDOUBLE
+ufunc_elliprc_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RC
+ufunc_elliprc_ptr[2*0+1] = ("elliprc")
+ufunc_elliprc_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RC
+ufunc_elliprc_ptr[2*1+1] = ("elliprc")
+ufunc_elliprc_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RC
+ufunc_elliprc_ptr[2*2+1] = ("elliprc")
+ufunc_elliprc_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RC
+ufunc_elliprc_ptr[2*3+1] = ("elliprc")
+ufunc_elliprc_data[0] = &ufunc_elliprc_ptr[2*0]
+ufunc_elliprc_data[1] = &ufunc_elliprc_ptr[2*1]
+ufunc_elliprc_data[2] = &ufunc_elliprc_ptr[2*2]
+ufunc_elliprc_data[3] = &ufunc_elliprc_ptr[2*3]
+elliprc = np.PyUFunc_FromFuncAndData(ufunc_elliprc_loops, ufunc_elliprc_data, ufunc_elliprc_types, 4, 2, 1, 0, "elliprc", ufunc_elliprc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprd_loops[4]
+cdef void *ufunc_elliprd_ptr[8]
+cdef void *ufunc_elliprd_data[4]
+cdef char ufunc_elliprd_types[16]
+cdef char *ufunc_elliprd_doc = (
+    "elliprd(x, y, z, out=None)\n"
+    "\n"
+    "Symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "The function RD is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{D}}(x, y, z) =\n"
+    "       \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}\n"
+    "       dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x` or `y` can be any number in the\n"
+    "    complex plane cut along the negative real axis, but at most one of them\n"
+    "    can be zero, while `z` must be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric elliptic integral.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==\n"
+    "elliprj(x, y, z, z)``.\n"
+    "\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E5\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprd\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprd(scale*x, scale*y, scale*z)\n"
+    "(-0.03703043835680379-0.24500934665683802j)\n"
+    "\n"
+    ">>> elliprd(x, y, z)*np.power(scale, -1.5)\n"
+    "(-0.0370304383568038-0.24500934665683805j)\n"
+    "\n"
+    "All three arguments coincide:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprd(x, x, x)\n"
+    "(-0.03986825876151896-0.14051741840449586j)\n"
+    "\n"
+    ">>> np.power(x, -1.5)\n"
+    "(-0.03986825876151894-0.14051741840449583j)\n"
+    "\n"
+    "The so-called \"second lemniscate constant\":\n"
+    "\n"
+    ">>> elliprd(0, 2, 1)/3\n"
+    "0.5990701173677961\n"
+    "\n"
+    ">>> from scipy.special import gamma\n"
+    ">>> gamma(0.75)**2/np.sqrt(2*np.pi)\n"
+    "0.5990701173677959")
+ufunc_elliprd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprd_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprd_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprd_types[0] = NPY_FLOAT
+ufunc_elliprd_types[1] = NPY_FLOAT
+ufunc_elliprd_types[2] = NPY_FLOAT
+ufunc_elliprd_types[3] = NPY_FLOAT
+ufunc_elliprd_types[4] = NPY_DOUBLE
+ufunc_elliprd_types[5] = NPY_DOUBLE
+ufunc_elliprd_types[6] = NPY_DOUBLE
+ufunc_elliprd_types[7] = NPY_DOUBLE
+ufunc_elliprd_types[8] = NPY_CFLOAT
+ufunc_elliprd_types[9] = NPY_CFLOAT
+ufunc_elliprd_types[10] = NPY_CFLOAT
+ufunc_elliprd_types[11] = NPY_CFLOAT
+ufunc_elliprd_types[12] = NPY_CDOUBLE
+ufunc_elliprd_types[13] = NPY_CDOUBLE
+ufunc_elliprd_types[14] = NPY_CDOUBLE
+ufunc_elliprd_types[15] = NPY_CDOUBLE
+ufunc_elliprd_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RD
+ufunc_elliprd_ptr[2*0+1] = ("elliprd")
+ufunc_elliprd_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RD
+ufunc_elliprd_ptr[2*1+1] = ("elliprd")
+ufunc_elliprd_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RD
+ufunc_elliprd_ptr[2*2+1] = ("elliprd")
+ufunc_elliprd_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RD
+ufunc_elliprd_ptr[2*3+1] = ("elliprd")
+ufunc_elliprd_data[0] = &ufunc_elliprd_ptr[2*0]
+ufunc_elliprd_data[1] = &ufunc_elliprd_ptr[2*1]
+ufunc_elliprd_data[2] = &ufunc_elliprd_ptr[2*2]
+ufunc_elliprd_data[3] = &ufunc_elliprd_ptr[2*3]
+elliprd = np.PyUFunc_FromFuncAndData(ufunc_elliprd_loops, ufunc_elliprd_data, ufunc_elliprd_types, 4, 3, 1, 0, "elliprd", ufunc_elliprd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprf_loops[4]
+cdef void *ufunc_elliprf_ptr[8]
+cdef void *ufunc_elliprf_data[4]
+cdef char ufunc_elliprf_types[16]
+cdef char *ufunc_elliprf_doc = (
+    "elliprf(x, y, z, out=None)\n"
+    "\n"
+    "Completely-symmetric elliptic integral of the first kind.\n"
+    "\n"
+    "The function RF is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{F}}(x, y, z) =\n"
+    "       \\frac{1}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` can be any number in\n"
+    "    the complex plane cut along the negative real axis, but at most one of\n"
+    "    them can be zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the return\n"
+    "    value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order (cf.:\n"
+    "https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete\n"
+    "integral. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E1\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprf\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprf(scale*x, scale*y, scale*z)\n"
+    "(0.5328051227278146-0.4008623567957094j)\n"
+    "\n"
+    ">>> elliprf(x, y, z)/np.sqrt(scale)\n"
+    "(0.5328051227278147-0.4008623567957095j)\n"
+    "\n"
+    "All three arguments coincide:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprf(x, x, x)\n"
+    "(0.42991731206146316-0.30417298187455954j)\n"
+    "\n"
+    ">>> 1/np.sqrt(x)\n"
+    "(0.4299173120614631-0.30417298187455954j)\n"
+    "\n"
+    "The so-called \"first lemniscate constant\":\n"
+    "\n"
+    ">>> elliprf(0, 1, 2)\n"
+    "1.3110287771460598\n"
+    "\n"
+    ">>> from scipy.special import gamma\n"
+    ">>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))\n"
+    "1.3110287771460598")
+ufunc_elliprf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprf_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprf_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprf_types[0] = NPY_FLOAT
+ufunc_elliprf_types[1] = NPY_FLOAT
+ufunc_elliprf_types[2] = NPY_FLOAT
+ufunc_elliprf_types[3] = NPY_FLOAT
+ufunc_elliprf_types[4] = NPY_DOUBLE
+ufunc_elliprf_types[5] = NPY_DOUBLE
+ufunc_elliprf_types[6] = NPY_DOUBLE
+ufunc_elliprf_types[7] = NPY_DOUBLE
+ufunc_elliprf_types[8] = NPY_CFLOAT
+ufunc_elliprf_types[9] = NPY_CFLOAT
+ufunc_elliprf_types[10] = NPY_CFLOAT
+ufunc_elliprf_types[11] = NPY_CFLOAT
+ufunc_elliprf_types[12] = NPY_CDOUBLE
+ufunc_elliprf_types[13] = NPY_CDOUBLE
+ufunc_elliprf_types[14] = NPY_CDOUBLE
+ufunc_elliprf_types[15] = NPY_CDOUBLE
+ufunc_elliprf_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RF
+ufunc_elliprf_ptr[2*0+1] = ("elliprf")
+ufunc_elliprf_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RF
+ufunc_elliprf_ptr[2*1+1] = ("elliprf")
+ufunc_elliprf_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RF
+ufunc_elliprf_ptr[2*2+1] = ("elliprf")
+ufunc_elliprf_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RF
+ufunc_elliprf_ptr[2*3+1] = ("elliprf")
+ufunc_elliprf_data[0] = &ufunc_elliprf_ptr[2*0]
+ufunc_elliprf_data[1] = &ufunc_elliprf_ptr[2*1]
+ufunc_elliprf_data[2] = &ufunc_elliprf_ptr[2*2]
+ufunc_elliprf_data[3] = &ufunc_elliprf_ptr[2*3]
+elliprf = np.PyUFunc_FromFuncAndData(ufunc_elliprf_loops, ufunc_elliprf_data, ufunc_elliprf_types, 4, 3, 1, 0, "elliprf", ufunc_elliprf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprg_loops[4]
+cdef void *ufunc_elliprg_ptr[8]
+cdef void *ufunc_elliprg_data[4]
+cdef char ufunc_elliprg_types[16]
+cdef char *ufunc_elliprg_doc = (
+    "elliprg(x, y, z, out=None)\n"
+    "\n"
+    "Completely-symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "The function RG is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{G}}(x, y, z) =\n"
+    "       \\frac{1}{4} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n"
+    "       \\left(\\frac{x}{t + x} + \\frac{y}{t + y} + \\frac{z}{t + z}\\right) t\n"
+    "       dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` can be any number in\n"
+    "    the complex plane cut along the negative real axis.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the return\n"
+    "    value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The implementation uses the relation [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    2 R_{\\mathrm{G}}(x, y, z) =\n"
+    "       z R_{\\mathrm{F}}(x, y, z) -\n"
+    "       \\frac{1}{3} (x - z) (y - z) R_{\\mathrm{D}}(x, y, z) +\n"
+    "       \\sqrt{\\frac{x y}{z}}\n"
+    "\n"
+    "and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can\n"
+    "be chosen as the pivot. When one of the arguments is close to zero, the AGM\n"
+    "method is applied instead. Other special cases are computed following Ref.\n"
+    "[2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E1\n"
+    "       https://dlmf.nist.gov/19.20.ii\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprg\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprg(scale*x, scale*y, scale*z)\n"
+    "(1.195936862005246+0.8470988320464167j)\n"
+    "\n"
+    ">>> elliprg(x, y, z)*np.sqrt(scale)\n"
+    "(1.195936862005246+0.8470988320464165j)\n"
+    "\n"
+    "Simplifications:\n"
+    "\n"
+    ">>> elliprg(0, y, y)\n"
+    "1.756203682760182\n"
+    "\n"
+    ">>> 0.25*np.pi*np.sqrt(y)\n"
+    "1.7562036827601817\n"
+    "\n"
+    ">>> elliprg(0, 0, z)\n"
+    "1.224744871391589\n"
+    "\n"
+    ">>> 0.5*np.sqrt(z)\n"
+    "1.224744871391589\n"
+    "\n"
+    "The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and\n"
+    "``c`` is given by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    S = 4 \\pi a b c R_{\\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).\n"
+    "\n"
+    ">>> def ellipsoid_area(a, b, c):\n"
+    "...     r = 4.0 * np.pi * a * b * c\n"
+    "...     return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))\n"
+    ">>> print(ellipsoid_area(1, 3, 5))\n"
+    "108.62688289491807")
+ufunc_elliprg_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprg_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprg_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprg_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprg_types[0] = NPY_FLOAT
+ufunc_elliprg_types[1] = NPY_FLOAT
+ufunc_elliprg_types[2] = NPY_FLOAT
+ufunc_elliprg_types[3] = NPY_FLOAT
+ufunc_elliprg_types[4] = NPY_DOUBLE
+ufunc_elliprg_types[5] = NPY_DOUBLE
+ufunc_elliprg_types[6] = NPY_DOUBLE
+ufunc_elliprg_types[7] = NPY_DOUBLE
+ufunc_elliprg_types[8] = NPY_CFLOAT
+ufunc_elliprg_types[9] = NPY_CFLOAT
+ufunc_elliprg_types[10] = NPY_CFLOAT
+ufunc_elliprg_types[11] = NPY_CFLOAT
+ufunc_elliprg_types[12] = NPY_CDOUBLE
+ufunc_elliprg_types[13] = NPY_CDOUBLE
+ufunc_elliprg_types[14] = NPY_CDOUBLE
+ufunc_elliprg_types[15] = NPY_CDOUBLE
+ufunc_elliprg_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RG
+ufunc_elliprg_ptr[2*0+1] = ("elliprg")
+ufunc_elliprg_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RG
+ufunc_elliprg_ptr[2*1+1] = ("elliprg")
+ufunc_elliprg_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RG
+ufunc_elliprg_ptr[2*2+1] = ("elliprg")
+ufunc_elliprg_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RG
+ufunc_elliprg_ptr[2*3+1] = ("elliprg")
+ufunc_elliprg_data[0] = &ufunc_elliprg_ptr[2*0]
+ufunc_elliprg_data[1] = &ufunc_elliprg_ptr[2*1]
+ufunc_elliprg_data[2] = &ufunc_elliprg_ptr[2*2]
+ufunc_elliprg_data[3] = &ufunc_elliprg_ptr[2*3]
+elliprg = np.PyUFunc_FromFuncAndData(ufunc_elliprg_loops, ufunc_elliprg_data, ufunc_elliprg_types, 4, 3, 1, 0, "elliprg", ufunc_elliprg_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprj_loops[4]
+cdef void *ufunc_elliprj_ptr[8]
+cdef void *ufunc_elliprj_data[4]
+cdef char ufunc_elliprj_types[20]
+cdef char *ufunc_elliprj_doc = (
+    "elliprj(x, y, z, p, out=None)\n"
+    "\n"
+    "Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "The function RJ is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{J}}(x, y, z, p) =\n"
+    "       \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n"
+    "       (t + p)^{-1} dt\n"
+    "\n"
+    ".. warning::\n"
+    "    This function should be considered experimental when the inputs are\n"
+    "    unbalanced.  Check correctness with another independent implementation.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z, p : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` are numbers in\n"
+    "    the complex plane cut along the negative real axis (subject to further\n"
+    "    constraints, see Notes), and at most one of them can be zero. `p` must\n"
+    "    be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "    If `p` is real and negative, while `x`, `y`, and `z` are real,\n"
+    "    non-negative, and at most one of them is zero, the Cauchy principal\n"
+    "    value is returned. [1]_ [2]_\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [3]_ The algorithm is slightly\n"
+    "different from its earlier incarnation as it appears in [1]_, in that the\n"
+    "call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in\n"
+    "the inner loop. Asymptotic approximations are used where arguments differ\n"
+    "widely in the order of magnitude. [5]_\n"
+    "\n"
+    "The input values are subject to certain sufficient but not necessary\n"
+    "constraints when input arguments are complex. Notably, ``x``, ``y``, and\n"
+    "``z`` must have non-negative real parts, unless two of them are\n"
+    "non-negative and complex-conjugates to each other while the other is a real\n"
+    "non-negative number. [1]_ If the inputs do not satisfy the sufficient\n"
+    "condition described in Ref. [1]_ they are rejected outright with the output\n"
+    "set to NaN.\n"
+    "\n"
+    "In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the\n"
+    "function ``elliprd`` should be preferred because of its less restrictive\n"
+    "domain.\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.20.iii\n"
+    ".. [3] B. C. Carlson, J. FitzSimmons, \"Reduction Theorems for Elliptic\n"
+    "       Integrands with the Square Root of Two Quadratic Factors,\" J.\n"
+    "       Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.\n"
+    "       https://doi.org/10.1016/S0377-0427(00)00282-X\n"
+    ".. [4] F. Johansson, \"Numerical Evaluation of Elliptic Functions, Elliptic\n"
+    "       Integrals and Modular Forms,\" in J. Blumlein, C. Schneider, P.\n"
+    "       Paule, eds., \"Elliptic Integrals, Elliptic Functions and Modular\n"
+    "       Forms in Quantum Field Theory,\" pp. 269-293, 2019 (Cham,\n"
+    "       Switzerland: Springer Nature Switzerland)\n"
+    "       https://arxiv.org/abs/1806.06725\n"
+    "       https://doi.org/10.1007/978-3-030-04480-0\n"
+    ".. [5] B. C. Carlson, J. L. Gustafson, \"Asymptotic Approximations for\n"
+    "       Symmetric Elliptic Integrals,\" SIAM J. Math. Anls., vol. 25, no. 2,\n"
+    "       pp. 288-303, 1994.\n"
+    "       https://arxiv.org/abs/math/9310223\n"
+    "       https://doi.org/10.1137/S0036141092228477\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprj\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> p = 7.\n"
+    ">>> scale = 0.3 - 0.4j\n"
+    ">>> elliprj(scale*x, scale*y, scale*z, scale*p)\n"
+    "(0.10834905565679157+0.19694950747103812j)\n"
+    "\n"
+    ">>> elliprj(x, y, z, p)*np.power(scale, -1.5)\n"
+    "(0.10834905565679556+0.19694950747103854j)\n"
+    "\n"
+    "Reduction to simpler elliptic integral:\n"
+    "\n"
+    ">>> elliprj(x, y, z, z)\n"
+    "(0.08288462362195129-0.028376809745123258j)\n"
+    "\n"
+    ">>> from scipy.special import elliprd\n"
+    ">>> elliprd(x, y, z)\n"
+    "(0.08288462362195136-0.028376809745123296j)\n"
+    "\n"
+    "All arguments coincide:\n"
+    "\n"
+    ">>> elliprj(x, x, x, x)\n"
+    "(-0.03986825876151896-0.14051741840449586j)\n"
+    "\n"
+    ">>> np.power(x, -1.5)\n"
+    "(-0.03986825876151894-0.14051741840449583j)")
+ufunc_elliprj_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_elliprj_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_elliprj_loops[2] = loop_D_DDDD__As_FFFF_F
+ufunc_elliprj_loops[3] = loop_D_DDDD__As_DDDD_D
+ufunc_elliprj_types[0] = NPY_FLOAT
+ufunc_elliprj_types[1] = NPY_FLOAT
+ufunc_elliprj_types[2] = NPY_FLOAT
+ufunc_elliprj_types[3] = NPY_FLOAT
+ufunc_elliprj_types[4] = NPY_FLOAT
+ufunc_elliprj_types[5] = NPY_DOUBLE
+ufunc_elliprj_types[6] = NPY_DOUBLE
+ufunc_elliprj_types[7] = NPY_DOUBLE
+ufunc_elliprj_types[8] = NPY_DOUBLE
+ufunc_elliprj_types[9] = NPY_DOUBLE
+ufunc_elliprj_types[10] = NPY_CFLOAT
+ufunc_elliprj_types[11] = NPY_CFLOAT
+ufunc_elliprj_types[12] = NPY_CFLOAT
+ufunc_elliprj_types[13] = NPY_CFLOAT
+ufunc_elliprj_types[14] = NPY_CFLOAT
+ufunc_elliprj_types[15] = NPY_CDOUBLE
+ufunc_elliprj_types[16] = NPY_CDOUBLE
+ufunc_elliprj_types[17] = NPY_CDOUBLE
+ufunc_elliprj_types[18] = NPY_CDOUBLE
+ufunc_elliprj_types[19] = NPY_CDOUBLE
+ufunc_elliprj_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RJ
+ufunc_elliprj_ptr[2*0+1] = ("elliprj")
+ufunc_elliprj_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RJ
+ufunc_elliprj_ptr[2*1+1] = ("elliprj")
+ufunc_elliprj_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RJ
+ufunc_elliprj_ptr[2*2+1] = ("elliprj")
+ufunc_elliprj_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RJ
+ufunc_elliprj_ptr[2*3+1] = ("elliprj")
+ufunc_elliprj_data[0] = &ufunc_elliprj_ptr[2*0]
+ufunc_elliprj_data[1] = &ufunc_elliprj_ptr[2*1]
+ufunc_elliprj_data[2] = &ufunc_elliprj_ptr[2*2]
+ufunc_elliprj_data[3] = &ufunc_elliprj_ptr[2*3]
+elliprj = np.PyUFunc_FromFuncAndData(ufunc_elliprj_loops, ufunc_elliprj_data, ufunc_elliprj_types, 4, 4, 1, 0, "elliprj", ufunc_elliprj_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_entr_loops[2]
+cdef void *ufunc_entr_ptr[4]
+cdef void *ufunc_entr_data[2]
+cdef char ufunc_entr_types[4]
+cdef char *ufunc_entr_doc = (
+    "entr(x, out=None)\n"
+    "\n"
+    "Elementwise function for computing entropy.\n"
+    "\n"
+    ".. math:: \\text{entr}(x) = \\begin{cases} - x \\log(x) & x > 0  \\\\ 0 & x = 0\n"
+    "          \\\\ -\\infty & \\text{otherwise} \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : ndarray\n"
+    "    Input array.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The value of the elementwise entropy function at the given points `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kl_div, rel_entr, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is concave.\n"
+    "\n"
+    "The origin of this function is in convex programming; see [1]_.\n"
+    "Given a probability distribution :math:`p_1, \\ldots, p_n`,\n"
+    "the definition of entropy in the context of *information theory* is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\sum_{i = 1}^n \\mathrm{entr}(p_i).\n"
+    "\n"
+    "To compute the latter quantity, use `scipy.stats.entropy`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`")
+ufunc_entr_loops[0] = loop_d_d__As_f_f
+ufunc_entr_loops[1] = loop_d_d__As_d_d
+ufunc_entr_types[0] = NPY_FLOAT
+ufunc_entr_types[1] = NPY_FLOAT
+ufunc_entr_types[2] = NPY_DOUBLE
+ufunc_entr_types[3] = NPY_DOUBLE
+ufunc_entr_ptr[2*0] = _func_entr
+ufunc_entr_ptr[2*0+1] = ("entr")
+ufunc_entr_ptr[2*1] = _func_entr
+ufunc_entr_ptr[2*1+1] = ("entr")
+ufunc_entr_data[0] = &ufunc_entr_ptr[2*0]
+ufunc_entr_data[1] = &ufunc_entr_ptr[2*1]
+entr = np.PyUFunc_FromFuncAndData(ufunc_entr_loops, ufunc_entr_data, ufunc_entr_types, 2, 1, 1, 0, "entr", ufunc_entr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erf_loops[4]
+cdef void *ufunc_erf_ptr[8]
+cdef void *ufunc_erf_data[4]
+cdef char ufunc_erf_types[8]
+cdef char *ufunc_erf_doc = (
+    "erf(z, out=None)\n"
+    "\n"
+    "Returns the error function of complex argument.\n"
+    "\n"
+    "It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : ndarray\n"
+    "    Input array.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The values of the error function at the given points `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erfc, erfinv, erfcinv, wofz, erfcx, erfi\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The cumulative of the unit normal distribution is given by\n"
+    "``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Error_function\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover,\n"
+    "    1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm\n"
+    ".. [3] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erf(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erf(x)$')\n"
+    ">>> plt.show()")
+ufunc_erf_loops[0] = loop_d_d__As_f_f
+ufunc_erf_loops[1] = loop_d_d__As_d_d
+ufunc_erf_loops[2] = loop_D_D__As_F_F
+ufunc_erf_loops[3] = loop_D_D__As_D_D
+ufunc_erf_types[0] = NPY_FLOAT
+ufunc_erf_types[1] = NPY_FLOAT
+ufunc_erf_types[2] = NPY_DOUBLE
+ufunc_erf_types[3] = NPY_DOUBLE
+ufunc_erf_types[4] = NPY_CFLOAT
+ufunc_erf_types[5] = NPY_CFLOAT
+ufunc_erf_types[6] = NPY_CDOUBLE
+ufunc_erf_types[7] = NPY_CDOUBLE
+ufunc_erf_ptr[2*0] = _func_cephes_erf
+ufunc_erf_ptr[2*0+1] = ("erf")
+ufunc_erf_ptr[2*1] = _func_cephes_erf
+ufunc_erf_ptr[2*1+1] = ("erf")
+ufunc_erf_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erf
+ufunc_erf_ptr[2*2+1] = ("erf")
+ufunc_erf_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erf
+ufunc_erf_ptr[2*3+1] = ("erf")
+ufunc_erf_data[0] = &ufunc_erf_ptr[2*0]
+ufunc_erf_data[1] = &ufunc_erf_ptr[2*1]
+ufunc_erf_data[2] = &ufunc_erf_ptr[2*2]
+ufunc_erf_data[3] = &ufunc_erf_ptr[2*3]
+erf = np.PyUFunc_FromFuncAndData(ufunc_erf_loops, ufunc_erf_data, ufunc_erf_types, 4, 1, 1, 0, "erf", ufunc_erf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfc_loops[4]
+cdef void *ufunc_erfc_ptr[8]
+cdef void *ufunc_erfc_data[4]
+cdef char ufunc_erfc_types[8]
+cdef char *ufunc_erfc_doc = (
+    "erfc(x, out=None)\n"
+    "\n"
+    "Complementary error function, ``1 - erf(x)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the complementary error function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfi, erfcx, dawsn, wofz\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfc(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfc(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfc_loops[0] = loop_d_d__As_f_f
+ufunc_erfc_loops[1] = loop_d_d__As_d_d
+ufunc_erfc_loops[2] = loop_D_D__As_F_F
+ufunc_erfc_loops[3] = loop_D_D__As_D_D
+ufunc_erfc_types[0] = NPY_FLOAT
+ufunc_erfc_types[1] = NPY_FLOAT
+ufunc_erfc_types[2] = NPY_DOUBLE
+ufunc_erfc_types[3] = NPY_DOUBLE
+ufunc_erfc_types[4] = NPY_CFLOAT
+ufunc_erfc_types[5] = NPY_CFLOAT
+ufunc_erfc_types[6] = NPY_CDOUBLE
+ufunc_erfc_types[7] = NPY_CDOUBLE
+ufunc_erfc_ptr[2*0] = _func_cephes_erfc
+ufunc_erfc_ptr[2*0+1] = ("erfc")
+ufunc_erfc_ptr[2*1] = _func_cephes_erfc
+ufunc_erfc_ptr[2*1+1] = ("erfc")
+ufunc_erfc_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex
+ufunc_erfc_ptr[2*2+1] = ("erfc")
+ufunc_erfc_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex
+ufunc_erfc_ptr[2*3+1] = ("erfc")
+ufunc_erfc_data[0] = &ufunc_erfc_ptr[2*0]
+ufunc_erfc_data[1] = &ufunc_erfc_ptr[2*1]
+ufunc_erfc_data[2] = &ufunc_erfc_ptr[2*2]
+ufunc_erfc_data[3] = &ufunc_erfc_ptr[2*3]
+erfc = np.PyUFunc_FromFuncAndData(ufunc_erfc_loops, ufunc_erfc_data, ufunc_erfc_types, 4, 1, 1, 0, "erfc", ufunc_erfc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfcinv_loops[2]
+cdef void *ufunc_erfcinv_ptr[4]
+cdef void *ufunc_erfcinv_data[2]
+cdef char ufunc_erfcinv_types[4]
+cdef char *ufunc_erfcinv_doc = (
+    "erfcinv(y, out=None)\n"
+    "\n"
+    "Inverse of the complementary error function.\n"
+    "\n"
+    "Computes the inverse of the complementary error function.\n"
+    "\n"
+    "In the complex domain, there is no unique complex number w satisfying\n"
+    "erfc(w)=z. This indicates a true inverse function would be multivalued.\n"
+    "When the domain restricts to the real, 0 < x < 2, there is a unique real\n"
+    "number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).\n"
+    "\n"
+    "It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : ndarray\n"
+    "    Argument at which to evaluate. Domain: [0, 2]\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "erfcinv : scalar or ndarray\n"
+    "    The inverse of erfc of y, element-wise\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf : Error function of a complex argument\n"
+    "erfc : Complementary error function, ``1 - erf(x)``\n"
+    "erfinv : Inverse of the error function\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import erfcinv\n"
+    "\n"
+    ">>> erfcinv(0.5)\n"
+    "0.4769362762044699\n"
+    "\n"
+    ">>> y = np.linspace(0.0, 2.0, num=11)\n"
+    ">>> erfcinv(y)\n"
+    "array([        inf,  0.9061938 ,  0.59511608,  0.37080716,  0.17914345,\n"
+    "       -0.        , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,\n"
+    "              -inf])\n"
+    "\n"
+    "Plot the function:\n"
+    "\n"
+    ">>> y = np.linspace(0, 2, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(y, erfcinv(y))\n"
+    ">>> ax.grid(True)\n"
+    ">>> ax.set_xlabel('y')\n"
+    ">>> ax.set_title('erfcinv(y)')\n"
+    ">>> plt.show()")
+ufunc_erfcinv_loops[0] = loop_d_d__As_f_f
+ufunc_erfcinv_loops[1] = loop_d_d__As_d_d
+ufunc_erfcinv_types[0] = NPY_FLOAT
+ufunc_erfcinv_types[1] = NPY_FLOAT
+ufunc_erfcinv_types[2] = NPY_DOUBLE
+ufunc_erfcinv_types[3] = NPY_DOUBLE
+ufunc_erfcinv_ptr[2*0] = _func_cephes_erfcinv
+ufunc_erfcinv_ptr[2*0+1] = ("erfcinv")
+ufunc_erfcinv_ptr[2*1] = _func_cephes_erfcinv
+ufunc_erfcinv_ptr[2*1+1] = ("erfcinv")
+ufunc_erfcinv_data[0] = &ufunc_erfcinv_ptr[2*0]
+ufunc_erfcinv_data[1] = &ufunc_erfcinv_ptr[2*1]
+erfcinv = np.PyUFunc_FromFuncAndData(ufunc_erfcinv_loops, ufunc_erfcinv_data, ufunc_erfcinv_types, 2, 1, 1, 0, "erfcinv", ufunc_erfcinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfcx_loops[4]
+cdef void *ufunc_erfcx_ptr[8]
+cdef void *ufunc_erfcx_data[4]
+cdef char ufunc_erfcx_types[8]
+cdef char *ufunc_erfcx_doc = (
+    "erfcx(x, out=None)\n"
+    "\n"
+    "Scaled complementary error function, ``exp(x**2) * erfc(x)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the scaled complementary error function\n"
+    "\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfc, erfi, dawsn, wofz\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.12.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfcx(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfcx(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfcx_loops[0] = loop_d_d__As_f_f
+ufunc_erfcx_loops[1] = loop_d_d__As_d_d
+ufunc_erfcx_loops[2] = loop_D_D__As_F_F
+ufunc_erfcx_loops[3] = loop_D_D__As_D_D
+ufunc_erfcx_types[0] = NPY_FLOAT
+ufunc_erfcx_types[1] = NPY_FLOAT
+ufunc_erfcx_types[2] = NPY_DOUBLE
+ufunc_erfcx_types[3] = NPY_DOUBLE
+ufunc_erfcx_types[4] = NPY_CFLOAT
+ufunc_erfcx_types[5] = NPY_CFLOAT
+ufunc_erfcx_types[6] = NPY_CDOUBLE
+ufunc_erfcx_types[7] = NPY_CDOUBLE
+ufunc_erfcx_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx
+ufunc_erfcx_ptr[2*0+1] = ("erfcx")
+ufunc_erfcx_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx
+ufunc_erfcx_ptr[2*1+1] = ("erfcx")
+ufunc_erfcx_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex
+ufunc_erfcx_ptr[2*2+1] = ("erfcx")
+ufunc_erfcx_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex
+ufunc_erfcx_ptr[2*3+1] = ("erfcx")
+ufunc_erfcx_data[0] = &ufunc_erfcx_ptr[2*0]
+ufunc_erfcx_data[1] = &ufunc_erfcx_ptr[2*1]
+ufunc_erfcx_data[2] = &ufunc_erfcx_ptr[2*2]
+ufunc_erfcx_data[3] = &ufunc_erfcx_ptr[2*3]
+erfcx = np.PyUFunc_FromFuncAndData(ufunc_erfcx_loops, ufunc_erfcx_data, ufunc_erfcx_types, 4, 1, 1, 0, "erfcx", ufunc_erfcx_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfi_loops[4]
+cdef void *ufunc_erfi_ptr[8]
+cdef void *ufunc_erfi_data[4]
+cdef char ufunc_erfi_types[8]
+cdef char *ufunc_erfi_doc = (
+    "erfi(z, out=None)\n"
+    "\n"
+    "Imaginary error function, ``-i erf(i z)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the imaginary error function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfc, erfcx, dawsn, wofz\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.12.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfi(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfi(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfi_loops[0] = loop_d_d__As_f_f
+ufunc_erfi_loops[1] = loop_d_d__As_d_d
+ufunc_erfi_loops[2] = loop_D_D__As_F_F
+ufunc_erfi_loops[3] = loop_D_D__As_D_D
+ufunc_erfi_types[0] = NPY_FLOAT
+ufunc_erfi_types[1] = NPY_FLOAT
+ufunc_erfi_types[2] = NPY_DOUBLE
+ufunc_erfi_types[3] = NPY_DOUBLE
+ufunc_erfi_types[4] = NPY_CFLOAT
+ufunc_erfi_types[5] = NPY_CFLOAT
+ufunc_erfi_types[6] = NPY_CDOUBLE
+ufunc_erfi_types[7] = NPY_CDOUBLE
+ufunc_erfi_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfi
+ufunc_erfi_ptr[2*0+1] = ("erfi")
+ufunc_erfi_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfi
+ufunc_erfi_ptr[2*1+1] = ("erfi")
+ufunc_erfi_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex
+ufunc_erfi_ptr[2*2+1] = ("erfi")
+ufunc_erfi_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex
+ufunc_erfi_ptr[2*3+1] = ("erfi")
+ufunc_erfi_data[0] = &ufunc_erfi_ptr[2*0]
+ufunc_erfi_data[1] = &ufunc_erfi_ptr[2*1]
+ufunc_erfi_data[2] = &ufunc_erfi_ptr[2*2]
+ufunc_erfi_data[3] = &ufunc_erfi_ptr[2*3]
+erfi = np.PyUFunc_FromFuncAndData(ufunc_erfi_loops, ufunc_erfi_data, ufunc_erfi_types, 4, 1, 1, 0, "erfi", ufunc_erfi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfinv_loops[2]
+cdef void *ufunc_erfinv_ptr[4]
+cdef void *ufunc_erfinv_data[2]
+cdef char ufunc_erfinv_types[4]
+cdef char *ufunc_erfinv_doc = (
+    "erfinv(y, out=None)\n"
+    "\n"
+    "Inverse of the error function.\n"
+    "\n"
+    "Computes the inverse of the error function.\n"
+    "\n"
+    "In the complex domain, there is no unique complex number w satisfying\n"
+    "erf(w)=z. This indicates a true inverse function would be multivalued.\n"
+    "When the domain restricts to the real, -1 < x < 1, there is a unique real\n"
+    "number satisfying erf(erfinv(x)) = x.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : ndarray\n"
+    "    Argument at which to evaluate. Domain: [-1, 1]\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "erfinv : scalar or ndarray\n"
+    "    The inverse of erf of y, element-wise\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf : Error function of a complex argument\n"
+    "erfc : Complementary error function, ``1 - erf(x)``\n"
+    "erfcinv : Inverse of the complementary error function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function wraps the ``erf_inv`` routine from the\n"
+    "Boost Math C++ library [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import erfinv, erf\n"
+    "\n"
+    ">>> erfinv(0.5)\n"
+    "0.4769362762044699\n"
+    "\n"
+    ">>> y = np.linspace(-1.0, 1.0, num=9)\n"
+    ">>> x = erfinv(y)\n"
+    ">>> x\n"
+    "array([       -inf, -0.81341985, -0.47693628, -0.22531206,  0.        ,\n"
+    "        0.22531206,  0.47693628,  0.81341985,         inf])\n"
+    "\n"
+    "Verify that ``erf(erfinv(y))`` is ``y``.\n"
+    "\n"
+    ">>> erf(x)\n"
+    "array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])\n"
+    "\n"
+    "Plot the function:\n"
+    "\n"
+    ">>> y = np.linspace(-1, 1, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(y, erfinv(y))\n"
+    ">>> ax.grid(True)\n"
+    ">>> ax.set_xlabel('y')\n"
+    ">>> ax.set_title('erfinv(y)')\n"
+    ">>> plt.show()")
+ufunc_erfinv_loops[0] = loop_f_f__As_f_f
+ufunc_erfinv_loops[1] = loop_d_d__As_d_d
+ufunc_erfinv_types[0] = NPY_FLOAT
+ufunc_erfinv_types[1] = NPY_FLOAT
+ufunc_erfinv_types[2] = NPY_DOUBLE
+ufunc_erfinv_types[3] = NPY_DOUBLE
+ufunc_erfinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_erfinv_float
+ufunc_erfinv_ptr[2*0+1] = ("erfinv")
+ufunc_erfinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_erfinv_double
+ufunc_erfinv_ptr[2*1+1] = ("erfinv")
+ufunc_erfinv_data[0] = &ufunc_erfinv_ptr[2*0]
+ufunc_erfinv_data[1] = &ufunc_erfinv_ptr[2*1]
+erfinv = np.PyUFunc_FromFuncAndData(ufunc_erfinv_loops, ufunc_erfinv_data, ufunc_erfinv_types, 2, 1, 1, 0, "erfinv", ufunc_erfinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyc_loops[5]
+cdef void *ufunc_eval_chebyc_ptr[10]
+cdef void *ufunc_eval_chebyc_data[5]
+cdef char ufunc_eval_chebyc_types[15]
+cdef char *ufunc_eval_chebyc_doc = (
+    "eval_chebyc(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    C_n(x) = 2 T_n(x/2)\n"
+    "\n"
+    "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.11 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyt`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "C : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyc : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the first kind on [-2, 2]\n"
+    "chebyc : Chebyshev polynomial object\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "eval_chebyt : evaluate Chebycshev polynomials of the first kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "They are a scaled version of the Chebyshev polynomials of the\n"
+    "first kind.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 6)\n"
+    ">>> sc.eval_chebyc(3, x)\n"
+    "array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])\n"
+    ">>> 2 * sc.eval_chebyt(3, x / 2)\n"
+    "array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])")
+ufunc_eval_chebyc_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyc_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyc_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyc_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyc_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyc_types[0] = NPY_INTP
+ufunc_eval_chebyc_types[1] = NPY_DOUBLE
+ufunc_eval_chebyc_types[2] = NPY_DOUBLE
+ufunc_eval_chebyc_types[3] = NPY_FLOAT
+ufunc_eval_chebyc_types[4] = NPY_FLOAT
+ufunc_eval_chebyc_types[5] = NPY_FLOAT
+ufunc_eval_chebyc_types[6] = NPY_FLOAT
+ufunc_eval_chebyc_types[7] = NPY_CFLOAT
+ufunc_eval_chebyc_types[8] = NPY_CFLOAT
+ufunc_eval_chebyc_types[9] = NPY_DOUBLE
+ufunc_eval_chebyc_types[10] = NPY_DOUBLE
+ufunc_eval_chebyc_types[11] = NPY_DOUBLE
+ufunc_eval_chebyc_types[12] = NPY_DOUBLE
+ufunc_eval_chebyc_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyc_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyc_ptr[2*0] = _func_eval_chebyc_l
+ufunc_eval_chebyc_ptr[2*0+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*1] = _func_eval_chebyc[double]
+ufunc_eval_chebyc_ptr[2*1+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*2] = _func_eval_chebyc[double_complex]
+ufunc_eval_chebyc_ptr[2*2+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*3] = _func_eval_chebyc[double]
+ufunc_eval_chebyc_ptr[2*3+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*4] = _func_eval_chebyc[double_complex]
+ufunc_eval_chebyc_ptr[2*4+1] = ("eval_chebyc")
+ufunc_eval_chebyc_data[0] = &ufunc_eval_chebyc_ptr[2*0]
+ufunc_eval_chebyc_data[1] = &ufunc_eval_chebyc_ptr[2*1]
+ufunc_eval_chebyc_data[2] = &ufunc_eval_chebyc_ptr[2*2]
+ufunc_eval_chebyc_data[3] = &ufunc_eval_chebyc_ptr[2*3]
+ufunc_eval_chebyc_data[4] = &ufunc_eval_chebyc_ptr[2*4]
+eval_chebyc = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyc_loops, ufunc_eval_chebyc_data, ufunc_eval_chebyc_types, 5, 2, 1, 0, "eval_chebyc", ufunc_eval_chebyc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebys_loops[5]
+cdef void *ufunc_eval_chebys_ptr[10]
+cdef void *ufunc_eval_chebys_data[5]
+cdef char ufunc_eval_chebys_types[15]
+cdef char *ufunc_eval_chebys_doc = (
+    "eval_chebys(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    S_n(x) = U_n(x/2)\n"
+    "\n"
+    "where :math:`U_n` is a Chebyshev polynomial of the second\n"
+    "kind. See 22.5.13 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyu`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "S : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebys : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the second kind on [-2, 2]\n"
+    "chebys : Chebyshev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "They are a scaled version of the Chebyshev polynomials of the\n"
+    "second kind.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 6)\n"
+    ">>> sc.eval_chebys(3, x)\n"
+    "array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])\n"
+    ">>> sc.eval_chebyu(3, x / 2)\n"
+    "array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])")
+ufunc_eval_chebys_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebys_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebys_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebys_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebys_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebys_types[0] = NPY_INTP
+ufunc_eval_chebys_types[1] = NPY_DOUBLE
+ufunc_eval_chebys_types[2] = NPY_DOUBLE
+ufunc_eval_chebys_types[3] = NPY_FLOAT
+ufunc_eval_chebys_types[4] = NPY_FLOAT
+ufunc_eval_chebys_types[5] = NPY_FLOAT
+ufunc_eval_chebys_types[6] = NPY_FLOAT
+ufunc_eval_chebys_types[7] = NPY_CFLOAT
+ufunc_eval_chebys_types[8] = NPY_CFLOAT
+ufunc_eval_chebys_types[9] = NPY_DOUBLE
+ufunc_eval_chebys_types[10] = NPY_DOUBLE
+ufunc_eval_chebys_types[11] = NPY_DOUBLE
+ufunc_eval_chebys_types[12] = NPY_DOUBLE
+ufunc_eval_chebys_types[13] = NPY_CDOUBLE
+ufunc_eval_chebys_types[14] = NPY_CDOUBLE
+ufunc_eval_chebys_ptr[2*0] = _func_eval_chebys_l
+ufunc_eval_chebys_ptr[2*0+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*1] = _func_eval_chebys[double]
+ufunc_eval_chebys_ptr[2*1+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*2] = _func_eval_chebys[double_complex]
+ufunc_eval_chebys_ptr[2*2+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*3] = _func_eval_chebys[double]
+ufunc_eval_chebys_ptr[2*3+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*4] = _func_eval_chebys[double_complex]
+ufunc_eval_chebys_ptr[2*4+1] = ("eval_chebys")
+ufunc_eval_chebys_data[0] = &ufunc_eval_chebys_ptr[2*0]
+ufunc_eval_chebys_data[1] = &ufunc_eval_chebys_ptr[2*1]
+ufunc_eval_chebys_data[2] = &ufunc_eval_chebys_ptr[2*2]
+ufunc_eval_chebys_data[3] = &ufunc_eval_chebys_ptr[2*3]
+ufunc_eval_chebys_data[4] = &ufunc_eval_chebys_ptr[2*4]
+eval_chebys = np.PyUFunc_FromFuncAndData(ufunc_eval_chebys_loops, ufunc_eval_chebys_data, ufunc_eval_chebys_types, 5, 2, 1, 0, "eval_chebys", ufunc_eval_chebys_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyt_loops[5]
+cdef void *ufunc_eval_chebyt_ptr[10]
+cdef void *ufunc_eval_chebyt_data[5]
+cdef char ufunc_eval_chebyt_types[15]
+cdef char *ufunc_eval_chebyt_doc = (
+    "eval_chebyt(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the first kind at a point.\n"
+    "\n"
+    "The Chebyshev polynomials of the first kind can be defined via the\n"
+    "Gauss hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.47 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "T : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyt : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the first kind\n"
+    "chebyu : Chebychev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This routine is numerically stable for `x` in ``[-1, 1]`` at least\n"
+    "up to order ``10000``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_chebyt_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyt_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyt_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyt_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyt_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyt_types[0] = NPY_INTP
+ufunc_eval_chebyt_types[1] = NPY_DOUBLE
+ufunc_eval_chebyt_types[2] = NPY_DOUBLE
+ufunc_eval_chebyt_types[3] = NPY_FLOAT
+ufunc_eval_chebyt_types[4] = NPY_FLOAT
+ufunc_eval_chebyt_types[5] = NPY_FLOAT
+ufunc_eval_chebyt_types[6] = NPY_FLOAT
+ufunc_eval_chebyt_types[7] = NPY_CFLOAT
+ufunc_eval_chebyt_types[8] = NPY_CFLOAT
+ufunc_eval_chebyt_types[9] = NPY_DOUBLE
+ufunc_eval_chebyt_types[10] = NPY_DOUBLE
+ufunc_eval_chebyt_types[11] = NPY_DOUBLE
+ufunc_eval_chebyt_types[12] = NPY_DOUBLE
+ufunc_eval_chebyt_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyt_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyt_ptr[2*0] = _func_eval_chebyt_l
+ufunc_eval_chebyt_ptr[2*0+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*1] = _func_eval_chebyt[double]
+ufunc_eval_chebyt_ptr[2*1+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*2] = _func_eval_chebyt[double_complex]
+ufunc_eval_chebyt_ptr[2*2+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*3] = _func_eval_chebyt[double]
+ufunc_eval_chebyt_ptr[2*3+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*4] = _func_eval_chebyt[double_complex]
+ufunc_eval_chebyt_ptr[2*4+1] = ("eval_chebyt")
+ufunc_eval_chebyt_data[0] = &ufunc_eval_chebyt_ptr[2*0]
+ufunc_eval_chebyt_data[1] = &ufunc_eval_chebyt_ptr[2*1]
+ufunc_eval_chebyt_data[2] = &ufunc_eval_chebyt_ptr[2*2]
+ufunc_eval_chebyt_data[3] = &ufunc_eval_chebyt_ptr[2*3]
+ufunc_eval_chebyt_data[4] = &ufunc_eval_chebyt_ptr[2*4]
+eval_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyt_loops, ufunc_eval_chebyt_data, ufunc_eval_chebyt_types, 5, 2, 1, 0, "eval_chebyt", ufunc_eval_chebyt_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyu_loops[5]
+cdef void *ufunc_eval_chebyu_ptr[10]
+cdef void *ufunc_eval_chebyu_data[5]
+cdef char ufunc_eval_chebyu_types[15]
+cdef char *ufunc_eval_chebyu_doc = (
+    "eval_chebyu(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the second kind at a point.\n"
+    "\n"
+    "The Chebyshev polynomials of the second kind can be defined via\n"
+    "the Gauss hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.48 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "U : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyu : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the second kind\n"
+    "chebyu : Chebyshev polynomial object\n"
+    "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_chebyu_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyu_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyu_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyu_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyu_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyu_types[0] = NPY_INTP
+ufunc_eval_chebyu_types[1] = NPY_DOUBLE
+ufunc_eval_chebyu_types[2] = NPY_DOUBLE
+ufunc_eval_chebyu_types[3] = NPY_FLOAT
+ufunc_eval_chebyu_types[4] = NPY_FLOAT
+ufunc_eval_chebyu_types[5] = NPY_FLOAT
+ufunc_eval_chebyu_types[6] = NPY_FLOAT
+ufunc_eval_chebyu_types[7] = NPY_CFLOAT
+ufunc_eval_chebyu_types[8] = NPY_CFLOAT
+ufunc_eval_chebyu_types[9] = NPY_DOUBLE
+ufunc_eval_chebyu_types[10] = NPY_DOUBLE
+ufunc_eval_chebyu_types[11] = NPY_DOUBLE
+ufunc_eval_chebyu_types[12] = NPY_DOUBLE
+ufunc_eval_chebyu_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyu_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyu_ptr[2*0] = _func_eval_chebyu_l
+ufunc_eval_chebyu_ptr[2*0+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*1] = _func_eval_chebyu[double]
+ufunc_eval_chebyu_ptr[2*1+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*2] = _func_eval_chebyu[double_complex]
+ufunc_eval_chebyu_ptr[2*2+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*3] = _func_eval_chebyu[double]
+ufunc_eval_chebyu_ptr[2*3+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*4] = _func_eval_chebyu[double_complex]
+ufunc_eval_chebyu_ptr[2*4+1] = ("eval_chebyu")
+ufunc_eval_chebyu_data[0] = &ufunc_eval_chebyu_ptr[2*0]
+ufunc_eval_chebyu_data[1] = &ufunc_eval_chebyu_ptr[2*1]
+ufunc_eval_chebyu_data[2] = &ufunc_eval_chebyu_ptr[2*2]
+ufunc_eval_chebyu_data[3] = &ufunc_eval_chebyu_ptr[2*3]
+ufunc_eval_chebyu_data[4] = &ufunc_eval_chebyu_ptr[2*4]
+eval_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyu_loops, ufunc_eval_chebyu_data, ufunc_eval_chebyu_types, 5, 2, 1, 0, "eval_chebyu", ufunc_eval_chebyu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_gegenbauer_loops[5]
+cdef void *ufunc_eval_gegenbauer_ptr[10]
+cdef void *ufunc_eval_gegenbauer_data[5]
+cdef char ufunc_eval_gegenbauer_types[20]
+cdef char *ufunc_eval_gegenbauer_doc = (
+    "eval_gegenbauer(n, alpha, x, out=None)\n"
+    "\n"
+    "Evaluate Gegenbauer polynomial at a point.\n"
+    "\n"
+    "The Gegenbauer polynomials can be defined via the Gauss\n"
+    "hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    C_n^{(\\alpha)} = \\frac{(2\\alpha)_n}{\\Gamma(n + 1)}\n"
+    "      {}_2F_1(-n, 2\\alpha + n; \\alpha + 1/2; (1 - z)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.46 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Gegenbauer polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "C : scalar or ndarray\n"
+    "    Values of the Gegenbauer polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_gegenbauer : roots and quadrature weights of Gegenbauer\n"
+    "                   polynomials\n"
+    "gegenbauer : Gegenbauer polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_gegenbauer_loops[0] = loop_d_pdd__As_pdd_d
+ufunc_eval_gegenbauer_loops[1] = loop_d_ddd__As_fff_f
+ufunc_eval_gegenbauer_loops[2] = loop_D_ddD__As_ffF_F
+ufunc_eval_gegenbauer_loops[3] = loop_d_ddd__As_ddd_d
+ufunc_eval_gegenbauer_loops[4] = loop_D_ddD__As_ddD_D
+ufunc_eval_gegenbauer_types[0] = NPY_INTP
+ufunc_eval_gegenbauer_types[1] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[2] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[3] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[4] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[5] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[6] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[7] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[8] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[9] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[10] = NPY_CFLOAT
+ufunc_eval_gegenbauer_types[11] = NPY_CFLOAT
+ufunc_eval_gegenbauer_types[12] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[13] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[14] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[15] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[16] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[17] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[18] = NPY_CDOUBLE
+ufunc_eval_gegenbauer_types[19] = NPY_CDOUBLE
+ufunc_eval_gegenbauer_ptr[2*0] = _func_eval_gegenbauer_l
+ufunc_eval_gegenbauer_ptr[2*0+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*1] = _func_eval_gegenbauer[double]
+ufunc_eval_gegenbauer_ptr[2*1+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*2] = _func_eval_gegenbauer[double_complex]
+ufunc_eval_gegenbauer_ptr[2*2+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*3] = _func_eval_gegenbauer[double]
+ufunc_eval_gegenbauer_ptr[2*3+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*4] = _func_eval_gegenbauer[double_complex]
+ufunc_eval_gegenbauer_ptr[2*4+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_data[0] = &ufunc_eval_gegenbauer_ptr[2*0]
+ufunc_eval_gegenbauer_data[1] = &ufunc_eval_gegenbauer_ptr[2*1]
+ufunc_eval_gegenbauer_data[2] = &ufunc_eval_gegenbauer_ptr[2*2]
+ufunc_eval_gegenbauer_data[3] = &ufunc_eval_gegenbauer_ptr[2*3]
+ufunc_eval_gegenbauer_data[4] = &ufunc_eval_gegenbauer_ptr[2*4]
+eval_gegenbauer = np.PyUFunc_FromFuncAndData(ufunc_eval_gegenbauer_loops, ufunc_eval_gegenbauer_data, ufunc_eval_gegenbauer_types, 5, 3, 1, 0, "eval_gegenbauer", ufunc_eval_gegenbauer_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_genlaguerre_loops[5]
+cdef void *ufunc_eval_genlaguerre_ptr[10]
+cdef void *ufunc_eval_genlaguerre_data[5]
+cdef char ufunc_eval_genlaguerre_types[20]
+cdef char *ufunc_eval_genlaguerre_doc = (
+    "eval_genlaguerre(n, alpha, x, out=None)\n"
+    "\n"
+    "Evaluate generalized Laguerre polynomial at a point.\n"
+    "\n"
+    "The generalized Laguerre polynomials can be defined via the\n"
+    "confluent hypergeometric function :math:`{}_1F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    L_n^{(\\alpha)}(x) = \\binom{n + \\alpha}{n}\n"
+    "      {}_1F_1(-n, \\alpha + 1, x).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre\n"
+    "polynomials are the special case where :math:`\\alpha = 0`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the confluent hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter; must have ``alpha > -1``\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the generalized Laguerre\n"
+    "    polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "L : scalar or ndarray\n"
+    "    Values of the generalized Laguerre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_genlaguerre : roots and quadrature weights of generalized\n"
+    "                    Laguerre polynomials\n"
+    "genlaguerre : generalized Laguerre polynomial object\n"
+    "hyp1f1 : confluent hypergeometric function\n"
+    "eval_laguerre : evaluate Laguerre polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_genlaguerre_loops[0] = loop_d_pdd__As_pdd_d
+ufunc_eval_genlaguerre_loops[1] = loop_d_ddd__As_fff_f
+ufunc_eval_genlaguerre_loops[2] = loop_D_ddD__As_ffF_F
+ufunc_eval_genlaguerre_loops[3] = loop_d_ddd__As_ddd_d
+ufunc_eval_genlaguerre_loops[4] = loop_D_ddD__As_ddD_D
+ufunc_eval_genlaguerre_types[0] = NPY_INTP
+ufunc_eval_genlaguerre_types[1] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[2] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[3] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[4] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[5] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[6] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[7] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[8] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[9] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[10] = NPY_CFLOAT
+ufunc_eval_genlaguerre_types[11] = NPY_CFLOAT
+ufunc_eval_genlaguerre_types[12] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[13] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[14] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[15] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[16] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[17] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[18] = NPY_CDOUBLE
+ufunc_eval_genlaguerre_types[19] = NPY_CDOUBLE
+ufunc_eval_genlaguerre_ptr[2*0] = _func_eval_genlaguerre_l
+ufunc_eval_genlaguerre_ptr[2*0+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*1] = _func_eval_genlaguerre[double]
+ufunc_eval_genlaguerre_ptr[2*1+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*2] = _func_eval_genlaguerre[double_complex]
+ufunc_eval_genlaguerre_ptr[2*2+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*3] = _func_eval_genlaguerre[double]
+ufunc_eval_genlaguerre_ptr[2*3+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*4] = _func_eval_genlaguerre[double_complex]
+ufunc_eval_genlaguerre_ptr[2*4+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_data[0] = &ufunc_eval_genlaguerre_ptr[2*0]
+ufunc_eval_genlaguerre_data[1] = &ufunc_eval_genlaguerre_ptr[2*1]
+ufunc_eval_genlaguerre_data[2] = &ufunc_eval_genlaguerre_ptr[2*2]
+ufunc_eval_genlaguerre_data[3] = &ufunc_eval_genlaguerre_ptr[2*3]
+ufunc_eval_genlaguerre_data[4] = &ufunc_eval_genlaguerre_ptr[2*4]
+eval_genlaguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_genlaguerre_loops, ufunc_eval_genlaguerre_data, ufunc_eval_genlaguerre_types, 5, 3, 1, 0, "eval_genlaguerre", ufunc_eval_genlaguerre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_hermite_loops[1]
+cdef void *ufunc_eval_hermite_ptr[2]
+cdef void *ufunc_eval_hermite_data[1]
+cdef char ufunc_eval_hermite_types[3]
+cdef char *ufunc_eval_hermite_doc = (
+    "eval_hermite(n, x, out=None)\n"
+    "\n"
+    "Evaluate physicist's Hermite polynomial at a point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    H_n(x) = (-1)^n e^{x^2} \\frac{d^n}{dx^n} e^{-x^2};\n"
+    "\n"
+    ":math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in\n"
+    "[AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Hermite polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "H : scalar or ndarray\n"
+    "    Values of the Hermite polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_hermite : roots and quadrature weights of physicist's\n"
+    "                Hermite polynomials\n"
+    "hermite : physicist's Hermite polynomial object\n"
+    "numpy.polynomial.hermite.Hermite : Physicist's Hermite series\n"
+    "eval_hermitenorm : evaluate Probabilist's Hermite polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_hermite_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_hermite_types[0] = NPY_INTP
+ufunc_eval_hermite_types[1] = NPY_DOUBLE
+ufunc_eval_hermite_types[2] = NPY_DOUBLE
+ufunc_eval_hermite_ptr[2*0] = _func_eval_hermite
+ufunc_eval_hermite_ptr[2*0+1] = ("eval_hermite")
+ufunc_eval_hermite_data[0] = &ufunc_eval_hermite_ptr[2*0]
+eval_hermite = np.PyUFunc_FromFuncAndData(ufunc_eval_hermite_loops, ufunc_eval_hermite_data, ufunc_eval_hermite_types, 1, 2, 1, 0, "eval_hermite", ufunc_eval_hermite_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_hermitenorm_loops[1]
+cdef void *ufunc_eval_hermitenorm_ptr[2]
+cdef void *ufunc_eval_hermitenorm_data[1]
+cdef char ufunc_eval_hermitenorm_types[3]
+cdef char *ufunc_eval_hermitenorm_doc = (
+    "eval_hermitenorm(n, x, out=None)\n"
+    "\n"
+    "Evaluate probabilist's (normalized) Hermite polynomial at a\n"
+    "point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    He_n(x) = (-1)^n e^{x^2/2} \\frac{d^n}{dx^n} e^{-x^2/2};\n"
+    "\n"
+    ":math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in\n"
+    "[AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Hermite polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "He : scalar or ndarray\n"
+    "    Values of the Hermite polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_hermitenorm : roots and quadrature weights of probabilist's\n"
+    "                    Hermite polynomials\n"
+    "hermitenorm : probabilist's Hermite polynomial object\n"
+    "numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series\n"
+    "eval_hermite : evaluate physicist's Hermite polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_hermitenorm_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_hermitenorm_types[0] = NPY_INTP
+ufunc_eval_hermitenorm_types[1] = NPY_DOUBLE
+ufunc_eval_hermitenorm_types[2] = NPY_DOUBLE
+ufunc_eval_hermitenorm_ptr[2*0] = _func_eval_hermitenorm
+ufunc_eval_hermitenorm_ptr[2*0+1] = ("eval_hermitenorm")
+ufunc_eval_hermitenorm_data[0] = &ufunc_eval_hermitenorm_ptr[2*0]
+eval_hermitenorm = np.PyUFunc_FromFuncAndData(ufunc_eval_hermitenorm_loops, ufunc_eval_hermitenorm_data, ufunc_eval_hermitenorm_types, 1, 2, 1, 0, "eval_hermitenorm", ufunc_eval_hermitenorm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_jacobi_loops[5]
+cdef void *ufunc_eval_jacobi_ptr[10]
+cdef void *ufunc_eval_jacobi_data[5]
+cdef char ufunc_eval_jacobi_types[25]
+cdef char *ufunc_eval_jacobi_doc = (
+    "eval_jacobi(n, alpha, beta, x, out=None)\n"
+    "\n"
+    "Evaluate Jacobi polynomial at a point.\n"
+    "\n"
+    "The Jacobi polynomials can be defined via the Gauss hypergeometric\n"
+    "function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n^{(\\alpha, \\beta)}(x) = \\frac{(\\alpha + 1)_n}{\\Gamma(n + 1)}\n"
+    "      {}_2F_1(-n, 1 + \\alpha + \\beta + n; \\alpha + 1; (1 - z)/2)\n"
+    "\n"
+    "where :math:`(\\cdot)_n` is the Pochhammer symbol; see `poch`. When\n"
+    ":math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.42 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter\n"
+    "beta : array_like\n"
+    "    Parameter\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the Jacobi polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_jacobi : roots and quadrature weights of Jacobi polynomials\n"
+    "jacobi : Jacobi polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_jacobi_loops[0] = loop_d_pddd__As_pddd_d
+ufunc_eval_jacobi_loops[1] = loop_d_dddd__As_ffff_f
+ufunc_eval_jacobi_loops[2] = loop_D_dddD__As_fffF_F
+ufunc_eval_jacobi_loops[3] = loop_d_dddd__As_dddd_d
+ufunc_eval_jacobi_loops[4] = loop_D_dddD__As_dddD_D
+ufunc_eval_jacobi_types[0] = NPY_INTP
+ufunc_eval_jacobi_types[1] = NPY_DOUBLE
+ufunc_eval_jacobi_types[2] = NPY_DOUBLE
+ufunc_eval_jacobi_types[3] = NPY_DOUBLE
+ufunc_eval_jacobi_types[4] = NPY_DOUBLE
+ufunc_eval_jacobi_types[5] = NPY_FLOAT
+ufunc_eval_jacobi_types[6] = NPY_FLOAT
+ufunc_eval_jacobi_types[7] = NPY_FLOAT
+ufunc_eval_jacobi_types[8] = NPY_FLOAT
+ufunc_eval_jacobi_types[9] = NPY_FLOAT
+ufunc_eval_jacobi_types[10] = NPY_FLOAT
+ufunc_eval_jacobi_types[11] = NPY_FLOAT
+ufunc_eval_jacobi_types[12] = NPY_FLOAT
+ufunc_eval_jacobi_types[13] = NPY_CFLOAT
+ufunc_eval_jacobi_types[14] = NPY_CFLOAT
+ufunc_eval_jacobi_types[15] = NPY_DOUBLE
+ufunc_eval_jacobi_types[16] = NPY_DOUBLE
+ufunc_eval_jacobi_types[17] = NPY_DOUBLE
+ufunc_eval_jacobi_types[18] = NPY_DOUBLE
+ufunc_eval_jacobi_types[19] = NPY_DOUBLE
+ufunc_eval_jacobi_types[20] = NPY_DOUBLE
+ufunc_eval_jacobi_types[21] = NPY_DOUBLE
+ufunc_eval_jacobi_types[22] = NPY_DOUBLE
+ufunc_eval_jacobi_types[23] = NPY_CDOUBLE
+ufunc_eval_jacobi_types[24] = NPY_CDOUBLE
+ufunc_eval_jacobi_ptr[2*0] = _func_eval_jacobi_l
+ufunc_eval_jacobi_ptr[2*0+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*1] = _func_eval_jacobi[double]
+ufunc_eval_jacobi_ptr[2*1+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*2] = _func_eval_jacobi[double_complex]
+ufunc_eval_jacobi_ptr[2*2+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*3] = _func_eval_jacobi[double]
+ufunc_eval_jacobi_ptr[2*3+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*4] = _func_eval_jacobi[double_complex]
+ufunc_eval_jacobi_ptr[2*4+1] = ("eval_jacobi")
+ufunc_eval_jacobi_data[0] = &ufunc_eval_jacobi_ptr[2*0]
+ufunc_eval_jacobi_data[1] = &ufunc_eval_jacobi_ptr[2*1]
+ufunc_eval_jacobi_data[2] = &ufunc_eval_jacobi_ptr[2*2]
+ufunc_eval_jacobi_data[3] = &ufunc_eval_jacobi_ptr[2*3]
+ufunc_eval_jacobi_data[4] = &ufunc_eval_jacobi_ptr[2*4]
+eval_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_jacobi_loops, ufunc_eval_jacobi_data, ufunc_eval_jacobi_types, 5, 4, 1, 0, "eval_jacobi", ufunc_eval_jacobi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_laguerre_loops[5]
+cdef void *ufunc_eval_laguerre_ptr[10]
+cdef void *ufunc_eval_laguerre_data[5]
+cdef char ufunc_eval_laguerre_types[15]
+cdef char *ufunc_eval_laguerre_doc = (
+    "eval_laguerre(n, x, out=None)\n"
+    "\n"
+    "Evaluate Laguerre polynomial at a point.\n"
+    "\n"
+    "The Laguerre polynomials can be defined via the confluent\n"
+    "hypergeometric function :math:`{}_1F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    L_n(x) = {}_1F_1(-n, 1, x).\n"
+    "\n"
+    "See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an\n"
+    "integer the result is a polynomial of degree :math:`n`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer the result is\n"
+    "    determined via the relation to the confluent hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Laguerre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "L : scalar or ndarray\n"
+    "    Values of the Laguerre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_laguerre : roots and quadrature weights of Laguerre\n"
+    "                 polynomials\n"
+    "laguerre : Laguerre polynomial object\n"
+    "numpy.polynomial.laguerre.Laguerre : Laguerre series\n"
+    "eval_genlaguerre : evaluate generalized Laguerre polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_laguerre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_laguerre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_laguerre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_laguerre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_laguerre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_laguerre_types[0] = NPY_INTP
+ufunc_eval_laguerre_types[1] = NPY_DOUBLE
+ufunc_eval_laguerre_types[2] = NPY_DOUBLE
+ufunc_eval_laguerre_types[3] = NPY_FLOAT
+ufunc_eval_laguerre_types[4] = NPY_FLOAT
+ufunc_eval_laguerre_types[5] = NPY_FLOAT
+ufunc_eval_laguerre_types[6] = NPY_FLOAT
+ufunc_eval_laguerre_types[7] = NPY_CFLOAT
+ufunc_eval_laguerre_types[8] = NPY_CFLOAT
+ufunc_eval_laguerre_types[9] = NPY_DOUBLE
+ufunc_eval_laguerre_types[10] = NPY_DOUBLE
+ufunc_eval_laguerre_types[11] = NPY_DOUBLE
+ufunc_eval_laguerre_types[12] = NPY_DOUBLE
+ufunc_eval_laguerre_types[13] = NPY_CDOUBLE
+ufunc_eval_laguerre_types[14] = NPY_CDOUBLE
+ufunc_eval_laguerre_ptr[2*0] = _func_eval_laguerre_l
+ufunc_eval_laguerre_ptr[2*0+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*1] = _func_eval_laguerre[double]
+ufunc_eval_laguerre_ptr[2*1+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*2] = _func_eval_laguerre[double_complex]
+ufunc_eval_laguerre_ptr[2*2+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*3] = _func_eval_laguerre[double]
+ufunc_eval_laguerre_ptr[2*3+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*4] = _func_eval_laguerre[double_complex]
+ufunc_eval_laguerre_ptr[2*4+1] = ("eval_laguerre")
+ufunc_eval_laguerre_data[0] = &ufunc_eval_laguerre_ptr[2*0]
+ufunc_eval_laguerre_data[1] = &ufunc_eval_laguerre_ptr[2*1]
+ufunc_eval_laguerre_data[2] = &ufunc_eval_laguerre_ptr[2*2]
+ufunc_eval_laguerre_data[3] = &ufunc_eval_laguerre_ptr[2*3]
+ufunc_eval_laguerre_data[4] = &ufunc_eval_laguerre_ptr[2*4]
+eval_laguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_laguerre_loops, ufunc_eval_laguerre_data, ufunc_eval_laguerre_types, 5, 2, 1, 0, "eval_laguerre", ufunc_eval_laguerre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_legendre_loops[5]
+cdef void *ufunc_eval_legendre_ptr[10]
+cdef void *ufunc_eval_legendre_data[5]
+cdef char ufunc_eval_legendre_types[15]
+cdef char *ufunc_eval_legendre_doc = (
+    "eval_legendre(n, x, out=None)\n"
+    "\n"
+    "Evaluate Legendre polynomial at a point.\n"
+    "\n"
+    "The Legendre polynomials can be defined via the Gauss\n"
+    "hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.49 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Legendre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the Legendre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_legendre : roots and quadrature weights of Legendre\n"
+    "                 polynomials\n"
+    "legendre : Legendre polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "numpy.polynomial.legendre.Legendre : Legendre series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import eval_legendre\n"
+    "\n"
+    "Evaluate the zero-order Legendre polynomial at x = 0\n"
+    "\n"
+    ">>> eval_legendre(0, 0)\n"
+    "1.0\n"
+    "\n"
+    "Evaluate the first-order Legendre polynomial between -1 and 1\n"
+    "\n"
+    ">>> X = np.linspace(-1, 1, 5)  # Domain of Legendre polynomials\n"
+    ">>> eval_legendre(1, X)\n"
+    "array([-1. , -0.5,  0. ,  0.5,  1. ])\n"
+    "\n"
+    "Evaluate Legendre polynomials of order 0 through 4 at x = 0\n"
+    "\n"
+    ">>> N = range(0, 5)\n"
+    ">>> eval_legendre(N, 0)\n"
+    "array([ 1.   ,  0.   , -0.5  ,  0.   ,  0.375])\n"
+    "\n"
+    "Plot Legendre polynomials of order 0 through 4\n"
+    "\n"
+    ">>> X = np.linspace(-1, 1)\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> for n in range(0, 5):\n"
+    "...     y = eval_legendre(n, X)\n"
+    "...     plt.plot(X, y, label=r'$P_{}(x)$'.format(n))\n"
+    "\n"
+    ">>> plt.title(\"Legendre Polynomials\")\n"
+    ">>> plt.xlabel(\"x\")\n"
+    ">>> plt.ylabel(r'$P_n(x)$')\n"
+    ">>> plt.legend(loc='lower right')\n"
+    ">>> plt.show()")
+ufunc_eval_legendre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_legendre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_legendre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_legendre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_legendre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_legendre_types[0] = NPY_INTP
+ufunc_eval_legendre_types[1] = NPY_DOUBLE
+ufunc_eval_legendre_types[2] = NPY_DOUBLE
+ufunc_eval_legendre_types[3] = NPY_FLOAT
+ufunc_eval_legendre_types[4] = NPY_FLOAT
+ufunc_eval_legendre_types[5] = NPY_FLOAT
+ufunc_eval_legendre_types[6] = NPY_FLOAT
+ufunc_eval_legendre_types[7] = NPY_CFLOAT
+ufunc_eval_legendre_types[8] = NPY_CFLOAT
+ufunc_eval_legendre_types[9] = NPY_DOUBLE
+ufunc_eval_legendre_types[10] = NPY_DOUBLE
+ufunc_eval_legendre_types[11] = NPY_DOUBLE
+ufunc_eval_legendre_types[12] = NPY_DOUBLE
+ufunc_eval_legendre_types[13] = NPY_CDOUBLE
+ufunc_eval_legendre_types[14] = NPY_CDOUBLE
+ufunc_eval_legendre_ptr[2*0] = _func_eval_legendre_l
+ufunc_eval_legendre_ptr[2*0+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*1] = _func_eval_legendre[double]
+ufunc_eval_legendre_ptr[2*1+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*2] = _func_eval_legendre[double_complex]
+ufunc_eval_legendre_ptr[2*2+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*3] = _func_eval_legendre[double]
+ufunc_eval_legendre_ptr[2*3+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*4] = _func_eval_legendre[double_complex]
+ufunc_eval_legendre_ptr[2*4+1] = ("eval_legendre")
+ufunc_eval_legendre_data[0] = &ufunc_eval_legendre_ptr[2*0]
+ufunc_eval_legendre_data[1] = &ufunc_eval_legendre_ptr[2*1]
+ufunc_eval_legendre_data[2] = &ufunc_eval_legendre_ptr[2*2]
+ufunc_eval_legendre_data[3] = &ufunc_eval_legendre_ptr[2*3]
+ufunc_eval_legendre_data[4] = &ufunc_eval_legendre_ptr[2*4]
+eval_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_legendre_loops, ufunc_eval_legendre_data, ufunc_eval_legendre_types, 5, 2, 1, 0, "eval_legendre", ufunc_eval_legendre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyt_loops[5]
+cdef void *ufunc_eval_sh_chebyt_ptr[10]
+cdef void *ufunc_eval_sh_chebyt_data[5]
+cdef char ufunc_eval_sh_chebyt_types[15]
+cdef char *ufunc_eval_sh_chebyt_doc = (
+    "eval_sh_chebyt(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Chebyshev polynomial of the first kind at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    T_n^*(x) = T_n(2x - 1)\n"
+    "\n"
+    "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.14 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyt`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "T : scalar or ndarray\n"
+    "    Values of the shifted Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_chebyt : roots and quadrature weights of shifted\n"
+    "                  Chebyshev polynomials of the first kind\n"
+    "sh_chebyt : shifted Chebyshev polynomial object\n"
+    "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_chebyt_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_chebyt_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_chebyt_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_chebyt_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_chebyt_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_chebyt_types[0] = NPY_INTP
+ufunc_eval_sh_chebyt_types[1] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[2] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[3] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[4] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[5] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[6] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[7] = NPY_CFLOAT
+ufunc_eval_sh_chebyt_types[8] = NPY_CFLOAT
+ufunc_eval_sh_chebyt_types[9] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[10] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[11] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[12] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_chebyt_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_chebyt_ptr[2*0] = _func_eval_sh_chebyt_l
+ufunc_eval_sh_chebyt_ptr[2*0+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*1] = _func_eval_sh_chebyt[double]
+ufunc_eval_sh_chebyt_ptr[2*1+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*2] = _func_eval_sh_chebyt[double_complex]
+ufunc_eval_sh_chebyt_ptr[2*2+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*3] = _func_eval_sh_chebyt[double]
+ufunc_eval_sh_chebyt_ptr[2*3+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*4] = _func_eval_sh_chebyt[double_complex]
+ufunc_eval_sh_chebyt_ptr[2*4+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_data[0] = &ufunc_eval_sh_chebyt_ptr[2*0]
+ufunc_eval_sh_chebyt_data[1] = &ufunc_eval_sh_chebyt_ptr[2*1]
+ufunc_eval_sh_chebyt_data[2] = &ufunc_eval_sh_chebyt_ptr[2*2]
+ufunc_eval_sh_chebyt_data[3] = &ufunc_eval_sh_chebyt_ptr[2*3]
+ufunc_eval_sh_chebyt_data[4] = &ufunc_eval_sh_chebyt_ptr[2*4]
+eval_sh_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyt_loops, ufunc_eval_sh_chebyt_data, ufunc_eval_sh_chebyt_types, 5, 2, 1, 0, "eval_sh_chebyt", ufunc_eval_sh_chebyt_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyu_loops[5]
+cdef void *ufunc_eval_sh_chebyu_ptr[10]
+cdef void *ufunc_eval_sh_chebyu_data[5]
+cdef char ufunc_eval_sh_chebyu_types[15]
+cdef char *ufunc_eval_sh_chebyu_doc = (
+    "eval_sh_chebyu(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Chebyshev polynomial of the second kind at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    U_n^*(x) = U_n(2x - 1)\n"
+    "\n"
+    "where :math:`U_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.15 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyu`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "U : scalar or ndarray\n"
+    "    Values of the shifted Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_chebyu : roots and quadrature weights of shifted\n"
+    "                  Chebychev polynomials of the second kind\n"
+    "sh_chebyu : shifted Chebyshev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_chebyu_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_chebyu_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_chebyu_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_chebyu_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_chebyu_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_chebyu_types[0] = NPY_INTP
+ufunc_eval_sh_chebyu_types[1] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[2] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[3] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[4] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[5] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[6] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[7] = NPY_CFLOAT
+ufunc_eval_sh_chebyu_types[8] = NPY_CFLOAT
+ufunc_eval_sh_chebyu_types[9] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[10] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[11] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[12] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_chebyu_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_chebyu_ptr[2*0] = _func_eval_sh_chebyu_l
+ufunc_eval_sh_chebyu_ptr[2*0+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*1] = _func_eval_sh_chebyu[double]
+ufunc_eval_sh_chebyu_ptr[2*1+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*2] = _func_eval_sh_chebyu[double_complex]
+ufunc_eval_sh_chebyu_ptr[2*2+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*3] = _func_eval_sh_chebyu[double]
+ufunc_eval_sh_chebyu_ptr[2*3+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*4] = _func_eval_sh_chebyu[double_complex]
+ufunc_eval_sh_chebyu_ptr[2*4+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_data[0] = &ufunc_eval_sh_chebyu_ptr[2*0]
+ufunc_eval_sh_chebyu_data[1] = &ufunc_eval_sh_chebyu_ptr[2*1]
+ufunc_eval_sh_chebyu_data[2] = &ufunc_eval_sh_chebyu_ptr[2*2]
+ufunc_eval_sh_chebyu_data[3] = &ufunc_eval_sh_chebyu_ptr[2*3]
+ufunc_eval_sh_chebyu_data[4] = &ufunc_eval_sh_chebyu_ptr[2*4]
+eval_sh_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyu_loops, ufunc_eval_sh_chebyu_data, ufunc_eval_sh_chebyu_types, 5, 2, 1, 0, "eval_sh_chebyu", ufunc_eval_sh_chebyu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_jacobi_loops[5]
+cdef void *ufunc_eval_sh_jacobi_ptr[10]
+cdef void *ufunc_eval_sh_jacobi_data[5]
+cdef char ufunc_eval_sh_jacobi_types[25]
+cdef char *ufunc_eval_sh_jacobi_doc = (
+    "eval_sh_jacobi(n, p, q, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Jacobi polynomial at a point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    G_n^{(p, q)}(x)\n"
+    "      = \\binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),\n"
+    "\n"
+    "where :math:`P_n^{(\\cdot, \\cdot)}` is the n-th Jacobi\n"
+    "polynomial. See 22.5.2 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `binom` and `eval_jacobi`.\n"
+    "p : float\n"
+    "    Parameter\n"
+    "q : float\n"
+    "    Parameter\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "G : scalar or ndarray\n"
+    "    Values of the shifted Jacobi polynomial.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_jacobi : roots and quadrature weights of shifted Jacobi\n"
+    "                  polynomials\n"
+    "sh_jacobi : shifted Jacobi polynomial object\n"
+    "eval_jacobi : evaluate Jacobi polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_jacobi_loops[0] = loop_d_pddd__As_pddd_d
+ufunc_eval_sh_jacobi_loops[1] = loop_d_dddd__As_ffff_f
+ufunc_eval_sh_jacobi_loops[2] = loop_D_dddD__As_fffF_F
+ufunc_eval_sh_jacobi_loops[3] = loop_d_dddd__As_dddd_d
+ufunc_eval_sh_jacobi_loops[4] = loop_D_dddD__As_dddD_D
+ufunc_eval_sh_jacobi_types[0] = NPY_INTP
+ufunc_eval_sh_jacobi_types[1] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[2] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[3] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[4] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[5] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[6] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[7] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[8] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[9] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[10] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[11] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[12] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[13] = NPY_CFLOAT
+ufunc_eval_sh_jacobi_types[14] = NPY_CFLOAT
+ufunc_eval_sh_jacobi_types[15] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[16] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[17] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[18] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[19] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[20] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[21] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[22] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[23] = NPY_CDOUBLE
+ufunc_eval_sh_jacobi_types[24] = NPY_CDOUBLE
+ufunc_eval_sh_jacobi_ptr[2*0] = _func_eval_sh_jacobi_l
+ufunc_eval_sh_jacobi_ptr[2*0+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*1] = _func_eval_sh_jacobi[double]
+ufunc_eval_sh_jacobi_ptr[2*1+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*2] = _func_eval_sh_jacobi[double_complex]
+ufunc_eval_sh_jacobi_ptr[2*2+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*3] = _func_eval_sh_jacobi[double]
+ufunc_eval_sh_jacobi_ptr[2*3+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*4] = _func_eval_sh_jacobi[double_complex]
+ufunc_eval_sh_jacobi_ptr[2*4+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_data[0] = &ufunc_eval_sh_jacobi_ptr[2*0]
+ufunc_eval_sh_jacobi_data[1] = &ufunc_eval_sh_jacobi_ptr[2*1]
+ufunc_eval_sh_jacobi_data[2] = &ufunc_eval_sh_jacobi_ptr[2*2]
+ufunc_eval_sh_jacobi_data[3] = &ufunc_eval_sh_jacobi_ptr[2*3]
+ufunc_eval_sh_jacobi_data[4] = &ufunc_eval_sh_jacobi_ptr[2*4]
+eval_sh_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_jacobi_loops, ufunc_eval_sh_jacobi_data, ufunc_eval_sh_jacobi_types, 5, 4, 1, 0, "eval_sh_jacobi", ufunc_eval_sh_jacobi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_legendre_loops[5]
+cdef void *ufunc_eval_sh_legendre_ptr[10]
+cdef void *ufunc_eval_sh_legendre_data[5]
+cdef char ufunc_eval_sh_legendre_types[15]
+cdef char *ufunc_eval_sh_legendre_doc = (
+    "eval_sh_legendre(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Legendre polynomial at a point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n^*(x) = P_n(2x - 1)\n"
+    "\n"
+    "where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_\n"
+    "for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the value is\n"
+    "    determined via the relation to `eval_legendre`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Legendre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the shifted Legendre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_legendre : roots and quadrature weights of shifted\n"
+    "                    Legendre polynomials\n"
+    "sh_legendre : shifted Legendre polynomial object\n"
+    "eval_legendre : evaluate Legendre polynomials\n"
+    "numpy.polynomial.legendre.Legendre : Legendre series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_legendre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_legendre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_legendre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_legendre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_legendre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_legendre_types[0] = NPY_INTP
+ufunc_eval_sh_legendre_types[1] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[2] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[3] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[4] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[5] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[6] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[7] = NPY_CFLOAT
+ufunc_eval_sh_legendre_types[8] = NPY_CFLOAT
+ufunc_eval_sh_legendre_types[9] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[10] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[11] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[12] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_legendre_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_legendre_ptr[2*0] = _func_eval_sh_legendre_l
+ufunc_eval_sh_legendre_ptr[2*0+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*1] = _func_eval_sh_legendre[double]
+ufunc_eval_sh_legendre_ptr[2*1+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*2] = _func_eval_sh_legendre[double_complex]
+ufunc_eval_sh_legendre_ptr[2*2+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*3] = _func_eval_sh_legendre[double]
+ufunc_eval_sh_legendre_ptr[2*3+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*4] = _func_eval_sh_legendre[double_complex]
+ufunc_eval_sh_legendre_ptr[2*4+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_data[0] = &ufunc_eval_sh_legendre_ptr[2*0]
+ufunc_eval_sh_legendre_data[1] = &ufunc_eval_sh_legendre_ptr[2*1]
+ufunc_eval_sh_legendre_data[2] = &ufunc_eval_sh_legendre_ptr[2*2]
+ufunc_eval_sh_legendre_data[3] = &ufunc_eval_sh_legendre_ptr[2*3]
+ufunc_eval_sh_legendre_data[4] = &ufunc_eval_sh_legendre_ptr[2*4]
+eval_sh_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_legendre_loops, ufunc_eval_sh_legendre_data, ufunc_eval_sh_legendre_types, 5, 2, 1, 0, "eval_sh_legendre", ufunc_eval_sh_legendre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_exp10_loops[2]
+cdef void *ufunc_exp10_ptr[4]
+cdef void *ufunc_exp10_data[2]
+cdef char ufunc_exp10_types[4]
+cdef char *ufunc_exp10_doc = (
+    "exp10(x, out=None)\n"
+    "\n"
+    "Compute ``10**x`` element-wise.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``10**x``, computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import exp10\n"
+    "\n"
+    ">>> exp10(3)\n"
+    "1000.0\n"
+    ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n"
+    ">>> exp10(x)\n"
+    "array([[  0.1       ,   0.31622777,   1.        ],\n"
+    "       [  3.16227766,  10.        ,  31.6227766 ]])")
+ufunc_exp10_loops[0] = loop_d_d__As_f_f
+ufunc_exp10_loops[1] = loop_d_d__As_d_d
+ufunc_exp10_types[0] = NPY_FLOAT
+ufunc_exp10_types[1] = NPY_FLOAT
+ufunc_exp10_types[2] = NPY_DOUBLE
+ufunc_exp10_types[3] = NPY_DOUBLE
+ufunc_exp10_ptr[2*0] = _func_cephes_exp10
+ufunc_exp10_ptr[2*0+1] = ("exp10")
+ufunc_exp10_ptr[2*1] = _func_cephes_exp10
+ufunc_exp10_ptr[2*1+1] = ("exp10")
+ufunc_exp10_data[0] = &ufunc_exp10_ptr[2*0]
+ufunc_exp10_data[1] = &ufunc_exp10_ptr[2*1]
+exp10 = np.PyUFunc_FromFuncAndData(ufunc_exp10_loops, ufunc_exp10_data, ufunc_exp10_types, 2, 1, 1, 0, "exp10", ufunc_exp10_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_exp2_loops[2]
+cdef void *ufunc_exp2_ptr[4]
+cdef void *ufunc_exp2_data[2]
+cdef char ufunc_exp2_types[4]
+cdef char *ufunc_exp2_doc = (
+    "exp2(x, out=None)\n"
+    "\n"
+    "Compute ``2**x`` element-wise.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``2**x``, computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import exp2\n"
+    "\n"
+    ">>> exp2(3)\n"
+    "8.0\n"
+    ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n"
+    ">>> exp2(x)\n"
+    "array([[ 0.5       ,  0.70710678,  1.        ],\n"
+    "       [ 1.41421356,  2.        ,  2.82842712]])")
+ufunc_exp2_loops[0] = loop_d_d__As_f_f
+ufunc_exp2_loops[1] = loop_d_d__As_d_d
+ufunc_exp2_types[0] = NPY_FLOAT
+ufunc_exp2_types[1] = NPY_FLOAT
+ufunc_exp2_types[2] = NPY_DOUBLE
+ufunc_exp2_types[3] = NPY_DOUBLE
+ufunc_exp2_ptr[2*0] = _func_cephes_exp2
+ufunc_exp2_ptr[2*0+1] = ("exp2")
+ufunc_exp2_ptr[2*1] = _func_cephes_exp2
+ufunc_exp2_ptr[2*1+1] = ("exp2")
+ufunc_exp2_data[0] = &ufunc_exp2_ptr[2*0]
+ufunc_exp2_data[1] = &ufunc_exp2_ptr[2*1]
+exp2 = np.PyUFunc_FromFuncAndData(ufunc_exp2_loops, ufunc_exp2_data, ufunc_exp2_types, 2, 1, 1, 0, "exp2", ufunc_exp2_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_expm1_loops[4]
+cdef void *ufunc_expm1_ptr[8]
+cdef void *ufunc_expm1_data[4]
+cdef char ufunc_expm1_types[8]
+cdef char *ufunc_expm1_doc = (
+    "expm1(x, out=None)\n"
+    "\n"
+    "Compute ``exp(x) - 1``.\n"
+    "\n"
+    "When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation\n"
+    "of ``exp(x) - 1`` can suffer from catastrophic loss of precision.\n"
+    "``expm1(x)`` is implemented to avoid the loss of precision that occurs when\n"
+    "`x` is near zero.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``exp(x) - 1`` computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import expm1\n"
+    "\n"
+    ">>> expm1(1.0)\n"
+    "1.7182818284590451\n"
+    ">>> expm1([-0.2, -0.1, 0, 0.1, 0.2])\n"
+    "array([-0.18126925, -0.09516258,  0.        ,  0.10517092,  0.22140276])\n"
+    "\n"
+    "The exact value of ``exp(7.5e-13) - 1`` is::\n"
+    "\n"
+    "    7.5000000000028125000000007031250000001318...*10**-13.\n"
+    "\n"
+    "Here is what ``expm1(7.5e-13)`` gives:\n"
+    "\n"
+    ">>> expm1(7.5e-13)\n"
+    "7.5000000000028135e-13\n"
+    "\n"
+    "Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in\n"
+    "a \"catastrophic\" loss of precision:\n"
+    "\n"
+    ">>> np.exp(7.5e-13) - 1\n"
+    "7.5006667543675576e-13")
+ufunc_expm1_loops[0] = loop_d_d__As_f_f
+ufunc_expm1_loops[1] = loop_d_d__As_d_d
+ufunc_expm1_loops[2] = loop_D_D__As_F_F
+ufunc_expm1_loops[3] = loop_D_D__As_D_D
+ufunc_expm1_types[0] = NPY_FLOAT
+ufunc_expm1_types[1] = NPY_FLOAT
+ufunc_expm1_types[2] = NPY_DOUBLE
+ufunc_expm1_types[3] = NPY_DOUBLE
+ufunc_expm1_types[4] = NPY_CFLOAT
+ufunc_expm1_types[5] = NPY_CFLOAT
+ufunc_expm1_types[6] = NPY_CDOUBLE
+ufunc_expm1_types[7] = NPY_CDOUBLE
+ufunc_expm1_ptr[2*0] = _func_cephes_expm1
+ufunc_expm1_ptr[2*0+1] = ("expm1")
+ufunc_expm1_ptr[2*1] = _func_cephes_expm1
+ufunc_expm1_ptr[2*1+1] = ("expm1")
+ufunc_expm1_ptr[2*2] = _func_cexpm1
+ufunc_expm1_ptr[2*2+1] = ("expm1")
+ufunc_expm1_ptr[2*3] = _func_cexpm1
+ufunc_expm1_ptr[2*3+1] = ("expm1")
+ufunc_expm1_data[0] = &ufunc_expm1_ptr[2*0]
+ufunc_expm1_data[1] = &ufunc_expm1_ptr[2*1]
+ufunc_expm1_data[2] = &ufunc_expm1_ptr[2*2]
+ufunc_expm1_data[3] = &ufunc_expm1_ptr[2*3]
+expm1 = np.PyUFunc_FromFuncAndData(ufunc_expm1_loops, ufunc_expm1_data, ufunc_expm1_types, 4, 1, 1, 0, "expm1", ufunc_expm1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_expn_loops[3]
+cdef void *ufunc_expn_ptr[6]
+cdef void *ufunc_expn_data[3]
+cdef char ufunc_expn_types[9]
+cdef char *ufunc_expn_doc = (
+    "expn(n, x, out=None)\n"
+    "\n"
+    "Generalized exponential integral En.\n"
+    "\n"
+    "For integer :math:`n \\geq 0` and real :math:`x \\geq 0` the\n"
+    "generalized exponential integral is defined as [dlmf]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    E_n(x) = x^{n - 1} \\int_x^\\infty \\frac{e^{-t}}{t^n} dt.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Non-negative integers\n"
+    "x : array_like\n"
+    "    Real argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the generalized exponential integral\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "exp1 : special case of :math:`E_n` for :math:`n = 1`\n"
+    "expi : related to :math:`E_n` when :math:`n = 1`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] Digital Library of Mathematical Functions, 8.19.2\n"
+    "          https://dlmf.nist.gov/8.19#E2\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Its domain is nonnegative n and x.\n"
+    "\n"
+    ">>> sc.expn(-1, 1.0), sc.expn(1, -1.0)\n"
+    "(nan, nan)\n"
+    "\n"
+    "It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it\n"
+    "is equal to ``1 / (n - 1)``.\n"
+    "\n"
+    ">>> sc.expn([0, 1, 2, 3, 4], 0)\n"
+    "array([       inf,        inf, 1.        , 0.5       , 0.33333333])\n"
+    "\n"
+    "For n equal to 0 it reduces to ``exp(-x) / x``.\n"
+    "\n"
+    ">>> x = np.array([1, 2, 3, 4])\n"
+    ">>> sc.expn(0, x)\n"
+    "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n"
+    ">>> np.exp(-x) / x\n"
+    "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n"
+    "\n"
+    "For n equal to 1 it reduces to `exp1`.\n"
+    "\n"
+    ">>> sc.expn(1, x)\n"
+    "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])\n"
+    ">>> sc.exp1(x)\n"
+    "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])")
+ufunc_expn_loops[0] = loop_d_pd__As_pd_d
+ufunc_expn_loops[1] = loop_d_dd__As_ff_f
+ufunc_expn_loops[2] = loop_d_dd__As_dd_d
+ufunc_expn_types[0] = NPY_INTP
+ufunc_expn_types[1] = NPY_DOUBLE
+ufunc_expn_types[2] = NPY_DOUBLE
+ufunc_expn_types[3] = NPY_FLOAT
+ufunc_expn_types[4] = NPY_FLOAT
+ufunc_expn_types[5] = NPY_FLOAT
+ufunc_expn_types[6] = NPY_DOUBLE
+ufunc_expn_types[7] = NPY_DOUBLE
+ufunc_expn_types[8] = NPY_DOUBLE
+ufunc_expn_ptr[2*0] = _func_cephes_expn_wrap
+ufunc_expn_ptr[2*0+1] = ("expn")
+ufunc_expn_ptr[2*1] = _func_expn_unsafe
+ufunc_expn_ptr[2*1+1] = ("expn")
+ufunc_expn_ptr[2*2] = _func_expn_unsafe
+ufunc_expn_ptr[2*2+1] = ("expn")
+ufunc_expn_data[0] = &ufunc_expn_ptr[2*0]
+ufunc_expn_data[1] = &ufunc_expn_ptr[2*1]
+ufunc_expn_data[2] = &ufunc_expn_ptr[2*2]
+expn = np.PyUFunc_FromFuncAndData(ufunc_expn_loops, ufunc_expn_data, ufunc_expn_types, 3, 2, 1, 0, "expn", ufunc_expn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtr_loops[2]
+cdef void *ufunc_fdtr_ptr[4]
+cdef void *ufunc_fdtr_data[2]
+cdef char ufunc_fdtr_types[8]
+cdef char *ufunc_fdtr_doc = (
+    "fdtr(dfn, dfd, x, out=None)\n"
+    "\n"
+    "F cumulative distribution function.\n"
+    "\n"
+    "Returns the value of the cumulative distribution function of the\n"
+    "F-distribution, also known as Snedecor's F-distribution or the\n"
+    "Fisher-Snedecor distribution.\n"
+    "\n"
+    "The F-distribution with parameters :math:`d_n` and :math:`d_d` is the\n"
+    "distribution of the random variable,\n"
+    "\n"
+    ".. math::\n"
+    "    X = \\frac{U_n/d_n}{U_d/d_d},\n"
+    "\n"
+    "where :math:`U_n` and :math:`U_d` are random variables distributed\n"
+    ":math:`\\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,\n"
+    "respectively.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtrc : F distribution survival function\n"
+    "fdtri : F distribution inverse cumulative distribution\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The regularized incomplete beta function is used, according to the\n"
+    "formula,\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also\n"
+    "available as `scipy.stats.f`. Calling `fdtr` directly can improve\n"
+    "performance compared to the ``cdf`` method of `scipy.stats.f` (see last\n"
+    "example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtr\n"
+    ">>> fdtr(1, 2, 1)\n"
+    "0.5773502691896258\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.5, 2., 3.])\n"
+    ">>> fdtr(1, 2, x)\n"
+    "array([0.4472136 , 0.70710678, 0.77459667])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [1, 5, 10, 50]\n"
+    ">>> dfd_parameters = [1, 1, 2, 3]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtr_vals = fdtr(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtr_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"F distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtr`\n"
+    "directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 1\n"
+    ">>> fdtr_res = fdtr(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).cdf(x)\n"
+    ">>> fdtr_res == f_dist_res  # test that results are equal\n"
+    "True")
+ufunc_fdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtr_types[0] = NPY_FLOAT
+ufunc_fdtr_types[1] = NPY_FLOAT
+ufunc_fdtr_types[2] = NPY_FLOAT
+ufunc_fdtr_types[3] = NPY_FLOAT
+ufunc_fdtr_types[4] = NPY_DOUBLE
+ufunc_fdtr_types[5] = NPY_DOUBLE
+ufunc_fdtr_types[6] = NPY_DOUBLE
+ufunc_fdtr_types[7] = NPY_DOUBLE
+ufunc_fdtr_ptr[2*0] = _func_xsf_fdtr
+ufunc_fdtr_ptr[2*0+1] = ("fdtr")
+ufunc_fdtr_ptr[2*1] = _func_xsf_fdtr
+ufunc_fdtr_ptr[2*1+1] = ("fdtr")
+ufunc_fdtr_data[0] = &ufunc_fdtr_ptr[2*0]
+ufunc_fdtr_data[1] = &ufunc_fdtr_ptr[2*1]
+fdtr = np.PyUFunc_FromFuncAndData(ufunc_fdtr_loops, ufunc_fdtr_data, ufunc_fdtr_types, 2, 3, 1, 0, "fdtr", ufunc_fdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtrc_loops[2]
+cdef void *ufunc_fdtrc_ptr[4]
+cdef void *ufunc_fdtrc_data[2]
+cdef char ufunc_fdtrc_types[8]
+cdef char *ufunc_fdtrc_doc = (
+    "fdtrc(dfn, dfd, x, out=None)\n"
+    "\n"
+    "F survival function.\n"
+    "\n"
+    "Returns the complemented F-distribution function (the integral of the\n"
+    "density from `x` to infinity).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    The complemented F-distribution function with parameters `dfn` and\n"
+    "    `dfd` at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtri : F distribution inverse cumulative distribution function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The regularized incomplete beta function is used, according to the\n"
+    "formula,\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also\n"
+    "available as `scipy.stats.f`. Calling `fdtrc` directly can improve\n"
+    "performance compared to the ``sf`` method of `scipy.stats.f` (see last\n"
+    "example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtrc\n"
+    ">>> fdtrc(1, 2, 1)\n"
+    "0.42264973081037427\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.5, 2., 3.])\n"
+    ">>> fdtrc(1, 2, x)\n"
+    "array([0.5527864 , 0.29289322, 0.22540333])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [1, 5, 10, 50]\n"
+    ">>> dfd_parameters = [1, 1, 2, 3]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtrc_vals = fdtrc(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtrc_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"F distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtrc`\n"
+    "directly can be much faster than calling the ``sf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 1\n"
+    ">>> fdtrc_res = fdtrc(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).sf(x)\n"
+    ">>> f_dist_res == fdtrc_res  # test that results are equal\n"
+    "True")
+ufunc_fdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtrc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtrc_types[0] = NPY_FLOAT
+ufunc_fdtrc_types[1] = NPY_FLOAT
+ufunc_fdtrc_types[2] = NPY_FLOAT
+ufunc_fdtrc_types[3] = NPY_FLOAT
+ufunc_fdtrc_types[4] = NPY_DOUBLE
+ufunc_fdtrc_types[5] = NPY_DOUBLE
+ufunc_fdtrc_types[6] = NPY_DOUBLE
+ufunc_fdtrc_types[7] = NPY_DOUBLE
+ufunc_fdtrc_ptr[2*0] = _func_xsf_fdtrc
+ufunc_fdtrc_ptr[2*0+1] = ("fdtrc")
+ufunc_fdtrc_ptr[2*1] = _func_xsf_fdtrc
+ufunc_fdtrc_ptr[2*1+1] = ("fdtrc")
+ufunc_fdtrc_data[0] = &ufunc_fdtrc_ptr[2*0]
+ufunc_fdtrc_data[1] = &ufunc_fdtrc_ptr[2*1]
+fdtrc = np.PyUFunc_FromFuncAndData(ufunc_fdtrc_loops, ufunc_fdtrc_data, ufunc_fdtrc_types, 2, 3, 1, 0, "fdtrc", ufunc_fdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtri_loops[2]
+cdef void *ufunc_fdtri_ptr[4]
+cdef void *ufunc_fdtri_data[2]
+cdef char ufunc_fdtri_types[8]
+cdef char *ufunc_fdtri_doc = (
+    "fdtri(dfn, dfd, p, out=None)\n"
+    "\n"
+    "The `p`-th quantile of the F-distribution.\n"
+    "\n"
+    "This function is the inverse of the F-distribution CDF, `fdtr`, returning\n"
+    "the `x` such that `fdtr(dfn, dfd, x) = p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    The quantile corresponding to `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtrc : F distribution survival function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The computation is carried out using the relation to the inverse\n"
+    "regularized beta function, :math:`I^{-1}_x(a, b)`.  Let\n"
+    ":math:`z = I^{-1}_p(d_d/2, d_n/2).`  Then,\n"
+    "\n"
+    ".. math::\n"
+    "    x = \\frac{d_d (1 - z)}{d_n z}.\n"
+    "\n"
+    "If `p` is such that :math:`x < 0.5`, the following relation is used\n"
+    "instead for improved stability: let\n"
+    ":math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,\n"
+    "\n"
+    ".. math::\n"
+    "    x = \\frac{d_d z'}{d_n (1 - z')}.\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtri`.\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Calling\n"
+    "`fdtri` directly can improve performance compared to the ``ppf``\n"
+    "method of `scipy.stats.f` (see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`fdtri` represents the inverse of the F distribution CDF which is\n"
+    "available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``\n"
+    "at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,\n"
+    "`df2` and the computed CDF value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtri, fdtr\n"
+    ">>> df1, df2 = 1, 2\n"
+    ">>> x = 3\n"
+    ">>> cdf_value =  fdtr(df1, df2, x)\n"
+    ">>> fdtri(df1, df2, cdf_value)\n"
+    "3.000000000000006\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.1, 0.4, 0.7])\n"
+    ">>> fdtri(1, 2, x)\n"
+    "array([0.02020202, 0.38095238, 1.92156863])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [50, 10, 1, 50]\n"
+    ">>> dfd_parameters = [0.5, 1, 1, 5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtri_vals = fdtri(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtri_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> title = \"F distribution inverse cumulative distribution function\"\n"
+    ">>> ax.set_title(title)\n"
+    ">>> ax.set_ylim(0, 30)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtri`\n"
+    "directly can be much faster than calling the ``ppf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 0.7\n"
+    ">>> fdtri_res = fdtri(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).ppf(x)\n"
+    ">>> f_dist_res == fdtri_res  # test that results are equal\n"
+    "True")
+ufunc_fdtri_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtri_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtri_types[0] = NPY_FLOAT
+ufunc_fdtri_types[1] = NPY_FLOAT
+ufunc_fdtri_types[2] = NPY_FLOAT
+ufunc_fdtri_types[3] = NPY_FLOAT
+ufunc_fdtri_types[4] = NPY_DOUBLE
+ufunc_fdtri_types[5] = NPY_DOUBLE
+ufunc_fdtri_types[6] = NPY_DOUBLE
+ufunc_fdtri_types[7] = NPY_DOUBLE
+ufunc_fdtri_ptr[2*0] = _func_xsf_fdtri
+ufunc_fdtri_ptr[2*0+1] = ("fdtri")
+ufunc_fdtri_ptr[2*1] = _func_xsf_fdtri
+ufunc_fdtri_ptr[2*1+1] = ("fdtri")
+ufunc_fdtri_data[0] = &ufunc_fdtri_ptr[2*0]
+ufunc_fdtri_data[1] = &ufunc_fdtri_ptr[2*1]
+fdtri = np.PyUFunc_FromFuncAndData(ufunc_fdtri_loops, ufunc_fdtri_data, ufunc_fdtri_types, 2, 3, 1, 0, "fdtri", ufunc_fdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtridfd_loops[2]
+cdef void *ufunc_fdtridfd_ptr[4]
+cdef void *ufunc_fdtridfd_data[2]
+cdef char ufunc_fdtridfd_types[8]
+cdef char *ufunc_fdtridfd_doc = (
+    "fdtridfd(dfn, p, x, out=None)\n"
+    "\n"
+    "Inverse to `fdtr` vs dfd\n"
+    "\n"
+    "Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfd : scalar or ndarray\n"
+    "    `dfd` such that ``fdtr(dfn, dfd, x) == p``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtrc : F distribution survival function\n"
+    "fdtri : F distribution quantile function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the F distribution cumulative distribution function for one\n"
+    "parameter set.\n"
+    "\n"
+    ">>> from scipy.special import fdtridfd, fdtr\n"
+    ">>> dfn, dfd, x = 10, 5, 2\n"
+    ">>> cdf_value = fdtr(dfn, dfd, x)\n"
+    ">>> cdf_value\n"
+    "0.7700248806501017\n"
+    "\n"
+    "Verify that `fdtridfd` recovers the original value for `dfd`:\n"
+    "\n"
+    ">>> fdtridfd(dfn, cdf_value, x)\n"
+    "5.0")
+ufunc_fdtridfd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtridfd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtridfd_types[0] = NPY_FLOAT
+ufunc_fdtridfd_types[1] = NPY_FLOAT
+ufunc_fdtridfd_types[2] = NPY_FLOAT
+ufunc_fdtridfd_types[3] = NPY_FLOAT
+ufunc_fdtridfd_types[4] = NPY_DOUBLE
+ufunc_fdtridfd_types[5] = NPY_DOUBLE
+ufunc_fdtridfd_types[6] = NPY_DOUBLE
+ufunc_fdtridfd_types[7] = NPY_DOUBLE
+ufunc_fdtridfd_ptr[2*0] = _func_fdtridfd
+ufunc_fdtridfd_ptr[2*0+1] = ("fdtridfd")
+ufunc_fdtridfd_ptr[2*1] = _func_fdtridfd
+ufunc_fdtridfd_ptr[2*1+1] = ("fdtridfd")
+ufunc_fdtridfd_data[0] = &ufunc_fdtridfd_ptr[2*0]
+ufunc_fdtridfd_data[1] = &ufunc_fdtridfd_ptr[2*1]
+fdtridfd = np.PyUFunc_FromFuncAndData(ufunc_fdtridfd_loops, ufunc_fdtridfd_data, ufunc_fdtridfd_types, 2, 3, 1, 0, "fdtridfd", ufunc_fdtridfd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtr_loops[2]
+cdef void *ufunc_gdtr_ptr[4]
+cdef void *ufunc_gdtr_data[2]
+cdef char ufunc_gdtr_types[8]
+cdef char *ufunc_gdtr_doc = (
+    "gdtr(a, b, x, out=None)\n"
+    "\n"
+    "Gamma distribution cumulative distribution function.\n"
+    "\n"
+    "Returns the integral from zero to `x` of the gamma probability density\n"
+    "function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\int_0^x \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n"
+    "\n"
+    "where :math:`\\Gamma` is the gamma function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    The rate parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\beta` (float).  It is also the reciprocal of the scale\n"
+    "    parameter :math:`\\theta`.\n"
+    "b : array_like\n"
+    "    The shape parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\alpha` (float).\n"
+    "x : array_like\n"
+    "    The quantile (upper limit of integration; float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The CDF of the gamma distribution with parameters `a` and `b`\n"
+    "    evaluated at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtrc : 1 - CDF of the gamma distribution.\n"
+    "scipy.stats.gamma: Gamma distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The evaluation is carried out using the relation to the incomplete gamma\n"
+    "integral (regularized gamma function).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can\n"
+    "improve performance compared to the ``cdf`` method of `scipy.stats.gamma`\n"
+    "(see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``a=1``, ``b=2`` at ``x=5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import gdtr\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> gdtr(1., 2., 5.)\n"
+    "0.9595723180054873\n"
+    "\n"
+    "Compute the function for ``a=1`` and ``b=2`` at several points by\n"
+    "providing a NumPy array for `x`.\n"
+    "\n"
+    ">>> xvalues = np.array([1., 2., 3., 4])\n"
+    ">>> gdtr(1., 1., xvalues)\n"
+    "array([0.63212056, 0.86466472, 0.95021293, 0.98168436])\n"
+    "\n"
+    "`gdtr` can evaluate different parameter sets by providing arrays with\n"
+    "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n"
+    "function for three different `a` at four positions `x` and ``b=3``,\n"
+    "resulting in a 3x4 array.\n"
+    "\n"
+    ">>> a = np.array([[0.5], [1.5], [2.5]])\n"
+    ">>> x = np.array([1., 2., 3., 4])\n"
+    ">>> a.shape, x.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> gdtr(a, 3., x)\n"
+    "array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],\n"
+    "       [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],\n"
+    "       [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> a_parameters = [0.3, 1, 2, 6]\n"
+    ">>> b_parameters = [2, 10, 15, 20]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     a, b, style = parameter_set\n"
+    "...     gdtr_vals = gdtr(a, b, x)\n"
+    "...     ax.plot(x, gdtr_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"Gamma distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The gamma distribution is also available as `scipy.stats.gamma`. Using\n"
+    "`gdtr` directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.gamma`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import gamma\n"
+    ">>> a = 2.\n"
+    ">>> b = 3\n"
+    ">>> x = 1.\n"
+    ">>> gdtr_result = gdtr(a, b, x)  # this will often be faster than below\n"
+    ">>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)\n"
+    ">>> gdtr_result == gamma_dist_result  # test that results are equal\n"
+    "True")
+ufunc_gdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtr_types[0] = NPY_FLOAT
+ufunc_gdtr_types[1] = NPY_FLOAT
+ufunc_gdtr_types[2] = NPY_FLOAT
+ufunc_gdtr_types[3] = NPY_FLOAT
+ufunc_gdtr_types[4] = NPY_DOUBLE
+ufunc_gdtr_types[5] = NPY_DOUBLE
+ufunc_gdtr_types[6] = NPY_DOUBLE
+ufunc_gdtr_types[7] = NPY_DOUBLE
+ufunc_gdtr_ptr[2*0] = _func_xsf_gdtr
+ufunc_gdtr_ptr[2*0+1] = ("gdtr")
+ufunc_gdtr_ptr[2*1] = _func_xsf_gdtr
+ufunc_gdtr_ptr[2*1+1] = ("gdtr")
+ufunc_gdtr_data[0] = &ufunc_gdtr_ptr[2*0]
+ufunc_gdtr_data[1] = &ufunc_gdtr_ptr[2*1]
+gdtr = np.PyUFunc_FromFuncAndData(ufunc_gdtr_loops, ufunc_gdtr_data, ufunc_gdtr_types, 2, 3, 1, 0, "gdtr", ufunc_gdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrc_loops[2]
+cdef void *ufunc_gdtrc_ptr[4]
+cdef void *ufunc_gdtrc_data[2]
+cdef char ufunc_gdtrc_types[8]
+cdef char *ufunc_gdtrc_doc = (
+    "gdtrc(a, b, x, out=None)\n"
+    "\n"
+    "Gamma distribution survival function.\n"
+    "\n"
+    "Integral from `x` to infinity of the gamma probability density function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\int_x^\\infty \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n"
+    "\n"
+    "where :math:`\\Gamma` is the gamma function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    The rate parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\beta` (float). It is also the reciprocal of the scale\n"
+    "    parameter :math:`\\theta`.\n"
+    "b : array_like\n"
+    "    The shape parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\alpha` (float).\n"
+    "x : array_like\n"
+    "    The quantile (lower limit of integration; float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The survival function of the gamma distribution with parameters `a`\n"
+    "    and `b` evaluated at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr: Gamma distribution cumulative distribution function\n"
+    "scipy.stats.gamma: Gamma distribution\n"
+    "gdtrix\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The evaluation is carried out using the relation to the incomplete gamma\n"
+    "integral (regularized gamma function).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can\n"
+    "improve performance compared to the ``sf`` method of `scipy.stats.gamma`\n"
+    "(see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``a=1`` and ``b=2`` at ``x=5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import gdtrc\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> gdtrc(1., 2., 5.)\n"
+    "0.04042768199451279\n"
+    "\n"
+    "Compute the function for ``a=1``, ``b=2`` at several points by providing\n"
+    "a NumPy array for `x`.\n"
+    "\n"
+    ">>> xvalues = np.array([1., 2., 3., 4])\n"
+    ">>> gdtrc(1., 1., xvalues)\n"
+    "array([0.36787944, 0.13533528, 0.04978707, 0.01831564])\n"
+    "\n"
+    "`gdtrc` can evaluate different parameter sets by providing arrays with\n"
+    "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n"
+    "function for three different `a` at four positions `x` and ``b=3``,\n"
+    "resulting in a 3x4 array.\n"
+    "\n"
+    ">>> a = np.array([[0.5], [1.5], [2.5]])\n"
+    ">>> x = np.array([1., 2., 3., 4])\n"
+    ">>> a.shape, x.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> gdtrc(a, 3., x)\n"
+    "array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],\n"
+    "       [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],\n"
+    "       [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> a_parameters = [0.3, 1, 2, 6]\n"
+    ">>> b_parameters = [2, 10, 15, 20]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     a, b, style = parameter_set\n"
+    "...     gdtrc_vals = gdtrc(a, b, x)\n"
+    "...     ax.plot(x, gdtrc_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"Gamma distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The gamma distribution is also available as `scipy.stats.gamma`.\n"
+    "Using `gdtrc` directly can be much faster than calling the ``sf`` method\n"
+    "of `scipy.stats.gamma`, especially for small arrays or individual\n"
+    "values. To get the same results one must use the following parametrization:\n"
+    "``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import gamma\n"
+    ">>> a = 2\n"
+    ">>> b = 3\n"
+    ">>> x = 1.\n"
+    ">>> gdtrc_result = gdtrc(a, b, x)  # this will often be faster than below\n"
+    ">>> gamma_dist_result = gamma(b, scale=1/a).sf(x)\n"
+    ">>> gdtrc_result == gamma_dist_result  # test that results are equal\n"
+    "True")
+ufunc_gdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrc_types[0] = NPY_FLOAT
+ufunc_gdtrc_types[1] = NPY_FLOAT
+ufunc_gdtrc_types[2] = NPY_FLOAT
+ufunc_gdtrc_types[3] = NPY_FLOAT
+ufunc_gdtrc_types[4] = NPY_DOUBLE
+ufunc_gdtrc_types[5] = NPY_DOUBLE
+ufunc_gdtrc_types[6] = NPY_DOUBLE
+ufunc_gdtrc_types[7] = NPY_DOUBLE
+ufunc_gdtrc_ptr[2*0] = _func_xsf_gdtrc
+ufunc_gdtrc_ptr[2*0+1] = ("gdtrc")
+ufunc_gdtrc_ptr[2*1] = _func_xsf_gdtrc
+ufunc_gdtrc_ptr[2*1+1] = ("gdtrc")
+ufunc_gdtrc_data[0] = &ufunc_gdtrc_ptr[2*0]
+ufunc_gdtrc_data[1] = &ufunc_gdtrc_ptr[2*1]
+gdtrc = np.PyUFunc_FromFuncAndData(ufunc_gdtrc_loops, ufunc_gdtrc_data, ufunc_gdtrc_types, 2, 3, 1, 0, "gdtrc", ufunc_gdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtria_loops[2]
+cdef void *ufunc_gdtria_ptr[4]
+cdef void *ufunc_gdtria_data[2]
+cdef char ufunc_gdtria_types[8]
+cdef char *ufunc_gdtria_doc = (
+    "gdtria(p, b, x, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs a.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `a` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "b : array_like\n"
+    "    `b` parameter values of `gdtr(a, b, x)`. `b` is the \"shape\" parameter\n"
+    "    of the gamma distribution.\n"
+    "x : array_like\n"
+    "    Nonnegative real values, from the domain of the gamma distribution.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`.  `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "a : scalar or ndarray\n"
+    "    Values of the `a` parameter such that ``p = gdtr(a, b, x)`.  ``1/a``\n"
+    "    is the \"scale\" parameter of the gamma distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.\n"
+    "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `a`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Computation of the incomplete gamma function ratios and their\n"
+    "       inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtria\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtria(p, 3.4, 5.6)\n"
+    "1.2")
+ufunc_gdtria_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtria_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtria_types[0] = NPY_FLOAT
+ufunc_gdtria_types[1] = NPY_FLOAT
+ufunc_gdtria_types[2] = NPY_FLOAT
+ufunc_gdtria_types[3] = NPY_FLOAT
+ufunc_gdtria_types[4] = NPY_DOUBLE
+ufunc_gdtria_types[5] = NPY_DOUBLE
+ufunc_gdtria_types[6] = NPY_DOUBLE
+ufunc_gdtria_types[7] = NPY_DOUBLE
+ufunc_gdtria_ptr[2*0] = _func_gdtria
+ufunc_gdtria_ptr[2*0+1] = ("gdtria")
+ufunc_gdtria_ptr[2*1] = _func_gdtria
+ufunc_gdtria_ptr[2*1+1] = ("gdtria")
+ufunc_gdtria_data[0] = &ufunc_gdtria_ptr[2*0]
+ufunc_gdtria_data[1] = &ufunc_gdtria_ptr[2*1]
+gdtria = np.PyUFunc_FromFuncAndData(ufunc_gdtria_loops, ufunc_gdtria_data, ufunc_gdtria_types, 2, 3, 1, 0, "gdtria", ufunc_gdtria_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrib_loops[2]
+cdef void *ufunc_gdtrib_ptr[4]
+cdef void *ufunc_gdtrib_data[2]
+cdef char ufunc_gdtrib_types[8]
+cdef char *ufunc_gdtrib_doc = (
+    "gdtrib(a, p, x, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs b.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `b` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the \"scale\"\n"
+    "    parameter of the gamma distribution.\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "x : array_like\n"
+    "    Nonnegative real values, from the domain of the gamma distribution.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`.  `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "b : scalar or ndarray\n"
+    "    Values of the `b` parameter such that `p = gdtr(a, b, x)`.  `b` is\n"
+    "    the \"shape\" parameter of the gamma distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.\n"
+    "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using the Cephes [1]_\n"
+    "routines `igam` and `igamc`. Computation of `b` involves a search for a value\n"
+    "that produces the desired value of `p` using Chandrupatla's bracketing\n"
+    "root finding algorithm [2]_.\n"
+    "\n"
+    "Note that there are some edge cases where `gdtrib` is extended by taking\n"
+    "limits where they are uniquely defined. In particular\n"
+    "``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.\n"
+    "For these edge cases, a numerical result will be returned for\n"
+    "``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is\n"
+    "undefined.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [2] Chandrupatla, Tirupathi R.\n"
+    "       \"A new hybrid quadratic/bisection algorithm for finding the zero of a\n"
+    "       nonlinear function without using derivatives\".\n"
+    "       Advances in Engineering Software, 28(3), 145-149.\n"
+    "       https://doi.org/10.1016/s0965-9978(96)00051-8\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtrib\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtrib(1.2, p, 5.6)\n"
+    "3.3999999999999995")
+ufunc_gdtrib_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrib_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrib_types[0] = NPY_FLOAT
+ufunc_gdtrib_types[1] = NPY_FLOAT
+ufunc_gdtrib_types[2] = NPY_FLOAT
+ufunc_gdtrib_types[3] = NPY_FLOAT
+ufunc_gdtrib_types[4] = NPY_DOUBLE
+ufunc_gdtrib_types[5] = NPY_DOUBLE
+ufunc_gdtrib_types[6] = NPY_DOUBLE
+ufunc_gdtrib_types[7] = NPY_DOUBLE
+ufunc_gdtrib_ptr[2*0] = _func_xsf_gdtrib
+ufunc_gdtrib_ptr[2*0+1] = ("gdtrib")
+ufunc_gdtrib_ptr[2*1] = _func_xsf_gdtrib
+ufunc_gdtrib_ptr[2*1+1] = ("gdtrib")
+ufunc_gdtrib_data[0] = &ufunc_gdtrib_ptr[2*0]
+ufunc_gdtrib_data[1] = &ufunc_gdtrib_ptr[2*1]
+gdtrib = np.PyUFunc_FromFuncAndData(ufunc_gdtrib_loops, ufunc_gdtrib_data, ufunc_gdtrib_types, 2, 3, 1, 0, "gdtrib", ufunc_gdtrib_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrix_loops[2]
+cdef void *ufunc_gdtrix_ptr[4]
+cdef void *ufunc_gdtrix_data[2]
+cdef char ufunc_gdtrix_types[8]
+cdef char *ufunc_gdtrix_doc = (
+    "gdtrix(a, b, p, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs x.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `x` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution. This is also known as the pth quantile of the\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the \"scale\"\n"
+    "    parameter of the gamma distribution.\n"
+    "b : array_like\n"
+    "    `b` parameter values of ``gdtr(a, b, x)``. `b` is the \"shape\" parameter\n"
+    "    of the gamma distribution.\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`. `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Values of the `x` parameter such that `p = gdtr(a, b, x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.\n"
+    "gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `x` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `x`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Computation of the incomplete gamma function ratios and their\n"
+    "       inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtrix\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtrix(1.2, 3.4, p)\n"
+    "5.5999999999999996")
+ufunc_gdtrix_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrix_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrix_types[0] = NPY_FLOAT
+ufunc_gdtrix_types[1] = NPY_FLOAT
+ufunc_gdtrix_types[2] = NPY_FLOAT
+ufunc_gdtrix_types[3] = NPY_FLOAT
+ufunc_gdtrix_types[4] = NPY_DOUBLE
+ufunc_gdtrix_types[5] = NPY_DOUBLE
+ufunc_gdtrix_types[6] = NPY_DOUBLE
+ufunc_gdtrix_types[7] = NPY_DOUBLE
+ufunc_gdtrix_ptr[2*0] = _func_gdtrix
+ufunc_gdtrix_ptr[2*0+1] = ("gdtrix")
+ufunc_gdtrix_ptr[2*1] = _func_gdtrix
+ufunc_gdtrix_ptr[2*1+1] = ("gdtrix")
+ufunc_gdtrix_data[0] = &ufunc_gdtrix_ptr[2*0]
+ufunc_gdtrix_data[1] = &ufunc_gdtrix_ptr[2*1]
+gdtrix = np.PyUFunc_FromFuncAndData(ufunc_gdtrix_loops, ufunc_gdtrix_data, ufunc_gdtrix_types, 2, 3, 1, 0, "gdtrix", ufunc_gdtrix_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_huber_loops[2]
+cdef void *ufunc_huber_ptr[4]
+cdef void *ufunc_huber_data[2]
+cdef char ufunc_huber_types[6]
+cdef char *ufunc_huber_doc = (
+    "huber(delta, r, out=None)\n"
+    "\n"
+    "Huber loss function.\n"
+    "\n"
+    ".. math:: \\text{huber}(\\delta, r) = \\begin{cases} \\infty & \\delta < 0  \\\\\n"
+    "          \\frac{1}{2}r^2 & 0 \\le \\delta, | r | \\le \\delta \\\\\n"
+    "          \\delta ( |r| - \\frac{1}{2}\\delta ) & \\text{otherwise} \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "delta : ndarray\n"
+    "    Input array, indicating the quadratic vs. linear loss changepoint.\n"
+    "r : ndarray\n"
+    "    Input array, possibly representing residuals.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The computed Huber loss function values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pseudo_huber : smooth approximation of this function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`huber` is useful as a loss function in robust statistics or machine\n"
+    "learning to reduce the influence of outliers as compared to the common\n"
+    "squared error loss, residuals with a magnitude higher than `delta` are\n"
+    "not squared [1]_.\n"
+    "\n"
+    "Typically, `r` represents residuals, the difference\n"
+    "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n"
+    "`huber` resembles the squared error and for :math:`|r|>\\delta` the\n"
+    "absolute error. This way, the Huber loss often achieves\n"
+    "a fast convergence in model fitting for small residuals like the squared\n"
+    "error loss function and still reduces the influence of outliers\n"
+    "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n"
+    "the cutoff between squared and absolute error regimes, it has\n"
+    "to be tuned carefully for each problem. `huber` is also\n"
+    "convex, making it suitable for gradient based optimization.\n"
+    "\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Peter Huber. \"Robust Estimation of a Location Parameter\",\n"
+    "       1964. Annals of Statistics. 53 (1): 73 - 101.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Import all necessary modules.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import huber\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Compute the function for ``delta=1`` at ``r=2``\n"
+    "\n"
+    ">>> huber(1., 2.)\n"
+    "1.5\n"
+    "\n"
+    "Compute the function for different `delta` by providing a NumPy array or\n"
+    "list for `delta`.\n"
+    "\n"
+    ">>> huber([1., 3., 5.], 4.)\n"
+    "array([3.5, 7.5, 8. ])\n"
+    "\n"
+    "Compute the function at different points by providing a NumPy array or\n"
+    "list for `r`.\n"
+    "\n"
+    ">>> huber(2., np.array([1., 1.5, 3.]))\n"
+    "array([0.5  , 1.125, 4.   ])\n"
+    "\n"
+    "The function can be calculated for different `delta` and `r` by\n"
+    "providing arrays for both with compatible shapes for broadcasting.\n"
+    "\n"
+    ">>> r = np.array([1., 2.5, 8., 10.])\n"
+    ">>> deltas = np.array([[1.], [5.], [9.]])\n"
+    ">>> print(r.shape, deltas.shape)\n"
+    "(4,) (3, 1)\n"
+    "\n"
+    ">>> huber(deltas, r)\n"
+    "array([[ 0.5  ,  2.   ,  7.5  ,  9.5  ],\n"
+    "       [ 0.5  ,  3.125, 27.5  , 37.5  ],\n"
+    "       [ 0.5  ,  3.125, 32.   , 49.5  ]])\n"
+    "\n"
+    "Plot the function for different `delta`.\n"
+    "\n"
+    ">>> x = np.linspace(-4, 4, 500)\n"
+    ">>> deltas = [1, 2, 3]\n"
+    ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n"
+    ">>> for delta, style in combined_plot_parameters:\n"
+    "...     ax.plot(x, huber(delta, x), label=fr\"$\\delta={delta}$\", ls=style)\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(r\"Huber loss function $h_{\\delta}(x)$\")\n"
+    ">>> ax.set_xlim(-4, 4)\n"
+    ">>> ax.set_ylim(0, 8)\n"
+    ">>> plt.show()")
+ufunc_huber_loops[0] = loop_d_dd__As_ff_f
+ufunc_huber_loops[1] = loop_d_dd__As_dd_d
+ufunc_huber_types[0] = NPY_FLOAT
+ufunc_huber_types[1] = NPY_FLOAT
+ufunc_huber_types[2] = NPY_FLOAT
+ufunc_huber_types[3] = NPY_DOUBLE
+ufunc_huber_types[4] = NPY_DOUBLE
+ufunc_huber_types[5] = NPY_DOUBLE
+ufunc_huber_ptr[2*0] = _func_huber
+ufunc_huber_ptr[2*0+1] = ("huber")
+ufunc_huber_ptr[2*1] = _func_huber
+ufunc_huber_ptr[2*1+1] = ("huber")
+ufunc_huber_data[0] = &ufunc_huber_ptr[2*0]
+ufunc_huber_data[1] = &ufunc_huber_ptr[2*1]
+huber = np.PyUFunc_FromFuncAndData(ufunc_huber_loops, ufunc_huber_data, ufunc_huber_types, 2, 2, 1, 0, "huber", ufunc_huber_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyp0f1_loops[4]
+cdef void *ufunc_hyp0f1_ptr[8]
+cdef void *ufunc_hyp0f1_data[4]
+cdef char ufunc_hyp0f1_types[12]
+cdef char *ufunc_hyp0f1_doc = (
+    "hyp0f1(v, z, out=None)\n"
+    "\n"
+    "Confluent hypergeometric limit function 0F1.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Real-valued parameter\n"
+    "z : array_like\n"
+    "    Real- or complex-valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The confluent hypergeometric limit function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function is defined as:\n"
+    "\n"
+    ".. math:: _0F_1(v, z) = \\sum_{k=0}^{\\infty}\\frac{z^k}{(v)_k k!}.\n"
+    "\n"
+    "It's also the limit as :math:`q \\to \\infty` of :math:`_1F_1(q; v; z/q)`,\n"
+    "and satisfies the differential equation :math:`f''(z) + vf'(z) =\n"
+    "f(z)`. See [1]_ for more information.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Wolfram MathWorld, \"Confluent Hypergeometric Limit Function\",\n"
+    "       http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is one when `z` is zero.\n"
+    "\n"
+    ">>> sc.hyp0f1(1, 0)\n"
+    "1.0\n"
+    "\n"
+    "It is the limit of the confluent hypergeometric function as `q`\n"
+    "goes to infinity.\n"
+    "\n"
+    ">>> q = np.array([1, 10, 100, 1000])\n"
+    ">>> v = 1\n"
+    ">>> z = 1\n"
+    ">>> sc.hyp1f1(q, v, z / q)\n"
+    "array([2.71828183, 2.31481985, 2.28303778, 2.27992985])\n"
+    ">>> sc.hyp0f1(v, z)\n"
+    "2.2795853023360673\n"
+    "\n"
+    "It is related to Bessel functions.\n"
+    "\n"
+    ">>> n = 1\n"
+    ">>> x = np.linspace(0, 1, 5)\n"
+    ">>> sc.jv(n, x)\n"
+    "array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])\n"
+    ">>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)\n"
+    "array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])")
+ufunc_hyp0f1_loops[0] = loop_d_dd__As_ff_f
+ufunc_hyp0f1_loops[1] = loop_D_dD__As_fF_F
+ufunc_hyp0f1_loops[2] = loop_d_dd__As_dd_d
+ufunc_hyp0f1_loops[3] = loop_D_dD__As_dD_D
+ufunc_hyp0f1_types[0] = NPY_FLOAT
+ufunc_hyp0f1_types[1] = NPY_FLOAT
+ufunc_hyp0f1_types[2] = NPY_FLOAT
+ufunc_hyp0f1_types[3] = NPY_FLOAT
+ufunc_hyp0f1_types[4] = NPY_CFLOAT
+ufunc_hyp0f1_types[5] = NPY_CFLOAT
+ufunc_hyp0f1_types[6] = NPY_DOUBLE
+ufunc_hyp0f1_types[7] = NPY_DOUBLE
+ufunc_hyp0f1_types[8] = NPY_DOUBLE
+ufunc_hyp0f1_types[9] = NPY_DOUBLE
+ufunc_hyp0f1_types[10] = NPY_CDOUBLE
+ufunc_hyp0f1_types[11] = NPY_CDOUBLE
+ufunc_hyp0f1_ptr[2*0] = _func__hyp0f1_real
+ufunc_hyp0f1_ptr[2*0+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*1] = _func__hyp0f1_cmplx
+ufunc_hyp0f1_ptr[2*1+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*2] = _func__hyp0f1_real
+ufunc_hyp0f1_ptr[2*2+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*3] = _func__hyp0f1_cmplx
+ufunc_hyp0f1_ptr[2*3+1] = ("hyp0f1")
+ufunc_hyp0f1_data[0] = &ufunc_hyp0f1_ptr[2*0]
+ufunc_hyp0f1_data[1] = &ufunc_hyp0f1_ptr[2*1]
+ufunc_hyp0f1_data[2] = &ufunc_hyp0f1_ptr[2*2]
+ufunc_hyp0f1_data[3] = &ufunc_hyp0f1_ptr[2*3]
+hyp0f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp0f1_loops, ufunc_hyp0f1_data, ufunc_hyp0f1_types, 4, 2, 1, 0, "hyp0f1", ufunc_hyp0f1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyp1f1_loops[4]
+cdef void *ufunc_hyp1f1_ptr[8]
+cdef void *ufunc_hyp1f1_data[4]
+cdef char ufunc_hyp1f1_types[16]
+cdef char *ufunc_hyp1f1_doc = (
+    "hyp1f1(a, b, x, out=None)\n"
+    "\n"
+    "Confluent hypergeometric function 1F1.\n"
+    "\n"
+    "The confluent hypergeometric function is defined by the series\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   {}_1F_1(a; b; x) = \\sum_{k = 0}^\\infty \\frac{(a)_k}{(b)_k k!} x^k.\n"
+    "\n"
+    "See [dlmf]_ for more details. Here :math:`(\\cdot)_k` is the\n"
+    "Pochhammer symbol; see `poch`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real parameters\n"
+    "x : array_like\n"
+    "    Real or complex argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the confluent hypergeometric function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "hyperu : another confluent hypergeometric function\n"
+    "hyp0f1 : confluent hypergeometric limit function\n"
+    "hyp2f1 : Gaussian hypergeometric function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real values, this function uses the ``hyp1f1`` routine from the C++ Boost\n"
+    "library [2]_, for complex values a C translation of the specfun\n"
+    "Fortran library [3]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] NIST Digital Library of Mathematical Functions\n"
+    "          https://dlmf.nist.gov/13.2#E2\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    ".. [3] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n"
+    "       and Sons, Inc, 1996.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is one when `x` is zero:\n"
+    "\n"
+    ">>> sc.hyp1f1(0.5, 0.5, 0)\n"
+    "1.0\n"
+    "\n"
+    "It is singular when `b` is a nonpositive integer.\n"
+    "\n"
+    ">>> sc.hyp1f1(0.5, -1, 0)\n"
+    "inf\n"
+    "\n"
+    "It is a polynomial when `a` is a nonpositive integer.\n"
+    "\n"
+    ">>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])\n"
+    ">>> sc.hyp1f1(a, b, x)\n"
+    "array([-1., -3., -5., -7.])\n"
+    ">>> 1 + (a / b) * x\n"
+    "array([-1., -3., -5., -7.])\n"
+    "\n"
+    "It reduces to the exponential function when ``a = b``.\n"
+    "\n"
+    ">>> sc.hyp1f1(2, 2, [1, 2, 3, 4])\n"
+    "array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])\n"
+    ">>> np.exp([1, 2, 3, 4])\n"
+    "array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])")
+ufunc_hyp1f1_loops[0] = loop_d_ddd__As_fff_f
+ufunc_hyp1f1_loops[1] = loop_D_ddD__As_ffF_F
+ufunc_hyp1f1_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_hyp1f1_loops[3] = loop_D_ddD__As_ddD_D
+ufunc_hyp1f1_types[0] = NPY_FLOAT
+ufunc_hyp1f1_types[1] = NPY_FLOAT
+ufunc_hyp1f1_types[2] = NPY_FLOAT
+ufunc_hyp1f1_types[3] = NPY_FLOAT
+ufunc_hyp1f1_types[4] = NPY_FLOAT
+ufunc_hyp1f1_types[5] = NPY_FLOAT
+ufunc_hyp1f1_types[6] = NPY_CFLOAT
+ufunc_hyp1f1_types[7] = NPY_CFLOAT
+ufunc_hyp1f1_types[8] = NPY_DOUBLE
+ufunc_hyp1f1_types[9] = NPY_DOUBLE
+ufunc_hyp1f1_types[10] = NPY_DOUBLE
+ufunc_hyp1f1_types[11] = NPY_DOUBLE
+ufunc_hyp1f1_types[12] = NPY_DOUBLE
+ufunc_hyp1f1_types[13] = NPY_DOUBLE
+ufunc_hyp1f1_types[14] = NPY_CDOUBLE
+ufunc_hyp1f1_types[15] = NPY_CDOUBLE
+ufunc_hyp1f1_ptr[2*0] = scipy.special._ufuncs_cxx._export_hyp1f1_double
+ufunc_hyp1f1_ptr[2*0+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*1] = _func_chyp1f1_wrap
+ufunc_hyp1f1_ptr[2*1+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*2] = scipy.special._ufuncs_cxx._export_hyp1f1_double
+ufunc_hyp1f1_ptr[2*2+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*3] = _func_chyp1f1_wrap
+ufunc_hyp1f1_ptr[2*3+1] = ("hyp1f1")
+ufunc_hyp1f1_data[0] = &ufunc_hyp1f1_ptr[2*0]
+ufunc_hyp1f1_data[1] = &ufunc_hyp1f1_ptr[2*1]
+ufunc_hyp1f1_data[2] = &ufunc_hyp1f1_ptr[2*2]
+ufunc_hyp1f1_data[3] = &ufunc_hyp1f1_ptr[2*3]
+hyp1f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp1f1_loops, ufunc_hyp1f1_data, ufunc_hyp1f1_types, 4, 3, 1, 0, "hyp1f1", ufunc_hyp1f1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyperu_loops[2]
+cdef void *ufunc_hyperu_ptr[4]
+cdef void *ufunc_hyperu_data[2]
+cdef char ufunc_hyperu_types[8]
+cdef char *ufunc_hyperu_doc = (
+    "hyperu(a, b, x, out=None)\n"
+    "\n"
+    "Confluent hypergeometric function U\n"
+    "\n"
+    "It is defined as the solution to the equation\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   x \\frac{d^2w}{dx^2} + (b - x) \\frac{dw}{dx} - aw = 0\n"
+    "\n"
+    "which satisfies the property\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   U(a, b, x) \\sim x^{-a}\n"
+    "\n"
+    "as :math:`x \\to \\infty`. See [dlmf]_ for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of `U`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] NIST Digital Library of Mathematics Functions\n"
+    "          https://dlmf.nist.gov/13.2#E6\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It has a branch cut along the negative `x` axis.\n"
+    "\n"
+    ">>> x = np.linspace(-0.1, -10, 5)\n"
+    ">>> sc.hyperu(1, 1, x)\n"
+    "array([nan, nan, nan, nan, nan])\n"
+    "\n"
+    "It approaches zero as `x` goes to infinity.\n"
+    "\n"
+    ">>> x = np.array([1, 10, 100])\n"
+    ">>> sc.hyperu(1, 1, x)\n"
+    "array([0.59634736, 0.09156333, 0.00990194])\n"
+    "\n"
+    "It satisfies Kummer's transformation.\n"
+    "\n"
+    ">>> a, b, x = 2, 1, 1\n"
+    ">>> sc.hyperu(a, b, x)\n"
+    "0.1926947246463881\n"
+    ">>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)\n"
+    "0.1926947246463881")
+ufunc_hyperu_loops[0] = loop_d_ddd__As_fff_f
+ufunc_hyperu_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_hyperu_types[0] = NPY_FLOAT
+ufunc_hyperu_types[1] = NPY_FLOAT
+ufunc_hyperu_types[2] = NPY_FLOAT
+ufunc_hyperu_types[3] = NPY_FLOAT
+ufunc_hyperu_types[4] = NPY_DOUBLE
+ufunc_hyperu_types[5] = NPY_DOUBLE
+ufunc_hyperu_types[6] = NPY_DOUBLE
+ufunc_hyperu_types[7] = NPY_DOUBLE
+ufunc_hyperu_ptr[2*0] = _func_hyperu
+ufunc_hyperu_ptr[2*0+1] = ("hyperu")
+ufunc_hyperu_ptr[2*1] = _func_hyperu
+ufunc_hyperu_ptr[2*1+1] = ("hyperu")
+ufunc_hyperu_data[0] = &ufunc_hyperu_ptr[2*0]
+ufunc_hyperu_data[1] = &ufunc_hyperu_ptr[2*1]
+hyperu = np.PyUFunc_FromFuncAndData(ufunc_hyperu_loops, ufunc_hyperu_data, ufunc_hyperu_types, 2, 3, 1, 0, "hyperu", ufunc_hyperu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_inv_boxcox_loops[2]
+cdef void *ufunc_inv_boxcox_ptr[4]
+cdef void *ufunc_inv_boxcox_data[2]
+cdef char ufunc_inv_boxcox_types[6]
+cdef char *ufunc_inv_boxcox_doc = (
+    "inv_boxcox(y, lmbda, out=None)\n"
+    "\n"
+    "Compute the inverse of the Box-Cox transformation.\n"
+    "\n"
+    "Find ``x`` such that::\n"
+    "\n"
+    "    y = (x**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(x)                  if lmbda == 0\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.16.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox, inv_boxcox\n"
+    ">>> y = boxcox([1, 4, 10], 2.5)\n"
+    ">>> inv_boxcox(y, 2.5)\n"
+    "array([1., 4., 10.])")
+ufunc_inv_boxcox_loops[0] = loop_d_dd__As_ff_f
+ufunc_inv_boxcox_loops[1] = loop_d_dd__As_dd_d
+ufunc_inv_boxcox_types[0] = NPY_FLOAT
+ufunc_inv_boxcox_types[1] = NPY_FLOAT
+ufunc_inv_boxcox_types[2] = NPY_FLOAT
+ufunc_inv_boxcox_types[3] = NPY_DOUBLE
+ufunc_inv_boxcox_types[4] = NPY_DOUBLE
+ufunc_inv_boxcox_types[5] = NPY_DOUBLE
+ufunc_inv_boxcox_ptr[2*0] = _func_inv_boxcox
+ufunc_inv_boxcox_ptr[2*0+1] = ("inv_boxcox")
+ufunc_inv_boxcox_ptr[2*1] = _func_inv_boxcox
+ufunc_inv_boxcox_ptr[2*1+1] = ("inv_boxcox")
+ufunc_inv_boxcox_data[0] = &ufunc_inv_boxcox_ptr[2*0]
+ufunc_inv_boxcox_data[1] = &ufunc_inv_boxcox_ptr[2*1]
+inv_boxcox = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox_loops, ufunc_inv_boxcox_data, ufunc_inv_boxcox_types, 2, 2, 1, 0, "inv_boxcox", ufunc_inv_boxcox_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_inv_boxcox1p_loops[2]
+cdef void *ufunc_inv_boxcox1p_ptr[4]
+cdef void *ufunc_inv_boxcox1p_data[2]
+cdef char ufunc_inv_boxcox1p_types[6]
+cdef char *ufunc_inv_boxcox1p_doc = (
+    "inv_boxcox1p(y, lmbda, out=None)\n"
+    "\n"
+    "Compute the inverse of the Box-Cox transformation.\n"
+    "\n"
+    "Find ``x`` such that::\n"
+    "\n"
+    "    y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(1+x)                    if lmbda == 0\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.16.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox1p, inv_boxcox1p\n"
+    ">>> y = boxcox1p([1, 4, 10], 2.5)\n"
+    ">>> inv_boxcox1p(y, 2.5)\n"
+    "array([1., 4., 10.])")
+ufunc_inv_boxcox1p_loops[0] = loop_d_dd__As_ff_f
+ufunc_inv_boxcox1p_loops[1] = loop_d_dd__As_dd_d
+ufunc_inv_boxcox1p_types[0] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[1] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[2] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[3] = NPY_DOUBLE
+ufunc_inv_boxcox1p_types[4] = NPY_DOUBLE
+ufunc_inv_boxcox1p_types[5] = NPY_DOUBLE
+ufunc_inv_boxcox1p_ptr[2*0] = _func_inv_boxcox1p
+ufunc_inv_boxcox1p_ptr[2*0+1] = ("inv_boxcox1p")
+ufunc_inv_boxcox1p_ptr[2*1] = _func_inv_boxcox1p
+ufunc_inv_boxcox1p_ptr[2*1+1] = ("inv_boxcox1p")
+ufunc_inv_boxcox1p_data[0] = &ufunc_inv_boxcox1p_ptr[2*0]
+ufunc_inv_boxcox1p_data[1] = &ufunc_inv_boxcox1p_ptr[2*1]
+inv_boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox1p_loops, ufunc_inv_boxcox1p_data, ufunc_inv_boxcox1p_types, 2, 2, 1, 0, "inv_boxcox1p", ufunc_inv_boxcox1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kl_div_loops[2]
+cdef void *ufunc_kl_div_ptr[4]
+cdef void *ufunc_kl_div_data[2]
+cdef char ufunc_kl_div_types[6]
+cdef char *ufunc_kl_div_doc = (
+    "kl_div(x, y, out=None)\n"
+    "\n"
+    "Elementwise function for computing Kullback-Leibler divergence.\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\mathrm{kl\\_div}(x, y) =\n"
+    "      \\begin{cases}\n"
+    "        x \\log(x / y) - x + y & x > 0, y > 0 \\\\\n"
+    "        y & x = 0, y \\ge 0 \\\\\n"
+    "        \\infty & \\text{otherwise}\n"
+    "      \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Real arguments\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Kullback-Liebler divergence.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "entr, rel_entr, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is non-negative and is jointly convex in `x` and `y`.\n"
+    "\n"
+    "The origin of this function is in convex programming; see [1]_ for\n"
+    "details. This is why the function contains the extra :math:`-x\n"
+    "+ y` terms over what might be expected from the Kullback-Leibler\n"
+    "divergence. For a version of the function without the extra terms,\n"
+    "see `rel_entr`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`")
+ufunc_kl_div_loops[0] = loop_d_dd__As_ff_f
+ufunc_kl_div_loops[1] = loop_d_dd__As_dd_d
+ufunc_kl_div_types[0] = NPY_FLOAT
+ufunc_kl_div_types[1] = NPY_FLOAT
+ufunc_kl_div_types[2] = NPY_FLOAT
+ufunc_kl_div_types[3] = NPY_DOUBLE
+ufunc_kl_div_types[4] = NPY_DOUBLE
+ufunc_kl_div_types[5] = NPY_DOUBLE
+ufunc_kl_div_ptr[2*0] = _func_kl_div
+ufunc_kl_div_ptr[2*0+1] = ("kl_div")
+ufunc_kl_div_ptr[2*1] = _func_kl_div
+ufunc_kl_div_ptr[2*1+1] = ("kl_div")
+ufunc_kl_div_data[0] = &ufunc_kl_div_ptr[2*0]
+ufunc_kl_div_data[1] = &ufunc_kl_div_ptr[2*1]
+kl_div = np.PyUFunc_FromFuncAndData(ufunc_kl_div_loops, ufunc_kl_div_data, ufunc_kl_div_types, 2, 2, 1, 0, "kl_div", ufunc_kl_div_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kn_loops[3]
+cdef void *ufunc_kn_ptr[6]
+cdef void *ufunc_kn_data[3]
+cdef char ufunc_kn_types[9]
+cdef char *ufunc_kn_doc = (
+    "kn(n, x, out=None)\n"
+    "\n"
+    "Modified Bessel function of the second kind of integer order `n`\n"
+    "\n"
+    "Returns the modified Bessel function of the second kind for integer order\n"
+    "`n` at real `z`.\n"
+    "\n"
+    "These are also sometimes called functions of the third kind, Basset\n"
+    "functions, or Macdonald functions.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like of int\n"
+    "    Order of Bessel functions (floats will truncate with a warning)\n"
+    "x : array_like of float\n"
+    "    Argument at which to evaluate the Bessel functions\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Modified Bessel function of the second kind,\n"
+    "    :math:`K_n(x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kv : Same function, but accepts real order and complex argument\n"
+    "kvp : Derivative of this function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the\n"
+    "algorithm used, see [2]_ and the references therein.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Donald E. Amos, \"AMOS, A Portable Package for Bessel Functions\n"
+    "       of a Complex Argument and Nonnegative Order\",\n"
+    "       http://netlib.org/amos/\n"
+    ".. [2] Donald E. Amos, \"Algorithm 644: A portable package for Bessel\n"
+    "       functions of a complex argument and nonnegative order\", ACM\n"
+    "       TOMS Vol. 12 Issue 3, Sept. 1986, p. 265\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Plot the function of several orders for real input:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import kn\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(0, 5, 1000)\n"
+    ">>> for N in range(6):\n"
+    "...     plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))\n"
+    ">>> plt.ylim(0, 10)\n"
+    ">>> plt.legend()\n"
+    ">>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Calculate for a single value at multiple orders:\n"
+    "\n"
+    ">>> kn([4, 5, 6], 1)\n"
+    "array([   44.23241585,   360.9605896 ,  3653.83831186])")
+ufunc_kn_loops[0] = loop_d_pd__As_pd_d
+ufunc_kn_loops[1] = loop_d_dd__As_ff_f
+ufunc_kn_loops[2] = loop_d_dd__As_dd_d
+ufunc_kn_types[0] = NPY_INTP
+ufunc_kn_types[1] = NPY_DOUBLE
+ufunc_kn_types[2] = NPY_DOUBLE
+ufunc_kn_types[3] = NPY_FLOAT
+ufunc_kn_types[4] = NPY_FLOAT
+ufunc_kn_types[5] = NPY_FLOAT
+ufunc_kn_types[6] = NPY_DOUBLE
+ufunc_kn_types[7] = NPY_DOUBLE
+ufunc_kn_types[8] = NPY_DOUBLE
+ufunc_kn_ptr[2*0] = _func_special_cyl_bessel_k_int
+ufunc_kn_ptr[2*0+1] = ("kn")
+ufunc_kn_ptr[2*1] = _func_kn_unsafe
+ufunc_kn_ptr[2*1+1] = ("kn")
+ufunc_kn_ptr[2*2] = _func_kn_unsafe
+ufunc_kn_ptr[2*2+1] = ("kn")
+ufunc_kn_data[0] = &ufunc_kn_ptr[2*0]
+ufunc_kn_data[1] = &ufunc_kn_ptr[2*1]
+ufunc_kn_data[2] = &ufunc_kn_ptr[2*2]
+kn = np.PyUFunc_FromFuncAndData(ufunc_kn_loops, ufunc_kn_data, ufunc_kn_types, 3, 2, 1, 0, "kn", ufunc_kn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kolmogi_loops[2]
+cdef void *ufunc_kolmogi_ptr[4]
+cdef void *ufunc_kolmogi_data[2]
+cdef char ufunc_kolmogi_types[4]
+cdef char *ufunc_kolmogi_doc = (
+    "kolmogi(p, out=None)\n"
+    "\n"
+    "Inverse Survival Function of Kolmogorov distribution\n"
+    "\n"
+    "It is the inverse function to `kolmogorov`.\n"
+    "Returns y such that ``kolmogorov(y) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : float array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of kolmogi(p)\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kolmogorov : The Survival Function for the distribution\n"
+    "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n"
+    "smirnov, smirnovi : Functions for the one-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`kolmogorov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.kstwobign` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import kolmogi\n"
+    ">>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])\n"
+    "array([        inf,  1.22384787,  1.01918472,  0.82757356,  0.67644769,\n"
+    "        0.57117327,  0.        ])")
+ufunc_kolmogi_loops[0] = loop_d_d__As_f_f
+ufunc_kolmogi_loops[1] = loop_d_d__As_d_d
+ufunc_kolmogi_types[0] = NPY_FLOAT
+ufunc_kolmogi_types[1] = NPY_FLOAT
+ufunc_kolmogi_types[2] = NPY_DOUBLE
+ufunc_kolmogi_types[3] = NPY_DOUBLE
+ufunc_kolmogi_ptr[2*0] = _func_xsf_kolmogi
+ufunc_kolmogi_ptr[2*0+1] = ("kolmogi")
+ufunc_kolmogi_ptr[2*1] = _func_xsf_kolmogi
+ufunc_kolmogi_ptr[2*1+1] = ("kolmogi")
+ufunc_kolmogi_data[0] = &ufunc_kolmogi_ptr[2*0]
+ufunc_kolmogi_data[1] = &ufunc_kolmogi_ptr[2*1]
+kolmogi = np.PyUFunc_FromFuncAndData(ufunc_kolmogi_loops, ufunc_kolmogi_data, ufunc_kolmogi_types, 2, 1, 1, 0, "kolmogi", ufunc_kolmogi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kolmogorov_loops[2]
+cdef void *ufunc_kolmogorov_ptr[4]
+cdef void *ufunc_kolmogorov_data[2]
+cdef char ufunc_kolmogorov_types[4]
+cdef char *ufunc_kolmogorov_doc = (
+    "kolmogorov(y, out=None)\n"
+    "\n"
+    "Complementary cumulative distribution (Survival Function) function of\n"
+    "Kolmogorov distribution.\n"
+    "\n"
+    "Returns the complementary cumulative distribution function of\n"
+    "Kolmogorov's limiting distribution (``D_n*\\sqrt(n)`` as n goes to infinity)\n"
+    "of a two-sided test for equality between an empirical and a theoretical\n"
+    "distribution. It is equal to the (limit as n->infinity of the)\n"
+    "probability that ``sqrt(n) * max absolute deviation > y``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : float array_like\n"
+    "  Absolute deviation between the Empirical CDF (ECDF) and the target CDF,\n"
+    "  multiplied by sqrt(n).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of kolmogorov(y)\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kolmogi : The Inverse Survival Function for the distribution\n"
+    "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n"
+    "smirnov, smirnovi : Functions for the one-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`kolmogorov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.kstwobign` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Show the probability of a gap at least as big as 0, 0.5 and 1.0.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import kolmogorov\n"
+    ">>> from scipy.stats import kstwobign\n"
+    ">>> kolmogorov([0, 0.5, 1.0])\n"
+    "array([ 1.        ,  0.96394524,  0.26999967])\n"
+    "\n"
+    "Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against\n"
+    "the target distribution, a Normal(0, 1) distribution.\n"
+    "\n"
+    ">>> from scipy.stats import norm, laplace\n"
+    ">>> rng = np.random.default_rng()\n"
+    ">>> n = 1000\n"
+    ">>> lap01 = laplace(0, 1)\n"
+    ">>> x = np.sort(lap01.rvs(n, random_state=rng))\n"
+    ">>> np.mean(x), np.std(x)\n"
+    "(-0.05841730131499543, 1.3968109101997568)\n"
+    "\n"
+    "Construct the Empirical CDF and the K-S statistic Dn.\n"
+    "\n"
+    ">>> target = norm(0,1)  # Normal mean 0, stddev 1\n"
+    ">>> cdfs = target.cdf(x)\n"
+    ">>> ecdfs = np.arange(n+1, dtype=float)/n\n"
+    ">>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])\n"
+    ">>> Dn = np.max(gaps)\n"
+    ">>> Kn = np.sqrt(n) * Dn\n"
+    ">>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))\n"
+    "Dn=0.043363, sqrt(n)*Dn=1.371265\n"
+    ">>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',\n"
+    "...   ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %\n"
+    "...    (Kn, kolmogorov(Kn)),\n"
+    "...   ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %\n"
+    "...    (Kn, kstwobign.cdf(Kn))]))\n"
+    "For a sample of size n drawn from a N(0, 1) distribution:\n"
+    " the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533\n"
+    " the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467\n"
+    "\n"
+    "Plot the Empirical CDF against the target N(0, 1) CDF.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')\n"
+    ">>> x3 = np.linspace(-3, 3, 100)\n"
+    ">>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')\n"
+    ">>> plt.ylim([0, 1]); plt.grid(True); plt.legend();\n"
+    ">>> # Add vertical lines marking Dn+ and Dn-\n"
+    ">>> iminus, iplus = np.argmax(gaps, axis=0)\n"
+    ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],\n"
+    "...            color='r', linestyle='dashed', lw=4)\n"
+    ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],\n"
+    "...            color='r', linestyle='dashed', lw=4)\n"
+    ">>> plt.show()")
+ufunc_kolmogorov_loops[0] = loop_d_d__As_f_f
+ufunc_kolmogorov_loops[1] = loop_d_d__As_d_d
+ufunc_kolmogorov_types[0] = NPY_FLOAT
+ufunc_kolmogorov_types[1] = NPY_FLOAT
+ufunc_kolmogorov_types[2] = NPY_DOUBLE
+ufunc_kolmogorov_types[3] = NPY_DOUBLE
+ufunc_kolmogorov_ptr[2*0] = _func_xsf_kolmogorov
+ufunc_kolmogorov_ptr[2*0+1] = ("kolmogorov")
+ufunc_kolmogorov_ptr[2*1] = _func_xsf_kolmogorov
+ufunc_kolmogorov_ptr[2*1+1] = ("kolmogorov")
+ufunc_kolmogorov_data[0] = &ufunc_kolmogorov_ptr[2*0]
+ufunc_kolmogorov_data[1] = &ufunc_kolmogorov_ptr[2*1]
+kolmogorov = np.PyUFunc_FromFuncAndData(ufunc_kolmogorov_loops, ufunc_kolmogorov_data, ufunc_kolmogorov_types, 2, 1, 1, 0, "kolmogorov", ufunc_kolmogorov_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_log1p_loops[4]
+cdef void *ufunc_log1p_ptr[8]
+cdef void *ufunc_log1p_data[4]
+cdef char ufunc_log1p_types[8]
+cdef char *ufunc_log1p_doc = (
+    "log1p(x, out=None)\n"
+    "\n"
+    "Calculates log(1 + x) for use when `x` is near zero.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of ``log(1 + x)``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "expm1, cosm1\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is more accurate than using ``log(1 + x)`` directly for ``x``\n"
+    "near 0. Note that in the below example ``1 + 1e-17 == 1`` to\n"
+    "double precision.\n"
+    "\n"
+    ">>> sc.log1p(1e-17)\n"
+    "1e-17\n"
+    ">>> np.log(1 + 1e-17)\n"
+    "0.0")
+ufunc_log1p_loops[0] = loop_d_d__As_f_f
+ufunc_log1p_loops[1] = loop_d_d__As_d_d
+ufunc_log1p_loops[2] = loop_D_D__As_F_F
+ufunc_log1p_loops[3] = loop_D_D__As_D_D
+ufunc_log1p_types[0] = NPY_FLOAT
+ufunc_log1p_types[1] = NPY_FLOAT
+ufunc_log1p_types[2] = NPY_DOUBLE
+ufunc_log1p_types[3] = NPY_DOUBLE
+ufunc_log1p_types[4] = NPY_CFLOAT
+ufunc_log1p_types[5] = NPY_CFLOAT
+ufunc_log1p_types[6] = NPY_CDOUBLE
+ufunc_log1p_types[7] = NPY_CDOUBLE
+ufunc_log1p_ptr[2*0] = _func_cephes_log1p
+ufunc_log1p_ptr[2*0+1] = ("log1p")
+ufunc_log1p_ptr[2*1] = _func_cephes_log1p
+ufunc_log1p_ptr[2*1+1] = ("log1p")
+ufunc_log1p_ptr[2*2] = _func_clog1p
+ufunc_log1p_ptr[2*2+1] = ("log1p")
+ufunc_log1p_ptr[2*3] = _func_clog1p
+ufunc_log1p_ptr[2*3+1] = ("log1p")
+ufunc_log1p_data[0] = &ufunc_log1p_ptr[2*0]
+ufunc_log1p_data[1] = &ufunc_log1p_ptr[2*1]
+ufunc_log1p_data[2] = &ufunc_log1p_ptr[2*2]
+ufunc_log1p_data[3] = &ufunc_log1p_ptr[2*3]
+log1p = np.PyUFunc_FromFuncAndData(ufunc_log1p_loops, ufunc_log1p_data, ufunc_log1p_types, 4, 1, 1, 0, "log1p", ufunc_log1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_log_ndtr_loops[4]
+cdef void *ufunc_log_ndtr_ptr[8]
+cdef void *ufunc_log_ndtr_data[4]
+cdef char ufunc_log_ndtr_types[8]
+cdef char *ufunc_log_ndtr_doc = (
+    "log_ndtr(x, out=None)\n"
+    "\n"
+    "Logarithm of Gaussian cumulative distribution function.\n"
+    "\n"
+    "Returns the log of the area under the standard Gaussian probability\n"
+    "density function, integrated from minus infinity to `x`::\n"
+    "\n"
+    "    log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like, real or complex\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the log of the normal CDF evaluated at `x`\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf\n"
+    "erfc\n"
+    "scipy.stats.norm\n"
+    "ndtr\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import log_ndtr, ndtr\n"
+    "\n"
+    "The benefit of ``log_ndtr(x)`` over the naive implementation\n"
+    "``np.log(ndtr(x))`` is most evident with moderate to large positive\n"
+    "values of ``x``:\n"
+    "\n"
+    ">>> x = np.array([6, 7, 9, 12, 15, 25])\n"
+    ">>> log_ndtr(x)\n"
+    "array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,\n"
+    "       -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])\n"
+    "\n"
+    "The results of the naive calculation for the moderate ``x`` values\n"
+    "have only 5 or 6 correct significant digits. For values of ``x``\n"
+    "greater than approximately 8.3, the naive expression returns 0:\n"
+    "\n"
+    ">>> np.log(ndtr(x))\n"
+    "array([-9.86587701e-10, -1.27986510e-12,  0.00000000e+00,\n"
+    "        0.00000000e+00,  0.00000000e+00,  0.00000000e+00])")
+ufunc_log_ndtr_loops[0] = loop_d_d__As_f_f
+ufunc_log_ndtr_loops[1] = loop_d_d__As_d_d
+ufunc_log_ndtr_loops[2] = loop_D_D__As_F_F
+ufunc_log_ndtr_loops[3] = loop_D_D__As_D_D
+ufunc_log_ndtr_types[0] = NPY_FLOAT
+ufunc_log_ndtr_types[1] = NPY_FLOAT
+ufunc_log_ndtr_types[2] = NPY_DOUBLE
+ufunc_log_ndtr_types[3] = NPY_DOUBLE
+ufunc_log_ndtr_types[4] = NPY_CFLOAT
+ufunc_log_ndtr_types[5] = NPY_CFLOAT
+ufunc_log_ndtr_types[6] = NPY_CDOUBLE
+ufunc_log_ndtr_types[7] = NPY_CDOUBLE
+ufunc_log_ndtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr
+ufunc_log_ndtr_ptr[2*0+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr
+ufunc_log_ndtr_ptr[2*1+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex
+ufunc_log_ndtr_ptr[2*2+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex
+ufunc_log_ndtr_ptr[2*3+1] = ("log_ndtr")
+ufunc_log_ndtr_data[0] = &ufunc_log_ndtr_ptr[2*0]
+ufunc_log_ndtr_data[1] = &ufunc_log_ndtr_ptr[2*1]
+ufunc_log_ndtr_data[2] = &ufunc_log_ndtr_ptr[2*2]
+ufunc_log_ndtr_data[3] = &ufunc_log_ndtr_ptr[2*3]
+log_ndtr = np.PyUFunc_FromFuncAndData(ufunc_log_ndtr_loops, ufunc_log_ndtr_data, ufunc_log_ndtr_types, 4, 1, 1, 0, "log_ndtr", ufunc_log_ndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_lpmv_loops[2]
+cdef void *ufunc_lpmv_ptr[4]
+cdef void *ufunc_lpmv_data[2]
+cdef char ufunc_lpmv_types[8]
+cdef char *ufunc_lpmv_doc = (
+    "lpmv(m, v, x, out=None)\n"
+    "\n"
+    "Associated Legendre function of integer order and real degree.\n"
+    "\n"
+    "Defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_v^m = (-1)^m (1 - x^2)^{m/2} \\frac{d^m}{dx^m} P_v(x)\n"
+    "\n"
+    "where\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_v = \\sum_{k = 0}^\\infty \\frac{(-v)_k (v + 1)_k}{(k!)^2}\n"
+    "            \\left(\\frac{1 - x}{2}\\right)^k\n"
+    "\n"
+    "is the Legendre function of the first kind. Here :math:`(\\cdot)_k`\n"
+    "is the Pochhammer symbol; see `poch`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "m : array_like\n"
+    "    Order (int or float). If passed a float not equal to an\n"
+    "    integer the function returns NaN.\n"
+    "v : array_like\n"
+    "    Degree (float).\n"
+    "x : array_like\n"
+    "    Argument (float). Must have ``|x| <= 1``.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "pmv : scalar or ndarray\n"
+    "    Value of the associated Legendre function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "lpmn : Compute the associated Legendre function for all orders\n"
+    "       ``0, ..., m`` and degrees ``0, ..., n``.\n"
+    "clpmn : Compute the associated Legendre function at complex\n"
+    "        arguments.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Note that this implementation includes the Condon-Shortley phase.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n"
+    "       and Sons, Inc, 1996.")
+ufunc_lpmv_loops[0] = loop_d_ddd__As_fff_f
+ufunc_lpmv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_lpmv_types[0] = NPY_FLOAT
+ufunc_lpmv_types[1] = NPY_FLOAT
+ufunc_lpmv_types[2] = NPY_FLOAT
+ufunc_lpmv_types[3] = NPY_FLOAT
+ufunc_lpmv_types[4] = NPY_DOUBLE
+ufunc_lpmv_types[5] = NPY_DOUBLE
+ufunc_lpmv_types[6] = NPY_DOUBLE
+ufunc_lpmv_types[7] = NPY_DOUBLE
+ufunc_lpmv_ptr[2*0] = _func_pmv_wrap
+ufunc_lpmv_ptr[2*0+1] = ("lpmv")
+ufunc_lpmv_ptr[2*1] = _func_pmv_wrap
+ufunc_lpmv_ptr[2*1+1] = ("lpmv")
+ufunc_lpmv_data[0] = &ufunc_lpmv_ptr[2*0]
+ufunc_lpmv_data[1] = &ufunc_lpmv_ptr[2*1]
+lpmv = np.PyUFunc_FromFuncAndData(ufunc_lpmv_loops, ufunc_lpmv_data, ufunc_lpmv_types, 2, 3, 1, 0, "lpmv", ufunc_lpmv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtr_loops[3]
+cdef void *ufunc_nbdtr_ptr[6]
+cdef void *ufunc_nbdtr_data[3]
+cdef char ufunc_nbdtr_types[12]
+cdef char *ufunc_nbdtr_doc = (
+    "nbdtr(k, n, p, out=None)\n"
+    "\n"
+    "Negative binomial cumulative distribution function.\n"
+    "\n"
+    "Returns the sum of the terms 0 through `k` of the negative binomial\n"
+    "distribution probability mass function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\sum_{j=0}^k {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n"
+    "\n"
+    "In a sequence of Bernoulli trials with individual success probabilities\n"
+    "`p`, this is the probability that `k` or fewer failures precede the nth\n"
+    "success.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The probability of `k` or fewer failures before `n` successes in a\n"
+    "    sequence of events with individual success probability `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtrc : Negative binomial survival function\n"
+    "nbdtrik : Negative binomial quantile function\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "If floating point values are passed for `k` or `n`, they will be truncated\n"
+    "to integers.\n"
+    "\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtr`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtr` directly can improve performance\n"
+    "compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtr\n"
+    ">>> nbdtr(10, 5, 0.5)\n"
+    "0.940765380859375\n"
+    "\n"
+    "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n"
+    "providing a NumPy array or list for `k`.\n"
+    "\n"
+    ">>> nbdtr([5, 10, 15], 10, 0.5)\n"
+    "array([0.15087891, 0.58809853, 0.88523853])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> k = np.arange(130)\n"
+    ">>> n_parameters = [20, 20, 20, 80]\n"
+    ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtr_vals = nbdtr(k, n, p)\n"
+    "...     ax.plot(k, nbdtr_vals, label=rf\"$n={n},\\, p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$k$\")\n"
+    ">>> ax.set_title(\"Negative binomial cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than\n"
+    "calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small\n"
+    "arrays or individual values. To get the same results one must use the\n"
+    "following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> k, n, p = 5, 3, 0.5\n"
+    ">>> nbdtr_res = nbdtr(k, n, p)  # this will often be faster than below\n"
+    ">>> stats_res = nbinom(n, p).cdf(k)\n"
+    ">>> stats_res, nbdtr_res  # test that results are equal\n"
+    "(0.85546875, 0.85546875)\n"
+    "\n"
+    "`nbdtr` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtr(k, 5, p)\n"
+    "array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],\n"
+    "       [0.48450894, 0.94076538, 0.99932777, 0.99999999],\n"
+    "       [0.76249222, 0.99409103, 0.99999445, 1.        ]])")
+ufunc_nbdtr_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtr_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtr_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtr_types[0] = NPY_INTP
+ufunc_nbdtr_types[1] = NPY_INTP
+ufunc_nbdtr_types[2] = NPY_DOUBLE
+ufunc_nbdtr_types[3] = NPY_DOUBLE
+ufunc_nbdtr_types[4] = NPY_FLOAT
+ufunc_nbdtr_types[5] = NPY_FLOAT
+ufunc_nbdtr_types[6] = NPY_FLOAT
+ufunc_nbdtr_types[7] = NPY_FLOAT
+ufunc_nbdtr_types[8] = NPY_DOUBLE
+ufunc_nbdtr_types[9] = NPY_DOUBLE
+ufunc_nbdtr_types[10] = NPY_DOUBLE
+ufunc_nbdtr_types[11] = NPY_DOUBLE
+ufunc_nbdtr_ptr[2*0] = _func_cephes_nbdtr_wrap
+ufunc_nbdtr_ptr[2*0+1] = ("nbdtr")
+ufunc_nbdtr_ptr[2*1] = _func_nbdtr_unsafe
+ufunc_nbdtr_ptr[2*1+1] = ("nbdtr")
+ufunc_nbdtr_ptr[2*2] = _func_nbdtr_unsafe
+ufunc_nbdtr_ptr[2*2+1] = ("nbdtr")
+ufunc_nbdtr_data[0] = &ufunc_nbdtr_ptr[2*0]
+ufunc_nbdtr_data[1] = &ufunc_nbdtr_ptr[2*1]
+ufunc_nbdtr_data[2] = &ufunc_nbdtr_ptr[2*2]
+nbdtr = np.PyUFunc_FromFuncAndData(ufunc_nbdtr_loops, ufunc_nbdtr_data, ufunc_nbdtr_types, 3, 3, 1, 0, "nbdtr", ufunc_nbdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrc_loops[3]
+cdef void *ufunc_nbdtrc_ptr[6]
+cdef void *ufunc_nbdtrc_data[3]
+cdef char ufunc_nbdtrc_types[12]
+cdef char *ufunc_nbdtrc_doc = (
+    "nbdtrc(k, n, p, out=None)\n"
+    "\n"
+    "Negative binomial survival function.\n"
+    "\n"
+    "Returns the sum of the terms `k + 1` to infinity of the negative binomial\n"
+    "distribution probability mass function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\sum_{j=k + 1}^\\infty {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n"
+    "\n"
+    "In a sequence of Bernoulli trials with individual success probabilities\n"
+    "`p`, this is the probability that more than `k` failures precede the nth\n"
+    "success.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The probability of `k + 1` or more failures before `n` successes in a\n"
+    "    sequence of events with individual success probability `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Negative binomial cumulative distribution function\n"
+    "nbdtrik : Negative binomial percentile function\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "If floating point values are passed for `k` or `n`, they will be truncated\n"
+    "to integers.\n"
+    "\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtrc`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance\n"
+    "compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtrc\n"
+    ">>> nbdtrc(10, 5, 0.5)\n"
+    "0.059234619140624986\n"
+    "\n"
+    "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n"
+    "providing a NumPy array or list for `k`.\n"
+    "\n"
+    ">>> nbdtrc([5, 10, 15], 10, 0.5)\n"
+    "array([0.84912109, 0.41190147, 0.11476147])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> k = np.arange(130)\n"
+    ">>> n_parameters = [20, 20, 20, 80]\n"
+    ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtrc_vals = nbdtrc(k, n, p)\n"
+    "...     ax.plot(k, nbdtrc_vals, label=rf\"$n={n},\\, p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$k$\")\n"
+    ">>> ax.set_title(\"Negative binomial distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than\n"
+    "calling the ``sf`` method of `scipy.stats.nbinom`, especially for small\n"
+    "arrays or individual values. To get the same results one must use the\n"
+    "following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> k, n, p = 3, 5, 0.5\n"
+    ">>> nbdtr_res = nbdtrc(k, n, p)  # this will often be faster than below\n"
+    ">>> stats_res = nbinom(n, p).sf(k)\n"
+    ">>> stats_res, nbdtr_res  # test that results are equal\n"
+    "(0.6367187499999999, 0.6367187499999999)\n"
+    "\n"
+    "`nbdtrc` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtrc(k, 5, p)\n"
+    "array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],\n"
+    "       [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],\n"
+    "       [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])")
+ufunc_nbdtrc_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtrc_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtrc_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrc_types[0] = NPY_INTP
+ufunc_nbdtrc_types[1] = NPY_INTP
+ufunc_nbdtrc_types[2] = NPY_DOUBLE
+ufunc_nbdtrc_types[3] = NPY_DOUBLE
+ufunc_nbdtrc_types[4] = NPY_FLOAT
+ufunc_nbdtrc_types[5] = NPY_FLOAT
+ufunc_nbdtrc_types[6] = NPY_FLOAT
+ufunc_nbdtrc_types[7] = NPY_FLOAT
+ufunc_nbdtrc_types[8] = NPY_DOUBLE
+ufunc_nbdtrc_types[9] = NPY_DOUBLE
+ufunc_nbdtrc_types[10] = NPY_DOUBLE
+ufunc_nbdtrc_types[11] = NPY_DOUBLE
+ufunc_nbdtrc_ptr[2*0] = _func_cephes_nbdtrc_wrap
+ufunc_nbdtrc_ptr[2*0+1] = ("nbdtrc")
+ufunc_nbdtrc_ptr[2*1] = _func_nbdtrc_unsafe
+ufunc_nbdtrc_ptr[2*1+1] = ("nbdtrc")
+ufunc_nbdtrc_ptr[2*2] = _func_nbdtrc_unsafe
+ufunc_nbdtrc_ptr[2*2+1] = ("nbdtrc")
+ufunc_nbdtrc_data[0] = &ufunc_nbdtrc_ptr[2*0]
+ufunc_nbdtrc_data[1] = &ufunc_nbdtrc_ptr[2*1]
+ufunc_nbdtrc_data[2] = &ufunc_nbdtrc_ptr[2*2]
+nbdtrc = np.PyUFunc_FromFuncAndData(ufunc_nbdtrc_loops, ufunc_nbdtrc_data, ufunc_nbdtrc_types, 3, 3, 1, 0, "nbdtrc", ufunc_nbdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtri_loops[3]
+cdef void *ufunc_nbdtri_ptr[6]
+cdef void *ufunc_nbdtri_data[3]
+cdef char ufunc_nbdtri_types[12]
+cdef char *ufunc_nbdtri_doc = (
+    "nbdtri(k, n, y, out=None)\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `p` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "p : scalar or ndarray\n"
+    "    Probability of success in a single event (float) such that\n"
+    "    `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtrc : Negative binomial survival function.\n"
+    "scipy.stats.nbinom : negative binomial distribution.\n"
+    "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n"
+    "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtri`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtri` directly can improve performance\n"
+    "compared to the ``ppf`` method of `scipy.stats.nbinom`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nbdtri` is the inverse of `nbdtr` with respect to `p`.\n"
+    "Up to floating point errors the following holds:\n"
+    "``nbdtri(k, n, nbdtr(k, n, p))=p``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtri, nbdtr\n"
+    ">>> k, n, y = 5, 10, 0.2\n"
+    ">>> cdf_val = nbdtr(k, n, y)\n"
+    ">>> nbdtri(k, n, cdf_val)\n"
+    "0.20000000000000004\n"
+    "\n"
+    "Compute the function for ``k=10`` and ``n=5`` at several points by\n"
+    "providing a NumPy array or list for `y`.\n"
+    "\n"
+    ">>> y = np.array([0.1, 0.4, 0.8])\n"
+    ">>> nbdtri(3, 5, y)\n"
+    "array([0.34462319, 0.51653095, 0.69677416])\n"
+    "\n"
+    "Plot the function for three different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> n_parameters = [5, 20, 30, 30]\n"
+    ">>> k_parameters = [20, 20, 60, 80]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))\n"
+    ">>> cdf_vals = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     n, k, style = parameter_set\n"
+    "...     nbdtri_vals = nbdtri(k, n, cdf_vals)\n"
+    "...     ax.plot(cdf_vals, nbdtri_vals, label=rf\"$k={k},\\ n={n}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylabel(\"$p$\")\n"
+    ">>> ax.set_xlabel(\"$CDF$\")\n"
+    ">>> title = \"nbdtri: inverse of negative binomial CDF with respect to $p$\"\n"
+    ">>> ax.set_title(title)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "`nbdtri` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> y = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, y.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtri(k, 5, y)\n"
+    "array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],\n"
+    "       [0.24588501, 0.30451981, 0.36778453, 0.46397088],\n"
+    "       [0.18362101, 0.22966758, 0.28054743, 0.36066188]])")
+ufunc_nbdtri_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtri_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtri_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtri_types[0] = NPY_INTP
+ufunc_nbdtri_types[1] = NPY_INTP
+ufunc_nbdtri_types[2] = NPY_DOUBLE
+ufunc_nbdtri_types[3] = NPY_DOUBLE
+ufunc_nbdtri_types[4] = NPY_FLOAT
+ufunc_nbdtri_types[5] = NPY_FLOAT
+ufunc_nbdtri_types[6] = NPY_FLOAT
+ufunc_nbdtri_types[7] = NPY_FLOAT
+ufunc_nbdtri_types[8] = NPY_DOUBLE
+ufunc_nbdtri_types[9] = NPY_DOUBLE
+ufunc_nbdtri_types[10] = NPY_DOUBLE
+ufunc_nbdtri_types[11] = NPY_DOUBLE
+ufunc_nbdtri_ptr[2*0] = _func_cephes_nbdtri_wrap
+ufunc_nbdtri_ptr[2*0+1] = ("nbdtri")
+ufunc_nbdtri_ptr[2*1] = _func_nbdtri_unsafe
+ufunc_nbdtri_ptr[2*1+1] = ("nbdtri")
+ufunc_nbdtri_ptr[2*2] = _func_nbdtri_unsafe
+ufunc_nbdtri_ptr[2*2+1] = ("nbdtri")
+ufunc_nbdtri_data[0] = &ufunc_nbdtri_ptr[2*0]
+ufunc_nbdtri_data[1] = &ufunc_nbdtri_ptr[2*1]
+ufunc_nbdtri_data[2] = &ufunc_nbdtri_ptr[2*2]
+nbdtri = np.PyUFunc_FromFuncAndData(ufunc_nbdtri_loops, ufunc_nbdtri_data, ufunc_nbdtri_types, 3, 3, 1, 0, "nbdtri", ufunc_nbdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrik_loops[2]
+cdef void *ufunc_nbdtrik_ptr[4]
+cdef void *ufunc_nbdtrik_data[2]
+cdef char ufunc_nbdtrik_types[8]
+cdef char *ufunc_nbdtrik_doc = (
+    "nbdtrik(y, n, p, out=None)\n"
+    "\n"
+    "Negative binomial percentile function.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `k` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "k : scalar or ndarray\n"
+    "    The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtrc : Survival function of the negative binomial.\n"
+    "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n"
+    "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n"
+    "\n"
+    "Formula 26.5.26 of [2]_,\n"
+    "\n"
+    ".. math::\n"
+    "    \\sum_{j=k + 1}^\\infty {{n + j - 1}\n"
+    "    \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n"
+    "\n"
+    "is used to reduce calculation of the cumulative distribution function to\n"
+    "that of a regularized incomplete beta :math:`I`.\n"
+    "\n"
+    "Computation of `k` involves a search for a value that produces the desired\n"
+    "value of `y`.  The search relies on the monotonicity of `y` with `k`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the negative binomial cumulative distribution function for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtr, nbdtrik\n"
+    ">>> k, n, p = 5, 2, 0.5\n"
+    ">>> cdf_value = nbdtr(k, n, p)\n"
+    ">>> cdf_value\n"
+    "0.9375\n"
+    "\n"
+    "Verify that `nbdtrik` recovers the original value for `k`.\n"
+    "\n"
+    ">>> nbdtrik(cdf_value, n, p)\n"
+    "5.0\n"
+    "\n"
+    "Plot the function for different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> p_parameters = [0.2, 0.5, 0.7, 0.5]\n"
+    ">>> n_parameters = [30, 30, 30, 80]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))\n"
+    ">>> cdf_vals = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtrik_vals = nbdtrik(cdf_vals, n, p)\n"
+    "...     ax.plot(cdf_vals, nbdtrik_vals, label=rf\"$n={n},\\ p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylabel(\"$k$\")\n"
+    ">>> ax.set_xlabel(\"$CDF$\")\n"
+    ">>> ax.set_title(\"Negative binomial percentile function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. The percentile function  method ``ppf``\n"
+    "returns the result of `nbdtrik` rounded up to integers:\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> q, n, p = 0.6, 5, 0.5\n"
+    ">>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)\n"
+    "(5.0, 4.800428460273882)")
+ufunc_nbdtrik_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nbdtrik_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrik_types[0] = NPY_FLOAT
+ufunc_nbdtrik_types[1] = NPY_FLOAT
+ufunc_nbdtrik_types[2] = NPY_FLOAT
+ufunc_nbdtrik_types[3] = NPY_FLOAT
+ufunc_nbdtrik_types[4] = NPY_DOUBLE
+ufunc_nbdtrik_types[5] = NPY_DOUBLE
+ufunc_nbdtrik_types[6] = NPY_DOUBLE
+ufunc_nbdtrik_types[7] = NPY_DOUBLE
+ufunc_nbdtrik_ptr[2*0] = _func_nbdtrik
+ufunc_nbdtrik_ptr[2*0+1] = ("nbdtrik")
+ufunc_nbdtrik_ptr[2*1] = _func_nbdtrik
+ufunc_nbdtrik_ptr[2*1+1] = ("nbdtrik")
+ufunc_nbdtrik_data[0] = &ufunc_nbdtrik_ptr[2*0]
+ufunc_nbdtrik_data[1] = &ufunc_nbdtrik_ptr[2*1]
+nbdtrik = np.PyUFunc_FromFuncAndData(ufunc_nbdtrik_loops, ufunc_nbdtrik_data, ufunc_nbdtrik_types, 2, 3, 1, 0, "nbdtrik", ufunc_nbdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrin_loops[2]
+cdef void *ufunc_nbdtrin_ptr[4]
+cdef void *ufunc_nbdtrin_data[2]
+cdef char ufunc_nbdtrin_types[8]
+cdef char *ufunc_nbdtrin_doc = (
+    "nbdtrin(k, y, p, out=None)\n"
+    "\n"
+    "Inverse of `nbdtr` vs `n`.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `n` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "n : scalar or ndarray\n"
+    "    The number of successes `n` such that `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n"
+    "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n"
+    "\n"
+    "Formula 26.5.26 of [2]_,\n"
+    "\n"
+    ".. math::\n"
+    "    \\sum_{j=k + 1}^\\infty {{n + j - 1}\n"
+    "    \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n"
+    "\n"
+    "is used to reduce calculation of the cumulative distribution function to\n"
+    "that of a regularized incomplete beta :math:`I`.\n"
+    "\n"
+    "Computation of `n` involves a search for a value that produces the desired\n"
+    "value of `y`.  The search relies on the monotonicity of `y` with `n`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the negative binomial cumulative distribution function for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.special import nbdtr, nbdtrin\n"
+    ">>> k, n, p = 5, 2, 0.5\n"
+    ">>> cdf_value = nbdtr(k, n, p)\n"
+    ">>> cdf_value\n"
+    "0.9375\n"
+    "\n"
+    "Verify that `nbdtrin` recovers the original value for `n` up to floating\n"
+    "point accuracy.\n"
+    "\n"
+    ">>> nbdtrin(k, cdf_value, p)\n"
+    "1.999999999998137")
+ufunc_nbdtrin_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nbdtrin_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrin_types[0] = NPY_FLOAT
+ufunc_nbdtrin_types[1] = NPY_FLOAT
+ufunc_nbdtrin_types[2] = NPY_FLOAT
+ufunc_nbdtrin_types[3] = NPY_FLOAT
+ufunc_nbdtrin_types[4] = NPY_DOUBLE
+ufunc_nbdtrin_types[5] = NPY_DOUBLE
+ufunc_nbdtrin_types[6] = NPY_DOUBLE
+ufunc_nbdtrin_types[7] = NPY_DOUBLE
+ufunc_nbdtrin_ptr[2*0] = _func_nbdtrin
+ufunc_nbdtrin_ptr[2*0+1] = ("nbdtrin")
+ufunc_nbdtrin_ptr[2*1] = _func_nbdtrin
+ufunc_nbdtrin_ptr[2*1+1] = ("nbdtrin")
+ufunc_nbdtrin_data[0] = &ufunc_nbdtrin_ptr[2*0]
+ufunc_nbdtrin_data[1] = &ufunc_nbdtrin_ptr[2*1]
+nbdtrin = np.PyUFunc_FromFuncAndData(ufunc_nbdtrin_loops, ufunc_nbdtrin_data, ufunc_nbdtrin_types, 2, 3, 1, 0, "nbdtrin", ufunc_nbdtrin_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtr_loops[2]
+cdef void *ufunc_ncfdtr_ptr[4]
+cdef void *ufunc_ncfdtr_data[2]
+cdef char ufunc_ncfdtr_types[10]
+cdef char *ufunc_ncfdtr_doc = (
+    "ncfdtr(dfn, dfd, nc, f, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the non-central F distribution.\n"
+    "\n"
+    "The non-central F describes the distribution of,\n"
+    "\n"
+    ".. math::\n"
+    "    Z = \\frac{X/d_n}{Y/d_d}\n"
+    "\n"
+    "where :math:`X` and :math:`Y` are independently distributed, with\n"
+    ":math:`X` distributed non-central :math:`\\chi^2` with noncentrality\n"
+    "parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`\n"
+    "distributed :math:`\\chi^2` with :math:`d_d` degrees of freedom.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares.  Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Range [0, inf).\n"
+    "f : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    The calculated CDF.  If all inputs are scalar, the return will be a\n"
+    "    float.  Otherwise it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "scipy.stats.ncf : Non-central F distribution.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the CDF of the non-central f distribution using\n"
+    "the Boost Math C++ library [1]_.\n"
+    "\n"
+    "The cumulative distribution function is computed using Formula 26.6.20 of\n"
+    "[2]_:\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d, n_c, f) = \\sum_{j=0}^\\infty e^{-n_c/2}\n"
+    "    \\frac{(n_c/2)^j}{j!} I_{x}(\\frac{d_n}{2} + j, \\frac{d_d}{2}),\n"
+    "\n"
+    "where :math:`I` is the regularized incomplete beta function, and\n"
+    ":math:`x = f d_n/(f d_n + d_d)`.\n"
+    "\n"
+    "Note that argument order of `ncfdtr` is different from that of the\n"
+    "similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last\n"
+    "parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> from scipy import stats\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Plot the CDF of the non-central F distribution, for nc=0.  Compare with the\n"
+    "F-distribution from scipy.stats:\n"
+    "\n"
+    ">>> x = np.linspace(-1, 8, num=500)\n"
+    ">>> dfn = 3\n"
+    ">>> dfd = 2\n"
+    ">>> ncf_stats = stats.f.cdf(x, dfn, dfd)\n"
+    ">>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)\n"
+    "\n"
+    ">>> fig = plt.figure()\n"
+    ">>> ax = fig.add_subplot(111)\n"
+    ">>> ax.plot(x, ncf_stats, 'b-', lw=3)\n"
+    ">>> ax.plot(x, ncf_special, 'r-')\n"
+    ">>> plt.show()")
+ufunc_ncfdtr_loops[0] = loop_f_ffff__As_ffff_f
+ufunc_ncfdtr_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtr_types[0] = NPY_FLOAT
+ufunc_ncfdtr_types[1] = NPY_FLOAT
+ufunc_ncfdtr_types[2] = NPY_FLOAT
+ufunc_ncfdtr_types[3] = NPY_FLOAT
+ufunc_ncfdtr_types[4] = NPY_FLOAT
+ufunc_ncfdtr_types[5] = NPY_DOUBLE
+ufunc_ncfdtr_types[6] = NPY_DOUBLE
+ufunc_ncfdtr_types[7] = NPY_DOUBLE
+ufunc_ncfdtr_types[8] = NPY_DOUBLE
+ufunc_ncfdtr_types[9] = NPY_DOUBLE
+ufunc_ncfdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_cdf_float
+ufunc_ncfdtr_ptr[2*0+1] = ("ncfdtr")
+ufunc_ncfdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_cdf_double
+ufunc_ncfdtr_ptr[2*1+1] = ("ncfdtr")
+ufunc_ncfdtr_data[0] = &ufunc_ncfdtr_ptr[2*0]
+ufunc_ncfdtr_data[1] = &ufunc_ncfdtr_ptr[2*1]
+ncfdtr = np.PyUFunc_FromFuncAndData(ufunc_ncfdtr_loops, ufunc_ncfdtr_data, ufunc_ncfdtr_types, 2, 4, 1, 0, "ncfdtr", ufunc_ncfdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtri_loops[2]
+cdef void *ufunc_ncfdtri_ptr[4]
+cdef void *ufunc_ncfdtri_data[2]
+cdef char ufunc_ncfdtri_types[10]
+cdef char *ufunc_ncfdtri_doc = (
+    "ncfdtri(dfn, dfd, nc, p, out=None)\n"
+    "\n"
+    "Inverse with respect to `f` of the CDF of the non-central F distribution.\n"
+    "\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares.  Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Range [0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function.  Must be in the\n"
+    "    range [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "f : scalar or ndarray\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "scipy.stats.ncf : Non-central F distribution.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the Quantile of the non-central f distribution\n"
+    "using the Boost Math C++ library [1]_.\n"
+    "\n"
+    "Note that argument order of `ncfdtri` is different from that of the\n"
+    "similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter\n"
+    "of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtri\n"
+    "\n"
+    "Compute the CDF for several values of `f`:\n"
+    "\n"
+    ">>> f = [0.5, 1, 1.5]\n"
+    ">>> p = ncfdtr(2, 3, 1.5, f)\n"
+    ">>> p\n"
+    "array([ 0.20782291,  0.36107392,  0.47345752])\n"
+    "\n"
+    "Compute the inverse.  We recover the values of `f`, as expected:\n"
+    "\n"
+    ">>> ncfdtri(2, 3, 1.5, p)\n"
+    "array([ 0.5,  1. ,  1.5])")
+ufunc_ncfdtri_loops[0] = loop_f_ffff__As_ffff_f
+ufunc_ncfdtri_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtri_types[0] = NPY_FLOAT
+ufunc_ncfdtri_types[1] = NPY_FLOAT
+ufunc_ncfdtri_types[2] = NPY_FLOAT
+ufunc_ncfdtri_types[3] = NPY_FLOAT
+ufunc_ncfdtri_types[4] = NPY_FLOAT
+ufunc_ncfdtri_types[5] = NPY_DOUBLE
+ufunc_ncfdtri_types[6] = NPY_DOUBLE
+ufunc_ncfdtri_types[7] = NPY_DOUBLE
+ufunc_ncfdtri_types[8] = NPY_DOUBLE
+ufunc_ncfdtri_types[9] = NPY_DOUBLE
+ufunc_ncfdtri_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_ppf_float
+ufunc_ncfdtri_ptr[2*0+1] = ("ncfdtri")
+ufunc_ncfdtri_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_ppf_double
+ufunc_ncfdtri_ptr[2*1+1] = ("ncfdtri")
+ufunc_ncfdtri_data[0] = &ufunc_ncfdtri_ptr[2*0]
+ufunc_ncfdtri_data[1] = &ufunc_ncfdtri_ptr[2*1]
+ncfdtri = np.PyUFunc_FromFuncAndData(ufunc_ncfdtri_loops, ufunc_ncfdtri_data, ufunc_ncfdtri_types, 2, 4, 1, 0, "ncfdtri", ufunc_ncfdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtridfd_loops[2]
+cdef void *ufunc_ncfdtridfd_ptr[4]
+cdef void *ufunc_ncfdtridfd_data[2]
+cdef char ufunc_ncfdtridfd_types[10]
+cdef char *ufunc_ncfdtridfd_doc = (
+    "ncfdtridfd(dfn, p, nc, f, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom (denominator) for the noncentral F-distribution.\n"
+    "\n"
+    "This is the inverse with respect to `dfd` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function.  Must be in the\n"
+    "    range [0, 1].\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Should be in range (0, 1e4).\n"
+    "f : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfd : scalar or ndarray\n"
+    "    Degrees of freedom of the denominator sum of squares.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The value of the cumulative noncentral F distribution is not necessarily\n"
+    "monotone in either degrees of freedom. There thus may be two values that\n"
+    "provide a given CDF value. This routine assumes monotonicity and will\n"
+    "find an arbitrary one of the two values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtridfd\n"
+    "\n"
+    "Compute the CDF for several values of `dfd`:\n"
+    "\n"
+    ">>> dfd = [1, 2, 3]\n"
+    ">>> p = ncfdtr(2, dfd, 0.25, 15)\n"
+    ">>> p\n"
+    "array([ 0.8097138 ,  0.93020416,  0.96787852])\n"
+    "\n"
+    "Compute the inverse.  We recover the values of `dfd`, as expected:\n"
+    "\n"
+    ">>> ncfdtridfd(2, p, 0.25, 15)\n"
+    "array([ 1.,  2.,  3.])")
+ufunc_ncfdtridfd_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtridfd_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtridfd_types[0] = NPY_FLOAT
+ufunc_ncfdtridfd_types[1] = NPY_FLOAT
+ufunc_ncfdtridfd_types[2] = NPY_FLOAT
+ufunc_ncfdtridfd_types[3] = NPY_FLOAT
+ufunc_ncfdtridfd_types[4] = NPY_FLOAT
+ufunc_ncfdtridfd_types[5] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[6] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[7] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[8] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[9] = NPY_DOUBLE
+ufunc_ncfdtridfd_ptr[2*0] = _func_ncfdtridfd
+ufunc_ncfdtridfd_ptr[2*0+1] = ("ncfdtridfd")
+ufunc_ncfdtridfd_ptr[2*1] = _func_ncfdtridfd
+ufunc_ncfdtridfd_ptr[2*1+1] = ("ncfdtridfd")
+ufunc_ncfdtridfd_data[0] = &ufunc_ncfdtridfd_ptr[2*0]
+ufunc_ncfdtridfd_data[1] = &ufunc_ncfdtridfd_ptr[2*1]
+ncfdtridfd = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfd_loops, ufunc_ncfdtridfd_data, ufunc_ncfdtridfd_types, 2, 4, 1, 0, "ncfdtridfd", ufunc_ncfdtridfd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtridfn_loops[2]
+cdef void *ufunc_ncfdtridfn_ptr[4]
+cdef void *ufunc_ncfdtridfn_data[2]
+cdef char ufunc_ncfdtridfn_types[10]
+cdef char *ufunc_ncfdtridfn_doc = (
+    "ncfdtridfn(p, dfd, nc, f, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom (numerator) for the noncentral F-distribution.\n"
+    "\n"
+    "This is the inverse with respect to `dfn` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function. Must be in the\n"
+    "    range [0, 1].\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares. Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Should be in range (0, 1e4).\n"
+    "f : float\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfn : scalar or ndarray\n"
+    "    Degrees of freedom of the numerator sum of squares.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The value of the cumulative noncentral F distribution is not necessarily\n"
+    "monotone in either degrees of freedom. There thus may be two values that\n"
+    "provide a given CDF value. This routine assumes monotonicity and will\n"
+    "find an arbitrary one of the two values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtridfn\n"
+    "\n"
+    "Compute the CDF for several values of `dfn`:\n"
+    "\n"
+    ">>> dfn = [1, 2, 3]\n"
+    ">>> p = ncfdtr(dfn, 2, 0.25, 15)\n"
+    ">>> p\n"
+    "array([ 0.92562363,  0.93020416,  0.93188394])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `dfn`, as expected:\n"
+    "\n"
+    ">>> ncfdtridfn(p, 2, 0.25, 15)\n"
+    "array([ 1.,  2.,  3.])")
+ufunc_ncfdtridfn_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtridfn_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtridfn_types[0] = NPY_FLOAT
+ufunc_ncfdtridfn_types[1] = NPY_FLOAT
+ufunc_ncfdtridfn_types[2] = NPY_FLOAT
+ufunc_ncfdtridfn_types[3] = NPY_FLOAT
+ufunc_ncfdtridfn_types[4] = NPY_FLOAT
+ufunc_ncfdtridfn_types[5] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[6] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[7] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[8] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[9] = NPY_DOUBLE
+ufunc_ncfdtridfn_ptr[2*0] = _func_ncfdtridfn
+ufunc_ncfdtridfn_ptr[2*0+1] = ("ncfdtridfn")
+ufunc_ncfdtridfn_ptr[2*1] = _func_ncfdtridfn
+ufunc_ncfdtridfn_ptr[2*1+1] = ("ncfdtridfn")
+ufunc_ncfdtridfn_data[0] = &ufunc_ncfdtridfn_ptr[2*0]
+ufunc_ncfdtridfn_data[1] = &ufunc_ncfdtridfn_ptr[2*1]
+ncfdtridfn = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfn_loops, ufunc_ncfdtridfn_data, ufunc_ncfdtridfn_types, 2, 4, 1, 0, "ncfdtridfn", ufunc_ncfdtridfn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtrinc_loops[2]
+cdef void *ufunc_ncfdtrinc_ptr[4]
+cdef void *ufunc_ncfdtrinc_data[2]
+cdef char ufunc_ncfdtrinc_types[10]
+cdef char *ufunc_ncfdtrinc_doc = (
+    "ncfdtrinc(dfn, dfd, p, f, out=None)\n"
+    "\n"
+    "Calculate non-centrality parameter for non-central F distribution.\n"
+    "\n"
+    "This is the inverse with respect to `nc` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares. Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares. Range (0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function. Must be in the\n"
+    "    range [0, 1].\n"
+    "f : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Noncentrality parameter.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtrinc\n"
+    "\n"
+    "Compute the CDF for several values of `nc`:\n"
+    "\n"
+    ">>> nc = [0.5, 1.5, 2.0]\n"
+    ">>> p = ncfdtr(2, 3, nc, 15)\n"
+    ">>> p\n"
+    "array([ 0.96309246,  0.94327955,  0.93304098])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `nc`, as expected:\n"
+    "\n"
+    ">>> ncfdtrinc(2, 3, p, 15)\n"
+    "array([ 0.5,  1.5,  2. ])")
+ufunc_ncfdtrinc_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtrinc_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtrinc_types[0] = NPY_FLOAT
+ufunc_ncfdtrinc_types[1] = NPY_FLOAT
+ufunc_ncfdtrinc_types[2] = NPY_FLOAT
+ufunc_ncfdtrinc_types[3] = NPY_FLOAT
+ufunc_ncfdtrinc_types[4] = NPY_FLOAT
+ufunc_ncfdtrinc_types[5] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[6] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[7] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[8] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[9] = NPY_DOUBLE
+ufunc_ncfdtrinc_ptr[2*0] = _func_ncfdtrinc
+ufunc_ncfdtrinc_ptr[2*0+1] = ("ncfdtrinc")
+ufunc_ncfdtrinc_ptr[2*1] = _func_ncfdtrinc
+ufunc_ncfdtrinc_ptr[2*1+1] = ("ncfdtrinc")
+ufunc_ncfdtrinc_data[0] = &ufunc_ncfdtrinc_ptr[2*0]
+ufunc_ncfdtrinc_data[1] = &ufunc_ncfdtrinc_ptr[2*1]
+ncfdtrinc = np.PyUFunc_FromFuncAndData(ufunc_ncfdtrinc_loops, ufunc_ncfdtrinc_data, ufunc_ncfdtrinc_types, 2, 4, 1, 0, "ncfdtrinc", ufunc_ncfdtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtr_loops[2]
+cdef void *ufunc_nctdtr_ptr[4]
+cdef void *ufunc_nctdtr_data[2]
+cdef char ufunc_nctdtr_types[8]
+cdef char *ufunc_nctdtr_doc = (
+    "nctdtr(df, nc, t, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the non-central `t` distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    The calculated CDF. If all inputs are scalar, the return will be a\n"
+    "    float. Otherwise, it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the CDF of the non-central t distribution using\n"
+    "the Boost Math C++ library [1]_.\n"
+    "\n"
+    "Note that the argument order of `nctdtr` is different from that of the\n"
+    "similar ``cdf`` method of `scipy.stats.nct`: `t` is the last\n"
+    "parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> from scipy import stats\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Plot the CDF of the non-central t distribution, for nc=0. Compare with the\n"
+    "t-distribution from scipy.stats:\n"
+    "\n"
+    ">>> x = np.linspace(-5, 5, num=500)\n"
+    ">>> df = 3\n"
+    ">>> nct_stats = stats.t.cdf(x, df)\n"
+    ">>> nct_special = special.nctdtr(df, 0, x)\n"
+    "\n"
+    ">>> fig = plt.figure()\n"
+    ">>> ax = fig.add_subplot(111)\n"
+    ">>> ax.plot(x, nct_stats, 'b-', lw=3)\n"
+    ">>> ax.plot(x, nct_special, 'r-')\n"
+    ">>> plt.show()")
+ufunc_nctdtr_loops[0] = loop_f_fff__As_fff_f
+ufunc_nctdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtr_types[0] = NPY_FLOAT
+ufunc_nctdtr_types[1] = NPY_FLOAT
+ufunc_nctdtr_types[2] = NPY_FLOAT
+ufunc_nctdtr_types[3] = NPY_FLOAT
+ufunc_nctdtr_types[4] = NPY_DOUBLE
+ufunc_nctdtr_types[5] = NPY_DOUBLE
+ufunc_nctdtr_types[6] = NPY_DOUBLE
+ufunc_nctdtr_types[7] = NPY_DOUBLE
+ufunc_nctdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_cdf_float
+ufunc_nctdtr_ptr[2*0+1] = ("nctdtr")
+ufunc_nctdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_cdf_double
+ufunc_nctdtr_ptr[2*1+1] = ("nctdtr")
+ufunc_nctdtr_data[0] = &ufunc_nctdtr_ptr[2*0]
+ufunc_nctdtr_data[1] = &ufunc_nctdtr_ptr[2*1]
+nctdtr = np.PyUFunc_FromFuncAndData(ufunc_nctdtr_loops, ufunc_nctdtr_data, ufunc_nctdtr_types, 2, 3, 1, 0, "nctdtr", ufunc_nctdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtridf_loops[2]
+cdef void *ufunc_nctdtridf_ptr[4]
+cdef void *ufunc_nctdtridf_data[2]
+cdef char ufunc_nctdtridf_types[8]
+cdef char *ufunc_nctdtridf_doc = (
+    "nctdtridf(p, nc, t, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom for non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter. Should be in range (-1e6, 1e6).\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    The degrees of freedom. If all inputs are scalar, the return will be a\n"
+    "    float. Otherwise, it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtridf\n"
+    "\n"
+    "Compute the CDF for several values of `df`:\n"
+    "\n"
+    ">>> df = [1, 2, 3]\n"
+    ">>> p = nctdtr(df, 0.25, 1)\n"
+    ">>> p\n"
+    "array([0.67491974, 0.716464  , 0.73349456])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `df`, as expected:\n"
+    "\n"
+    ">>> nctdtridf(p, 0.25, 1)\n"
+    "array([1., 2., 3.])")
+ufunc_nctdtridf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtridf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtridf_types[0] = NPY_FLOAT
+ufunc_nctdtridf_types[1] = NPY_FLOAT
+ufunc_nctdtridf_types[2] = NPY_FLOAT
+ufunc_nctdtridf_types[3] = NPY_FLOAT
+ufunc_nctdtridf_types[4] = NPY_DOUBLE
+ufunc_nctdtridf_types[5] = NPY_DOUBLE
+ufunc_nctdtridf_types[6] = NPY_DOUBLE
+ufunc_nctdtridf_types[7] = NPY_DOUBLE
+ufunc_nctdtridf_ptr[2*0] = _func_nctdtridf
+ufunc_nctdtridf_ptr[2*0+1] = ("nctdtridf")
+ufunc_nctdtridf_ptr[2*1] = _func_nctdtridf
+ufunc_nctdtridf_ptr[2*1+1] = ("nctdtridf")
+ufunc_nctdtridf_data[0] = &ufunc_nctdtridf_ptr[2*0]
+ufunc_nctdtridf_data[1] = &ufunc_nctdtridf_ptr[2*1]
+nctdtridf = np.PyUFunc_FromFuncAndData(ufunc_nctdtridf_loops, ufunc_nctdtridf_data, ufunc_nctdtridf_types, 2, 3, 1, 0, "nctdtridf", ufunc_nctdtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtrinc_loops[2]
+cdef void *ufunc_nctdtrinc_ptr[4]
+cdef void *ufunc_nctdtrinc_data[2]
+cdef char ufunc_nctdtrinc_types[8]
+cdef char *ufunc_nctdtrinc_doc = (
+    "nctdtrinc(df, p, t, out=None)\n"
+    "\n"
+    "Calculate non-centrality parameter for non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Noncentrality parameter\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtrinc\n"
+    "\n"
+    "Compute the CDF for several values of `nc`:\n"
+    "\n"
+    ">>> nc = [0.5, 1.5, 2.5]\n"
+    ">>> p = nctdtr(3, nc, 1.5)\n"
+    ">>> p\n"
+    "array([0.77569497, 0.45524533, 0.1668691 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `nc`, as expected:\n"
+    "\n"
+    ">>> nctdtrinc(3, p, 1.5)\n"
+    "array([0.5, 1.5, 2.5])")
+ufunc_nctdtrinc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtrinc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtrinc_types[0] = NPY_FLOAT
+ufunc_nctdtrinc_types[1] = NPY_FLOAT
+ufunc_nctdtrinc_types[2] = NPY_FLOAT
+ufunc_nctdtrinc_types[3] = NPY_FLOAT
+ufunc_nctdtrinc_types[4] = NPY_DOUBLE
+ufunc_nctdtrinc_types[5] = NPY_DOUBLE
+ufunc_nctdtrinc_types[6] = NPY_DOUBLE
+ufunc_nctdtrinc_types[7] = NPY_DOUBLE
+ufunc_nctdtrinc_ptr[2*0] = _func_nctdtrinc
+ufunc_nctdtrinc_ptr[2*0+1] = ("nctdtrinc")
+ufunc_nctdtrinc_ptr[2*1] = _func_nctdtrinc
+ufunc_nctdtrinc_ptr[2*1+1] = ("nctdtrinc")
+ufunc_nctdtrinc_data[0] = &ufunc_nctdtrinc_ptr[2*0]
+ufunc_nctdtrinc_data[1] = &ufunc_nctdtrinc_ptr[2*1]
+nctdtrinc = np.PyUFunc_FromFuncAndData(ufunc_nctdtrinc_loops, ufunc_nctdtrinc_data, ufunc_nctdtrinc_types, 2, 3, 1, 0, "nctdtrinc", ufunc_nctdtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtrit_loops[2]
+cdef void *ufunc_nctdtrit_ptr[4]
+cdef void *ufunc_nctdtrit_data[2]
+cdef char ufunc_nctdtrit_types[8]
+cdef char *ufunc_nctdtrit_doc = (
+    "nctdtrit(df, nc, p, out=None)\n"
+    "\n"
+    "Inverse cumulative distribution function of the non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter. Should be in range (-1e6, 1e6).\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t : scalar or ndarray\n"
+    "    Quantiles\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtrit\n"
+    "\n"
+    "Compute the CDF for several values of `t`:\n"
+    "\n"
+    ">>> t = [0.5, 1, 1.5]\n"
+    ">>> p = nctdtr(3, 1, t)\n"
+    ">>> p\n"
+    "array([0.29811049, 0.46922687, 0.6257559 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `t`, as expected:\n"
+    "\n"
+    ">>> nctdtrit(3, 1, p)\n"
+    "array([0.5, 1. , 1.5])")
+ufunc_nctdtrit_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtrit_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtrit_types[0] = NPY_FLOAT
+ufunc_nctdtrit_types[1] = NPY_FLOAT
+ufunc_nctdtrit_types[2] = NPY_FLOAT
+ufunc_nctdtrit_types[3] = NPY_FLOAT
+ufunc_nctdtrit_types[4] = NPY_DOUBLE
+ufunc_nctdtrit_types[5] = NPY_DOUBLE
+ufunc_nctdtrit_types[6] = NPY_DOUBLE
+ufunc_nctdtrit_types[7] = NPY_DOUBLE
+ufunc_nctdtrit_ptr[2*0] = _func_nctdtrit
+ufunc_nctdtrit_ptr[2*0+1] = ("nctdtrit")
+ufunc_nctdtrit_ptr[2*1] = _func_nctdtrit
+ufunc_nctdtrit_ptr[2*1+1] = ("nctdtrit")
+ufunc_nctdtrit_data[0] = &ufunc_nctdtrit_ptr[2*0]
+ufunc_nctdtrit_data[1] = &ufunc_nctdtrit_ptr[2*1]
+nctdtrit = np.PyUFunc_FromFuncAndData(ufunc_nctdtrit_loops, ufunc_nctdtrit_data, ufunc_nctdtrit_types, 2, 3, 1, 0, "nctdtrit", ufunc_nctdtrit_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtr_loops[4]
+cdef void *ufunc_ndtr_ptr[8]
+cdef void *ufunc_ndtr_data[4]
+cdef char ufunc_ndtr_types[8]
+cdef char *ufunc_ndtr_doc = (
+    "ndtr(x, out=None)\n"
+    "\n"
+    "Cumulative distribution of the standard normal distribution.\n"
+    "\n"
+    "Returns the area under the standard Gaussian probability\n"
+    "density function, integrated from minus infinity to `x`\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^x \\exp(-t^2/2) dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like, real or complex\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the normal CDF evaluated at `x`\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "log_ndtr : Logarithm of ndtr\n"
+    "ndtri : Inverse of ndtr, standard normal percentile function\n"
+    "erf : Error function\n"
+    "erfc : 1 - erf\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Evaluate `ndtr` at one point.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import ndtr\n"
+    ">>> ndtr(0.5)\n"
+    "0.6914624612740131\n"
+    "\n"
+    "Evaluate the function at several points by providing a NumPy array\n"
+    "or list for `x`.\n"
+    "\n"
+    ">>> ndtr([0, 0.5, 2])\n"
+    "array([0.5       , 0.69146246, 0.97724987])\n"
+    "\n"
+    "Plot the function.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-5, 5, 100)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, ndtr(x))\n"
+    ">>> ax.set_title(r\"Standard normal cumulative distribution function $\\Phi$\")\n"
+    ">>> plt.show()")
+ufunc_ndtr_loops[0] = loop_d_d__As_f_f
+ufunc_ndtr_loops[1] = loop_d_d__As_d_d
+ufunc_ndtr_loops[2] = loop_D_D__As_F_F
+ufunc_ndtr_loops[3] = loop_D_D__As_D_D
+ufunc_ndtr_types[0] = NPY_FLOAT
+ufunc_ndtr_types[1] = NPY_FLOAT
+ufunc_ndtr_types[2] = NPY_DOUBLE
+ufunc_ndtr_types[3] = NPY_DOUBLE
+ufunc_ndtr_types[4] = NPY_CFLOAT
+ufunc_ndtr_types[5] = NPY_CFLOAT
+ufunc_ndtr_types[6] = NPY_CDOUBLE
+ufunc_ndtr_types[7] = NPY_CDOUBLE
+ufunc_ndtr_ptr[2*0] = _func_xsf_ndtr
+ufunc_ndtr_ptr[2*0+1] = ("ndtr")
+ufunc_ndtr_ptr[2*1] = _func_xsf_ndtr
+ufunc_ndtr_ptr[2*1+1] = ("ndtr")
+ufunc_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr
+ufunc_ndtr_ptr[2*2+1] = ("ndtr")
+ufunc_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr
+ufunc_ndtr_ptr[2*3+1] = ("ndtr")
+ufunc_ndtr_data[0] = &ufunc_ndtr_ptr[2*0]
+ufunc_ndtr_data[1] = &ufunc_ndtr_ptr[2*1]
+ufunc_ndtr_data[2] = &ufunc_ndtr_ptr[2*2]
+ufunc_ndtr_data[3] = &ufunc_ndtr_ptr[2*3]
+ndtr = np.PyUFunc_FromFuncAndData(ufunc_ndtr_loops, ufunc_ndtr_data, ufunc_ndtr_types, 4, 1, 1, 0, "ndtr", ufunc_ndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtri_loops[2]
+cdef void *ufunc_ndtri_ptr[4]
+cdef void *ufunc_ndtri_data[2]
+cdef char ufunc_ndtri_types[4]
+cdef char *ufunc_ndtri_doc = (
+    "ndtri(y, out=None)\n"
+    "\n"
+    "Inverse of `ndtr` vs x\n"
+    "\n"
+    "Returns the argument x for which the area under the standard normal\n"
+    "probability density function (integrated from minus infinity to `x`)\n"
+    "is equal to y.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value of x such that ``ndtr(x) == p``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri_exp : Inverse of log_ndtr\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`ndtri` is the percentile function of the standard normal distribution.\n"
+    "This means it returns the inverse of the cumulative density `ndtr`. First,\n"
+    "let us compute a cumulative density value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import ndtri, ndtr\n"
+    ">>> cdf_val = ndtr(2)\n"
+    ">>> cdf_val\n"
+    "0.9772498680518208\n"
+    "\n"
+    "Verify that `ndtri` yields the original value for `x` up to floating point\n"
+    "errors.\n"
+    "\n"
+    ">>> ndtri(cdf_val)\n"
+    "2.0000000000000004\n"
+    "\n"
+    "Plot the function. For that purpose, we provide a NumPy array as argument.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(0.01, 1, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, ndtri(x))\n"
+    ">>> ax.set_title(\"Standard normal percentile function\")\n"
+    ">>> plt.show()")
+ufunc_ndtri_loops[0] = loop_d_d__As_f_f
+ufunc_ndtri_loops[1] = loop_d_d__As_d_d
+ufunc_ndtri_types[0] = NPY_FLOAT
+ufunc_ndtri_types[1] = NPY_FLOAT
+ufunc_ndtri_types[2] = NPY_DOUBLE
+ufunc_ndtri_types[3] = NPY_DOUBLE
+ufunc_ndtri_ptr[2*0] = _func_xsf_ndtri
+ufunc_ndtri_ptr[2*0+1] = ("ndtri")
+ufunc_ndtri_ptr[2*1] = _func_xsf_ndtri
+ufunc_ndtri_ptr[2*1+1] = ("ndtri")
+ufunc_ndtri_data[0] = &ufunc_ndtri_ptr[2*0]
+ufunc_ndtri_data[1] = &ufunc_ndtri_ptr[2*1]
+ndtri = np.PyUFunc_FromFuncAndData(ufunc_ndtri_loops, ufunc_ndtri_data, ufunc_ndtri_types, 2, 1, 1, 0, "ndtri", ufunc_ndtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtri_exp_loops[2]
+cdef void *ufunc_ndtri_exp_ptr[4]
+cdef void *ufunc_ndtri_exp_data[2]
+cdef char ufunc_ndtri_exp_types[4]
+cdef char *ufunc_ndtri_exp_doc = (
+    "ndtri_exp(y, out=None)\n"
+    "\n"
+    "Inverse of `log_ndtr` vs x. Allows for greater precision than\n"
+    "`ndtri` composed with `numpy.exp` for very small values of y and for\n"
+    "y close to 0.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like of float\n"
+    "    Function argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Inverse of the log CDF of the standard normal distribution, evaluated\n"
+    "    at y.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "log_ndtr : log of the standard normal cumulative distribution function\n"
+    "ndtr : standard normal cumulative distribution function\n"
+    "ndtri : standard normal percentile function\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "`ndtri_exp` agrees with the naive implementation when the latter does\n"
+    "not suffer from underflow.\n"
+    "\n"
+    ">>> sc.ndtri_exp(-1)\n"
+    "-0.33747496376420244\n"
+    ">>> sc.ndtri(np.exp(-1))\n"
+    "-0.33747496376420244\n"
+    "\n"
+    "For extreme values of y, the naive approach fails\n"
+    "\n"
+    ">>> sc.ndtri(np.exp(-800))\n"
+    "-inf\n"
+    ">>> sc.ndtri(np.exp(-1e-20))\n"
+    "inf\n"
+    "\n"
+    "whereas `ndtri_exp` is still able to compute the result to high precision.\n"
+    "\n"
+    ">>> sc.ndtri_exp(-800)\n"
+    "-39.88469483825668\n"
+    ">>> sc.ndtri_exp(-1e-20)\n"
+    "9.262340089798409")
+ufunc_ndtri_exp_loops[0] = loop_d_d__As_f_f
+ufunc_ndtri_exp_loops[1] = loop_d_d__As_d_d
+ufunc_ndtri_exp_types[0] = NPY_FLOAT
+ufunc_ndtri_exp_types[1] = NPY_FLOAT
+ufunc_ndtri_exp_types[2] = NPY_DOUBLE
+ufunc_ndtri_exp_types[3] = NPY_DOUBLE
+ufunc_ndtri_exp_ptr[2*0] = _func_ndtri_exp
+ufunc_ndtri_exp_ptr[2*0+1] = ("ndtri_exp")
+ufunc_ndtri_exp_ptr[2*1] = _func_ndtri_exp
+ufunc_ndtri_exp_ptr[2*1+1] = ("ndtri_exp")
+ufunc_ndtri_exp_data[0] = &ufunc_ndtri_exp_ptr[2*0]
+ufunc_ndtri_exp_data[1] = &ufunc_ndtri_exp_ptr[2*1]
+ndtri_exp = np.PyUFunc_FromFuncAndData(ufunc_ndtri_exp_loops, ufunc_ndtri_exp_data, ufunc_ndtri_exp_types, 2, 1, 1, 0, "ndtri_exp", ufunc_ndtri_exp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nrdtrimn_loops[2]
+cdef void *ufunc_nrdtrimn_ptr[4]
+cdef void *ufunc_nrdtrimn_data[2]
+cdef char ufunc_nrdtrimn_types[8]
+cdef char *ufunc_nrdtrimn_doc = (
+    "nrdtrimn(p, std, x, out=None)\n"
+    "\n"
+    "Calculate mean of normal distribution given other params.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "std : array_like\n"
+    "    Standard deviation.\n"
+    "x : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "mn : scalar or ndarray\n"
+    "    The mean of the normal distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri : Inverse of standard normal CDF with respect to quantile\n"
+    "nrdtrisd : Inverse of normal distribution CDF with respect to\n"
+    "           standard deviation\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nrdtrimn` can be used to recover the mean of a normal distribution\n"
+    "if we know the CDF value `p` for a given quantile `x` and the\n"
+    "standard deviation `std`. First, we calculate\n"
+    "the normal distribution CDF for an exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.stats import norm\n"
+    ">>> mean = 3.\n"
+    ">>> std = 2.\n"
+    ">>> x = 6.\n"
+    ">>> p = norm.cdf(x, loc=mean, scale=std)\n"
+    ">>> p\n"
+    "0.9331927987311419\n"
+    "\n"
+    "Verify that `nrdtrimn` returns the original value for `mean`.\n"
+    "\n"
+    ">>> from scipy.special import nrdtrimn\n"
+    ">>> nrdtrimn(p, std, x)\n"
+    "3.0000000000000004")
+ufunc_nrdtrimn_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nrdtrimn_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nrdtrimn_types[0] = NPY_FLOAT
+ufunc_nrdtrimn_types[1] = NPY_FLOAT
+ufunc_nrdtrimn_types[2] = NPY_FLOAT
+ufunc_nrdtrimn_types[3] = NPY_FLOAT
+ufunc_nrdtrimn_types[4] = NPY_DOUBLE
+ufunc_nrdtrimn_types[5] = NPY_DOUBLE
+ufunc_nrdtrimn_types[6] = NPY_DOUBLE
+ufunc_nrdtrimn_types[7] = NPY_DOUBLE
+ufunc_nrdtrimn_ptr[2*0] = _func_nrdtrimn
+ufunc_nrdtrimn_ptr[2*0+1] = ("nrdtrimn")
+ufunc_nrdtrimn_ptr[2*1] = _func_nrdtrimn
+ufunc_nrdtrimn_ptr[2*1+1] = ("nrdtrimn")
+ufunc_nrdtrimn_data[0] = &ufunc_nrdtrimn_ptr[2*0]
+ufunc_nrdtrimn_data[1] = &ufunc_nrdtrimn_ptr[2*1]
+nrdtrimn = np.PyUFunc_FromFuncAndData(ufunc_nrdtrimn_loops, ufunc_nrdtrimn_data, ufunc_nrdtrimn_types, 2, 3, 1, 0, "nrdtrimn", ufunc_nrdtrimn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nrdtrisd_loops[2]
+cdef void *ufunc_nrdtrisd_ptr[4]
+cdef void *ufunc_nrdtrisd_data[2]
+cdef char ufunc_nrdtrisd_types[8]
+cdef char *ufunc_nrdtrisd_doc = (
+    "nrdtrisd(mn, p, x, out=None)\n"
+    "\n"
+    "Calculate standard deviation of normal distribution given other params.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "mn : scalar or ndarray\n"
+    "    The mean of the normal distribution.\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "x : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "std : scalar or ndarray\n"
+    "    Standard deviation.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri : Inverse of standard normal CDF with respect to quantile\n"
+    "nrdtrimn : Inverse of normal distribution CDF with respect to\n"
+    "           mean\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nrdtrisd` can be used to recover the standard deviation of a normal\n"
+    "distribution if we know the CDF value `p` for a given quantile `x` and\n"
+    "the mean `mn`. First, we calculate the normal distribution CDF for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.stats import norm\n"
+    ">>> mean = 3.\n"
+    ">>> std = 2.\n"
+    ">>> x = 6.\n"
+    ">>> p = norm.cdf(x, loc=mean, scale=std)\n"
+    ">>> p\n"
+    "0.9331927987311419\n"
+    "\n"
+    "Verify that `nrdtrisd` returns the original value for `std`.\n"
+    "\n"
+    ">>> from scipy.special import nrdtrisd\n"
+    ">>> nrdtrisd(mean, p, x)\n"
+    "2.0000000000000004")
+ufunc_nrdtrisd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nrdtrisd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nrdtrisd_types[0] = NPY_FLOAT
+ufunc_nrdtrisd_types[1] = NPY_FLOAT
+ufunc_nrdtrisd_types[2] = NPY_FLOAT
+ufunc_nrdtrisd_types[3] = NPY_FLOAT
+ufunc_nrdtrisd_types[4] = NPY_DOUBLE
+ufunc_nrdtrisd_types[5] = NPY_DOUBLE
+ufunc_nrdtrisd_types[6] = NPY_DOUBLE
+ufunc_nrdtrisd_types[7] = NPY_DOUBLE
+ufunc_nrdtrisd_ptr[2*0] = _func_nrdtrisd
+ufunc_nrdtrisd_ptr[2*0+1] = ("nrdtrisd")
+ufunc_nrdtrisd_ptr[2*1] = _func_nrdtrisd
+ufunc_nrdtrisd_ptr[2*1+1] = ("nrdtrisd")
+ufunc_nrdtrisd_data[0] = &ufunc_nrdtrisd_ptr[2*0]
+ufunc_nrdtrisd_data[1] = &ufunc_nrdtrisd_ptr[2*1]
+nrdtrisd = np.PyUFunc_FromFuncAndData(ufunc_nrdtrisd_loops, ufunc_nrdtrisd_data, ufunc_nrdtrisd_types, 2, 3, 1, 0, "nrdtrisd", ufunc_nrdtrisd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_owens_t_loops[2]
+cdef void *ufunc_owens_t_ptr[4]
+cdef void *ufunc_owens_t_data[2]
+cdef char ufunc_owens_t_types[6]
+cdef char *ufunc_owens_t_doc = (
+    "owens_t(h, a, out=None)\n"
+    "\n"
+    "Owen's T Function.\n"
+    "\n"
+    "The function T(h, a) gives the probability of the event\n"
+    "(X > h and 0 < Y < a * X) where X and Y are independent\n"
+    "standard normal random variables.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "h: array_like\n"
+    "    Input value.\n"
+    "a: array_like\n"
+    "    Input value.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t: scalar or ndarray\n"
+    "    Probability of the event (X > h and 0 < Y < a * X),\n"
+    "    where X and Y are independent standard normal random variables.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] M. Patefield and D. Tandy, \"Fast and accurate calculation of\n"
+    "       Owen's T Function\", Statistical Software vol. 5, pp. 1-25, 2000.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy import special\n"
+    ">>> a = 3.5\n"
+    ">>> h = 0.78\n"
+    ">>> special.owens_t(h, a)\n"
+    "0.10877216734852274")
+ufunc_owens_t_loops[0] = loop_d_dd__As_ff_f
+ufunc_owens_t_loops[1] = loop_d_dd__As_dd_d
+ufunc_owens_t_types[0] = NPY_FLOAT
+ufunc_owens_t_types[1] = NPY_FLOAT
+ufunc_owens_t_types[2] = NPY_FLOAT
+ufunc_owens_t_types[3] = NPY_DOUBLE
+ufunc_owens_t_types[4] = NPY_DOUBLE
+ufunc_owens_t_types[5] = NPY_DOUBLE
+ufunc_owens_t_ptr[2*0] = _func_xsf_owens_t
+ufunc_owens_t_ptr[2*0+1] = ("owens_t")
+ufunc_owens_t_ptr[2*1] = _func_xsf_owens_t
+ufunc_owens_t_ptr[2*1+1] = ("owens_t")
+ufunc_owens_t_data[0] = &ufunc_owens_t_ptr[2*0]
+ufunc_owens_t_data[1] = &ufunc_owens_t_ptr[2*1]
+owens_t = np.PyUFunc_FromFuncAndData(ufunc_owens_t_loops, ufunc_owens_t_data, ufunc_owens_t_types, 2, 2, 1, 0, "owens_t", ufunc_owens_t_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtr_loops[2]
+cdef void *ufunc_pdtr_ptr[4]
+cdef void *ufunc_pdtr_data[2]
+cdef char ufunc_pdtr_types[6]
+cdef char *ufunc_pdtr_doc = (
+    "pdtr(k, m, out=None)\n"
+    "\n"
+    "Poisson cumulative distribution function.\n"
+    "\n"
+    "Defined as the probability that a Poisson-distributed random\n"
+    "variable with event rate :math:`m` is less than or equal to\n"
+    ":math:`k`. More concretely, this works out to be [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   \\exp(-m) \\sum_{j = 0}^{\\lfloor{k}\\rfloor} \\frac{m^j}{j!}.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Poisson cumulative distribution function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Poisson_distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is a cumulative distribution function, so it converges to 1\n"
+    "monotonically as `k` goes to infinity.\n"
+    "\n"
+    ">>> sc.pdtr([1, 10, 100, np.inf], 1)\n"
+    "array([0.73575888, 0.99999999, 1.        , 1.        ])\n"
+    "\n"
+    "It is discontinuous at integers and constant between integers.\n"
+    "\n"
+    ">>> sc.pdtr([1, 1.5, 1.9, 2], 1)\n"
+    "array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])")
+ufunc_pdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtr_types[0] = NPY_FLOAT
+ufunc_pdtr_types[1] = NPY_FLOAT
+ufunc_pdtr_types[2] = NPY_FLOAT
+ufunc_pdtr_types[3] = NPY_DOUBLE
+ufunc_pdtr_types[4] = NPY_DOUBLE
+ufunc_pdtr_types[5] = NPY_DOUBLE
+ufunc_pdtr_ptr[2*0] = _func_xsf_pdtr
+ufunc_pdtr_ptr[2*0+1] = ("pdtr")
+ufunc_pdtr_ptr[2*1] = _func_xsf_pdtr
+ufunc_pdtr_ptr[2*1+1] = ("pdtr")
+ufunc_pdtr_data[0] = &ufunc_pdtr_ptr[2*0]
+ufunc_pdtr_data[1] = &ufunc_pdtr_ptr[2*1]
+pdtr = np.PyUFunc_FromFuncAndData(ufunc_pdtr_loops, ufunc_pdtr_data, ufunc_pdtr_types, 2, 2, 1, 0, "pdtr", ufunc_pdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtrc_loops[2]
+cdef void *ufunc_pdtrc_ptr[4]
+cdef void *ufunc_pdtrc_data[2]
+cdef char ufunc_pdtrc_types[6]
+cdef char *ufunc_pdtrc_doc = (
+    "pdtrc(k, m, out=None)\n"
+    "\n"
+    "Poisson survival function\n"
+    "\n"
+    "Returns the sum of the terms from k+1 to infinity of the Poisson\n"
+    "distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(\n"
+    "k+1, m). Arguments must both be non-negative doubles.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Poisson survival function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is a survival function, so it decreases to 0\n"
+    "monotonically as `k` goes to infinity.\n"
+    "\n"
+    ">>> k = np.array([1, 10, 100, np.inf])\n"
+    ">>> sc.pdtrc(k, 1)\n"
+    "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])\n"
+    "\n"
+    "It can be expressed in terms of the lower incomplete gamma\n"
+    "function `gammainc`.\n"
+    "\n"
+    ">>> sc.gammainc(k + 1, 1)\n"
+    "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])")
+ufunc_pdtrc_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtrc_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtrc_types[0] = NPY_FLOAT
+ufunc_pdtrc_types[1] = NPY_FLOAT
+ufunc_pdtrc_types[2] = NPY_FLOAT
+ufunc_pdtrc_types[3] = NPY_DOUBLE
+ufunc_pdtrc_types[4] = NPY_DOUBLE
+ufunc_pdtrc_types[5] = NPY_DOUBLE
+ufunc_pdtrc_ptr[2*0] = _func_xsf_pdtrc
+ufunc_pdtrc_ptr[2*0+1] = ("pdtrc")
+ufunc_pdtrc_ptr[2*1] = _func_xsf_pdtrc
+ufunc_pdtrc_ptr[2*1+1] = ("pdtrc")
+ufunc_pdtrc_data[0] = &ufunc_pdtrc_ptr[2*0]
+ufunc_pdtrc_data[1] = &ufunc_pdtrc_ptr[2*1]
+pdtrc = np.PyUFunc_FromFuncAndData(ufunc_pdtrc_loops, ufunc_pdtrc_data, ufunc_pdtrc_types, 2, 2, 1, 0, "pdtrc", ufunc_pdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtri_loops[3]
+cdef void *ufunc_pdtri_ptr[6]
+cdef void *ufunc_pdtri_data[3]
+cdef char ufunc_pdtri_types[9]
+cdef char *ufunc_pdtri_doc = (
+    "pdtri(k, y, out=None)\n"
+    "\n"
+    "Inverse to `pdtr` vs m\n"
+    "\n"
+    "Returns the Poisson variable `m` such that the sum from 0 to `k` of\n"
+    "the Poisson density is equal to the given probability `y`:\n"
+    "calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative\n"
+    "integer and `y` between 0 and 1.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "y : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the shape parameter `m` such that ``pdtr(k, m) = p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Compute the CDF for several values of `m`:\n"
+    "\n"
+    ">>> m = [0.5, 1, 1.5]\n"
+    ">>> p = sc.pdtr(1, m)\n"
+    ">>> p\n"
+    "array([0.90979599, 0.73575888, 0.5578254 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `m`, as expected:\n"
+    "\n"
+    ">>> sc.pdtri(1, p)\n"
+    "array([0.5, 1. , 1.5])")
+ufunc_pdtri_loops[0] = loop_d_pd__As_pd_d
+ufunc_pdtri_loops[1] = loop_d_dd__As_ff_f
+ufunc_pdtri_loops[2] = loop_d_dd__As_dd_d
+ufunc_pdtri_types[0] = NPY_INTP
+ufunc_pdtri_types[1] = NPY_DOUBLE
+ufunc_pdtri_types[2] = NPY_DOUBLE
+ufunc_pdtri_types[3] = NPY_FLOAT
+ufunc_pdtri_types[4] = NPY_FLOAT
+ufunc_pdtri_types[5] = NPY_FLOAT
+ufunc_pdtri_types[6] = NPY_DOUBLE
+ufunc_pdtri_types[7] = NPY_DOUBLE
+ufunc_pdtri_types[8] = NPY_DOUBLE
+ufunc_pdtri_ptr[2*0] = _func_cephes_pdtri_wrap
+ufunc_pdtri_ptr[2*0+1] = ("pdtri")
+ufunc_pdtri_ptr[2*1] = _func_pdtri_unsafe
+ufunc_pdtri_ptr[2*1+1] = ("pdtri")
+ufunc_pdtri_ptr[2*2] = _func_pdtri_unsafe
+ufunc_pdtri_ptr[2*2+1] = ("pdtri")
+ufunc_pdtri_data[0] = &ufunc_pdtri_ptr[2*0]
+ufunc_pdtri_data[1] = &ufunc_pdtri_ptr[2*1]
+ufunc_pdtri_data[2] = &ufunc_pdtri_ptr[2*2]
+pdtri = np.PyUFunc_FromFuncAndData(ufunc_pdtri_loops, ufunc_pdtri_data, ufunc_pdtri_types, 3, 2, 1, 0, "pdtri", ufunc_pdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtrik_loops[2]
+cdef void *ufunc_pdtrik_ptr[4]
+cdef void *ufunc_pdtrik_data[2]
+cdef char ufunc_pdtrik_types[6]
+cdef char *ufunc_pdtrik_doc = (
+    "pdtrik(p, m, out=None)\n"
+    "\n"
+    "Inverse to `pdtr` vs `k`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The number of occurrences `k` such that ``pdtr(k, m) = p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Compute the CDF for several values of `k`:\n"
+    "\n"
+    ">>> k = [1, 2, 3]\n"
+    ">>> p = sc.pdtr(k, 2)\n"
+    ">>> p\n"
+    "array([0.40600585, 0.67667642, 0.85712346])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `k`, as expected:\n"
+    "\n"
+    ">>> sc.pdtrik(p, 2)\n"
+    "array([1., 2., 3.])")
+ufunc_pdtrik_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtrik_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtrik_types[0] = NPY_FLOAT
+ufunc_pdtrik_types[1] = NPY_FLOAT
+ufunc_pdtrik_types[2] = NPY_FLOAT
+ufunc_pdtrik_types[3] = NPY_DOUBLE
+ufunc_pdtrik_types[4] = NPY_DOUBLE
+ufunc_pdtrik_types[5] = NPY_DOUBLE
+ufunc_pdtrik_ptr[2*0] = _func_pdtrik
+ufunc_pdtrik_ptr[2*0+1] = ("pdtrik")
+ufunc_pdtrik_ptr[2*1] = _func_pdtrik
+ufunc_pdtrik_ptr[2*1+1] = ("pdtrik")
+ufunc_pdtrik_data[0] = &ufunc_pdtrik_ptr[2*0]
+ufunc_pdtrik_data[1] = &ufunc_pdtrik_ptr[2*1]
+pdtrik = np.PyUFunc_FromFuncAndData(ufunc_pdtrik_loops, ufunc_pdtrik_data, ufunc_pdtrik_types, 2, 2, 1, 0, "pdtrik", ufunc_pdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_poch_loops[2]
+cdef void *ufunc_poch_ptr[4]
+cdef void *ufunc_poch_data[2]
+cdef char ufunc_poch_types[6]
+cdef char *ufunc_poch_doc = (
+    "poch(z, m, out=None)\n"
+    "\n"
+    "Pochhammer symbol.\n"
+    "\n"
+    "The Pochhammer symbol (rising factorial) is defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    (z)_m = \\frac{\\Gamma(z + m)}{\\Gamma(z)}\n"
+    "\n"
+    "For positive integer `m` it reads\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    (z)_m = z (z + 1) ... (z + m - 1)\n"
+    "\n"
+    "See [dlmf]_ for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z, m : array_like\n"
+    "    Real-valued arguments.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the function.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] Nist, Digital Library of Mathematical Functions\n"
+    "    https://dlmf.nist.gov/5.2#iii\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is 1 when m is 0.\n"
+    "\n"
+    ">>> sc.poch([1, 2, 3, 4], 0)\n"
+    "array([1., 1., 1., 1.])\n"
+    "\n"
+    "For z equal to 1 it reduces to the factorial function.\n"
+    "\n"
+    ">>> sc.poch(1, 5)\n"
+    "120.0\n"
+    ">>> 1 * 2 * 3 * 4 * 5\n"
+    "120\n"
+    "\n"
+    "It can be expressed in terms of the gamma function.\n"
+    "\n"
+    ">>> z, m = 3.7, 2.1\n"
+    ">>> sc.poch(z, m)\n"
+    "20.529581933776953\n"
+    ">>> sc.gamma(z + m) / sc.gamma(z)\n"
+    "20.52958193377696")
+ufunc_poch_loops[0] = loop_d_dd__As_ff_f
+ufunc_poch_loops[1] = loop_d_dd__As_dd_d
+ufunc_poch_types[0] = NPY_FLOAT
+ufunc_poch_types[1] = NPY_FLOAT
+ufunc_poch_types[2] = NPY_FLOAT
+ufunc_poch_types[3] = NPY_DOUBLE
+ufunc_poch_types[4] = NPY_DOUBLE
+ufunc_poch_types[5] = NPY_DOUBLE
+ufunc_poch_ptr[2*0] = _func_cephes_poch
+ufunc_poch_ptr[2*0+1] = ("poch")
+ufunc_poch_ptr[2*1] = _func_cephes_poch
+ufunc_poch_ptr[2*1+1] = ("poch")
+ufunc_poch_data[0] = &ufunc_poch_ptr[2*0]
+ufunc_poch_data[1] = &ufunc_poch_ptr[2*1]
+poch = np.PyUFunc_FromFuncAndData(ufunc_poch_loops, ufunc_poch_data, ufunc_poch_types, 2, 2, 1, 0, "poch", ufunc_poch_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_powm1_loops[2]
+cdef void *ufunc_powm1_ptr[4]
+cdef void *ufunc_powm1_data[2]
+cdef char ufunc_powm1_types[6]
+cdef char *ufunc_powm1_doc = (
+    "powm1(x, y, out=None)\n"
+    "\n"
+    "Computes ``x**y - 1``.\n"
+    "\n"
+    "This function is useful when `y` is near 0, or when `x` is near 1.\n"
+    "\n"
+    "The function is implemented for real types only (unlike ``numpy.power``,\n"
+    "which accepts complex inputs).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    The base. Must be a real type (i.e. integer or float, not complex).\n"
+    "y : array_like\n"
+    "    The exponent. Must be a real type (i.e. integer or float, not complex).\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "array_like\n"
+    "    Result of the calculation\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.10.0\n"
+    "\n"
+    "The underlying code is implemented for single precision and double\n"
+    "precision floats only.  Unlike `numpy.power`, integer inputs to\n"
+    "`powm1` are converted to floating point, and complex inputs are\n"
+    "not accepted.\n"
+    "\n"
+    "Note the following edge cases:\n"
+    "\n"
+    "* ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``\n"
+    "  and ``nan``.\n"
+    "* ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``\n"
+    "  and ``inf``.\n"
+    "\n"
+    "This function wraps the ``powm1`` routine from the\n"
+    "Boost Math C++ library [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import powm1\n"
+    "\n"
+    ">>> x = np.array([1.2, 10.0, 0.9999999975])\n"
+    ">>> y = np.array([1e-9, 1e-11, 0.1875])\n"
+    ">>> powm1(x, y)\n"
+    "array([ 1.82321557e-10,  2.30258509e-11, -4.68749998e-10])\n"
+    "\n"
+    "It can be verified that the relative errors in those results\n"
+    "are less than 2.5e-16.\n"
+    "\n"
+    "Compare that to the result of ``x**y - 1``, where the\n"
+    "relative errors are all larger than 8e-8:\n"
+    "\n"
+    ">>> x**y - 1\n"
+    "array([ 1.82321491e-10,  2.30258035e-11, -4.68750039e-10])")
+ufunc_powm1_loops[0] = loop_f_ff__As_ff_f
+ufunc_powm1_loops[1] = loop_d_dd__As_dd_d
+ufunc_powm1_types[0] = NPY_FLOAT
+ufunc_powm1_types[1] = NPY_FLOAT
+ufunc_powm1_types[2] = NPY_FLOAT
+ufunc_powm1_types[3] = NPY_DOUBLE
+ufunc_powm1_types[4] = NPY_DOUBLE
+ufunc_powm1_types[5] = NPY_DOUBLE
+ufunc_powm1_ptr[2*0] = scipy.special._ufuncs_cxx._export_powm1_float
+ufunc_powm1_ptr[2*0+1] = ("powm1")
+ufunc_powm1_ptr[2*1] = scipy.special._ufuncs_cxx._export_powm1_double
+ufunc_powm1_ptr[2*1+1] = ("powm1")
+ufunc_powm1_data[0] = &ufunc_powm1_ptr[2*0]
+ufunc_powm1_data[1] = &ufunc_powm1_ptr[2*1]
+powm1 = np.PyUFunc_FromFuncAndData(ufunc_powm1_loops, ufunc_powm1_data, ufunc_powm1_types, 2, 2, 1, 0, "powm1", ufunc_powm1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pseudo_huber_loops[2]
+cdef void *ufunc_pseudo_huber_ptr[4]
+cdef void *ufunc_pseudo_huber_data[2]
+cdef char ufunc_pseudo_huber_types[6]
+cdef char *ufunc_pseudo_huber_doc = (
+    "pseudo_huber(delta, r, out=None)\n"
+    "\n"
+    "Pseudo-Huber loss function.\n"
+    "\n"
+    ".. math:: \\mathrm{pseudo\\_huber}(\\delta, r) =\n"
+    "          \\delta^2 \\left( \\sqrt{ 1 + \\left( \\frac{r}{\\delta} \\right)^2 } - 1 \\right)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "delta : array_like\n"
+    "    Input array, indicating the soft quadratic vs. linear loss changepoint.\n"
+    "r : array_like\n"
+    "    Input array, possibly representing residuals.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The computed Pseudo-Huber loss function values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "huber: Similar function which this function approximates\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Like `huber`, `pseudo_huber` often serves as a robust loss function\n"
+    "in statistics or machine learning to reduce the influence of outliers.\n"
+    "Unlike `huber`, `pseudo_huber` is smooth.\n"
+    "\n"
+    "Typically, `r` represents residuals, the difference\n"
+    "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n"
+    "`pseudo_huber` resembles the squared error and for :math:`|r|>\\delta` the\n"
+    "absolute error. This way, the Pseudo-Huber loss often achieves\n"
+    "a fast convergence in model fitting for small residuals like the squared\n"
+    "error loss function and still reduces the influence of outliers\n"
+    "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n"
+    "the cutoff between squared and absolute error regimes, it has\n"
+    "to be tuned carefully for each problem. `pseudo_huber` is also\n"
+    "convex, making it suitable for gradient based optimization. [1]_ [2]_\n"
+    "\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Hartley, Zisserman, \"Multiple View Geometry in Computer Vision\".\n"
+    "       2003. Cambridge University Press. p. 619\n"
+    ".. [2] Charbonnier et al. \"Deterministic edge-preserving regularization\n"
+    "       in computed imaging\". 1997. IEEE Trans. Image Processing.\n"
+    "       6 (2): 298 - 311.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Import all necessary modules.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import pseudo_huber, huber\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Calculate the function for ``delta=1`` at ``r=2``.\n"
+    "\n"
+    ">>> pseudo_huber(1., 2.)\n"
+    "1.2360679774997898\n"
+    "\n"
+    "Calculate the function at ``r=2`` for different `delta` by providing\n"
+    "a list or NumPy array for `delta`.\n"
+    "\n"
+    ">>> pseudo_huber([1., 2., 4.], 3.)\n"
+    "array([2.16227766, 3.21110255, 4.        ])\n"
+    "\n"
+    "Calculate the function for ``delta=1`` at several points by providing\n"
+    "a list or NumPy array for `r`.\n"
+    "\n"
+    ">>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))\n"
+    "array([0.47213595, 1.        , 3.21110255, 4.94427191])\n"
+    "\n"
+    "The function can be calculated for different `delta` and `r` by\n"
+    "providing arrays for both with compatible shapes for broadcasting.\n"
+    "\n"
+    ">>> r = np.array([1., 2.5, 8., 10.])\n"
+    ">>> deltas = np.array([[1.], [5.], [9.]])\n"
+    ">>> print(r.shape, deltas.shape)\n"
+    "(4,) (3, 1)\n"
+    "\n"
+    ">>> pseudo_huber(deltas, r)\n"
+    "array([[ 0.41421356,  1.6925824 ,  7.06225775,  9.04987562],\n"
+    "       [ 0.49509757,  2.95084972, 22.16990566, 30.90169944],\n"
+    "       [ 0.49846624,  3.06693762, 27.37435121, 40.08261642]])\n"
+    "\n"
+    "Plot the function for different `delta`.\n"
+    "\n"
+    ">>> x = np.linspace(-4, 4, 500)\n"
+    ">>> deltas = [1, 2, 3]\n"
+    ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n"
+    ">>> for delta, style in combined_plot_parameters:\n"
+    "...     ax.plot(x, pseudo_huber(delta, x), label=rf\"$\\delta={delta}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(r\"Pseudo-Huber loss function $h_{\\delta}(x)$\")\n"
+    ">>> ax.set_xlim(-4, 4)\n"
+    ">>> ax.set_ylim(0, 8)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Finally, illustrate the difference between `huber` and `pseudo_huber` by\n"
+    "plotting them and their gradients with respect to `r`. The plot shows\n"
+    "that `pseudo_huber` is continuously differentiable while `huber` is not\n"
+    "at the points :math:`\\pm\\delta`.\n"
+    "\n"
+    ">>> def huber_grad(delta, x):\n"
+    "...     grad = np.copy(x)\n"
+    "...     linear_area = np.argwhere(np.abs(x) > delta)\n"
+    "...     grad[linear_area]=delta*np.sign(x[linear_area])\n"
+    "...     return grad\n"
+    ">>> def pseudo_huber_grad(delta, x):\n"
+    "...     return x* (1+(x/delta)**2)**(-0.5)\n"
+    ">>> x=np.linspace(-3, 3, 500)\n"
+    ">>> delta = 1.\n"
+    ">>> fig, ax = plt.subplots(figsize=(7, 7))\n"
+    ">>> ax.plot(x, huber(delta, x), label=\"Huber\", ls=\"dashed\")\n"
+    ">>> ax.plot(x, huber_grad(delta, x), label=\"Huber Gradient\", ls=\"dashdot\")\n"
+    ">>> ax.plot(x, pseudo_huber(delta, x), label=\"Pseudo-Huber\", ls=\"dotted\")\n"
+    ">>> ax.plot(x, pseudo_huber_grad(delta, x), label=\"Pseudo-Huber Gradient\",\n"
+    "...         ls=\"solid\")\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> plt.show()")
+ufunc_pseudo_huber_loops[0] = loop_d_dd__As_ff_f
+ufunc_pseudo_huber_loops[1] = loop_d_dd__As_dd_d
+ufunc_pseudo_huber_types[0] = NPY_FLOAT
+ufunc_pseudo_huber_types[1] = NPY_FLOAT
+ufunc_pseudo_huber_types[2] = NPY_FLOAT
+ufunc_pseudo_huber_types[3] = NPY_DOUBLE
+ufunc_pseudo_huber_types[4] = NPY_DOUBLE
+ufunc_pseudo_huber_types[5] = NPY_DOUBLE
+ufunc_pseudo_huber_ptr[2*0] = _func_pseudo_huber
+ufunc_pseudo_huber_ptr[2*0+1] = ("pseudo_huber")
+ufunc_pseudo_huber_ptr[2*1] = _func_pseudo_huber
+ufunc_pseudo_huber_ptr[2*1+1] = ("pseudo_huber")
+ufunc_pseudo_huber_data[0] = &ufunc_pseudo_huber_ptr[2*0]
+ufunc_pseudo_huber_data[1] = &ufunc_pseudo_huber_ptr[2*1]
+pseudo_huber = np.PyUFunc_FromFuncAndData(ufunc_pseudo_huber_loops, ufunc_pseudo_huber_data, ufunc_pseudo_huber_types, 2, 2, 1, 0, "pseudo_huber", ufunc_pseudo_huber_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_rel_entr_loops[2]
+cdef void *ufunc_rel_entr_ptr[4]
+cdef void *ufunc_rel_entr_data[2]
+cdef char ufunc_rel_entr_types[6]
+cdef char *ufunc_rel_entr_doc = (
+    "rel_entr(x, y, out=None)\n"
+    "\n"
+    "Elementwise function for computing relative entropy.\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\mathrm{rel\\_entr}(x, y) =\n"
+    "        \\begin{cases}\n"
+    "            x \\log(x / y) & x > 0, y > 0 \\\\\n"
+    "            0 & x = 0, y \\ge 0 \\\\\n"
+    "            \\infty & \\text{otherwise}\n"
+    "        \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Input arrays\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Relative entropy of the inputs\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "entr, kl_div, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is jointly convex in x and y.\n"
+    "\n"
+    "The origin of this function is in convex programming; see\n"
+    "[1]_. Given two discrete probability distributions :math:`p_1,\n"
+    "\\ldots, p_n` and :math:`q_1, \\ldots, q_n`, the definition of relative\n"
+    "entropy in the context of *information theory* is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\sum_{i = 1}^n \\mathrm{rel\\_entr}(p_i, q_i).\n"
+    "\n"
+    "To compute the latter quantity, use `scipy.stats.entropy`.\n"
+    "\n"
+    "See [2]_ for details.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`\n"
+    ".. [2] Kullback-Leibler divergence,\n"
+    "       https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence")
+ufunc_rel_entr_loops[0] = loop_d_dd__As_ff_f
+ufunc_rel_entr_loops[1] = loop_d_dd__As_dd_d
+ufunc_rel_entr_types[0] = NPY_FLOAT
+ufunc_rel_entr_types[1] = NPY_FLOAT
+ufunc_rel_entr_types[2] = NPY_FLOAT
+ufunc_rel_entr_types[3] = NPY_DOUBLE
+ufunc_rel_entr_types[4] = NPY_DOUBLE
+ufunc_rel_entr_types[5] = NPY_DOUBLE
+ufunc_rel_entr_ptr[2*0] = _func_rel_entr
+ufunc_rel_entr_ptr[2*0+1] = ("rel_entr")
+ufunc_rel_entr_ptr[2*1] = _func_rel_entr
+ufunc_rel_entr_ptr[2*1+1] = ("rel_entr")
+ufunc_rel_entr_data[0] = &ufunc_rel_entr_ptr[2*0]
+ufunc_rel_entr_data[1] = &ufunc_rel_entr_ptr[2*1]
+rel_entr = np.PyUFunc_FromFuncAndData(ufunc_rel_entr_loops, ufunc_rel_entr_data, ufunc_rel_entr_types, 2, 2, 1, 0, "rel_entr", ufunc_rel_entr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_round_loops[2]
+cdef void *ufunc_round_ptr[4]
+cdef void *ufunc_round_data[2]
+cdef char ufunc_round_types[4]
+cdef char *ufunc_round_doc = (
+    "round(x, out=None)\n"
+    "\n"
+    "Round to the nearest integer.\n"
+    "\n"
+    "Returns the nearest integer to `x`.  If `x` ends in 0.5 exactly,\n"
+    "the nearest even integer is chosen.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real valued input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The nearest integers to the elements of `x`. The result is of\n"
+    "    floating type, not integer type.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It rounds to even.\n"
+    "\n"
+    ">>> sc.round([0.5, 1.5])\n"
+    "array([0., 2.])")
+ufunc_round_loops[0] = loop_d_d__As_f_f
+ufunc_round_loops[1] = loop_d_d__As_d_d
+ufunc_round_types[0] = NPY_FLOAT
+ufunc_round_types[1] = NPY_FLOAT
+ufunc_round_types[2] = NPY_DOUBLE
+ufunc_round_types[3] = NPY_DOUBLE
+ufunc_round_ptr[2*0] = _func_cephes_round
+ufunc_round_ptr[2*0+1] = ("round")
+ufunc_round_ptr[2*1] = _func_cephes_round
+ufunc_round_ptr[2*1+1] = ("round")
+ufunc_round_data[0] = &ufunc_round_ptr[2*0]
+ufunc_round_data[1] = &ufunc_round_ptr[2*1]
+round = np.PyUFunc_FromFuncAndData(ufunc_round_loops, ufunc_round_data, ufunc_round_types, 2, 1, 1, 0, "round", ufunc_round_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_shichi_loops[4]
+cdef void *ufunc_shichi_ptr[8]
+cdef void *ufunc_shichi_data[4]
+cdef char ufunc_shichi_types[12]
+cdef char *ufunc_shichi_doc = (
+    "shichi(x, out=None)\n"
+    "\n"
+    "Hyperbolic sine and cosine integrals.\n"
+    "\n"
+    "The hyperbolic sine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\int_0^x \\frac{\\sinh{t}}{t}dt\n"
+    "\n"
+    "and the hyperbolic cosine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\gamma + \\log(x) + \\int_0^x \\frac{\\cosh{t} - 1}{t} dt\n"
+    "\n"
+    "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n"
+    "principal branch of the logarithm [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex points at which to compute the hyperbolic sine\n"
+    "    and cosine integrals.\n"
+    "out : tuple of ndarray, optional\n"
+    "    Optional output arrays for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "si : scalar or ndarray\n"
+    "    Hyperbolic sine integral at ``x``\n"
+    "ci : scalar or ndarray\n"
+    "    Hyperbolic cosine integral at ``x``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "sici : Sine and cosine integrals.\n"
+    "exp1 : Exponential integral E1.\n"
+    "expi : Exponential integral Ei.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real arguments with ``x < 0``, ``chi`` is the real part of the\n"
+    "hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x\n"
+    "+ 0j)`` differ by a factor of ``1j*pi``.\n"
+    "\n"
+    "For real arguments the function is computed by calling Cephes'\n"
+    "[2]_ *shichi* routine. For complex arguments the algorithm is based\n"
+    "on Mpmath's [3]_ *shi* and *chi* routines.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "       (See Section 5.2.)\n"
+    ".. [2] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [3] Fredrik Johansson and others.\n"
+    "       \"mpmath: a Python library for arbitrary-precision floating-point\n"
+    "       arithmetic\" (Version 0.19) http://mpmath.org/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import shichi, sici\n"
+    "\n"
+    "`shichi` accepts real or complex input:\n"
+    "\n"
+    ">>> shichi(0.5)\n"
+    "(0.5069967498196671, -0.05277684495649357)\n"
+    ">>> shichi(0.5 + 2.5j)\n"
+    "((0.11772029666668238+1.831091777729851j),\n"
+    " (0.29912435887648825+1.7395351121166562j))\n"
+    "\n"
+    "The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are\n"
+    "related to the sine and cosine integrals Si(z) and Ci(z) by\n"
+    "\n"
+    "* Shi(z) = -i*Si(i*z)\n"
+    "* Chi(z) = Ci(-i*z) + i*pi/2\n"
+    "\n"
+    ">>> z = 0.25 + 5j\n"
+    ">>> shi, chi = shichi(z)\n"
+    ">>> shi, -1j*sici(1j*z)[0]            # Should be the same.\n"
+    "((-0.04834719325101729+1.5469354086921228j),\n"
+    " (-0.04834719325101729+1.5469354086921228j))\n"
+    ">>> chi, sici(-1j*z)[1] + 1j*np.pi/2  # Should be the same.\n"
+    "((-0.19568708973868087+1.556276312103824j),\n"
+    " (-0.19568708973868087+1.556276312103824j))\n"
+    "\n"
+    "Plot the functions evaluated on the real axis:\n"
+    "\n"
+    ">>> xp = np.geomspace(1e-8, 4.0, 250)\n"
+    ">>> x = np.concatenate((-xp[::-1], xp))\n"
+    ">>> shi, chi = shichi(x)\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, shi, label='Shi(x)')\n"
+    ">>> ax.plot(x, chi, '--', label='Chi(x)')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('Hyperbolic Sine and Cosine Integrals')\n"
+    ">>> ax.legend(shadow=True, framealpha=1, loc='lower right')\n"
+    ">>> ax.grid(True)\n"
+    ">>> plt.show()")
+ufunc_shichi_loops[0] = loop_i_d_dd_As_f_ff
+ufunc_shichi_loops[1] = loop_i_d_dd_As_d_dd
+ufunc_shichi_loops[2] = loop_i_D_DD_As_F_FF
+ufunc_shichi_loops[3] = loop_i_D_DD_As_D_DD
+ufunc_shichi_types[0] = NPY_FLOAT
+ufunc_shichi_types[1] = NPY_FLOAT
+ufunc_shichi_types[2] = NPY_FLOAT
+ufunc_shichi_types[3] = NPY_DOUBLE
+ufunc_shichi_types[4] = NPY_DOUBLE
+ufunc_shichi_types[5] = NPY_DOUBLE
+ufunc_shichi_types[6] = NPY_CFLOAT
+ufunc_shichi_types[7] = NPY_CFLOAT
+ufunc_shichi_types[8] = NPY_CFLOAT
+ufunc_shichi_types[9] = NPY_CDOUBLE
+ufunc_shichi_types[10] = NPY_CDOUBLE
+ufunc_shichi_types[11] = NPY_CDOUBLE
+ufunc_shichi_ptr[2*0] = _func_xsf_shichi
+ufunc_shichi_ptr[2*0+1] = ("shichi")
+ufunc_shichi_ptr[2*1] = _func_xsf_shichi
+ufunc_shichi_ptr[2*1+1] = ("shichi")
+ufunc_shichi_ptr[2*2] = _func_xsf_cshichi
+ufunc_shichi_ptr[2*2+1] = ("shichi")
+ufunc_shichi_ptr[2*3] = _func_xsf_cshichi
+ufunc_shichi_ptr[2*3+1] = ("shichi")
+ufunc_shichi_data[0] = &ufunc_shichi_ptr[2*0]
+ufunc_shichi_data[1] = &ufunc_shichi_ptr[2*1]
+ufunc_shichi_data[2] = &ufunc_shichi_ptr[2*2]
+ufunc_shichi_data[3] = &ufunc_shichi_ptr[2*3]
+shichi = np.PyUFunc_FromFuncAndData(ufunc_shichi_loops, ufunc_shichi_data, ufunc_shichi_types, 4, 1, 2, 0, "shichi", ufunc_shichi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_sici_loops[4]
+cdef void *ufunc_sici_ptr[8]
+cdef void *ufunc_sici_data[4]
+cdef char ufunc_sici_types[12]
+cdef char *ufunc_sici_doc = (
+    "sici(x, out=None)\n"
+    "\n"
+    "Sine and cosine integrals.\n"
+    "\n"
+    "The sine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\int_0^x \\frac{\\sin{t}}{t}dt\n"
+    "\n"
+    "and the cosine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\gamma + \\log(x) + \\int_0^x \\frac{\\cos{t} - 1}{t}dt\n"
+    "\n"
+    "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n"
+    "principal branch of the logarithm [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex points at which to compute the sine and cosine\n"
+    "    integrals.\n"
+    "out : tuple of ndarray, optional\n"
+    "    Optional output arrays for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "si : scalar or ndarray\n"
+    "    Sine integral at ``x``\n"
+    "ci : scalar or ndarray\n"
+    "    Cosine integral at ``x``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "shichi : Hyperbolic sine and cosine integrals.\n"
+    "exp1 : Exponential integral E1.\n"
+    "expi : Exponential integral Ei.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real arguments with ``x < 0``, ``ci`` is the real part of the\n"
+    "cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``\n"
+    "differ by a factor of ``1j*pi``.\n"
+    "\n"
+    "For real arguments the function is computed by calling Cephes'\n"
+    "[2]_ *sici* routine. For complex arguments the algorithm is based\n"
+    "on Mpmath's [3]_ *si* and *ci* routines.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "       (See Section 5.2.)\n"
+    ".. [2] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [3] Fredrik Johansson and others.\n"
+    "       \"mpmath: a Python library for arbitrary-precision floating-point\n"
+    "       arithmetic\" (Version 0.19) http://mpmath.org/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import sici, exp1\n"
+    "\n"
+    "`sici` accepts real or complex input:\n"
+    "\n"
+    ">>> sici(2.5)\n"
+    "(1.7785201734438267, 0.2858711963653835)\n"
+    ">>> sici(2.5 + 3j)\n"
+    "((4.505735874563953+0.06863305018999577j),\n"
+    "(0.0793644206906966-2.935510262937543j))\n"
+    "\n"
+    "For z in the right half plane, the sine and cosine integrals are\n"
+    "related to the exponential integral E1 (implemented in SciPy as\n"
+    "`scipy.special.exp1`) by\n"
+    "\n"
+    "* Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2\n"
+    "* Ci(z) = -(E1(i*z) + E1(-i*z))/2\n"
+    "\n"
+    "See [1]_ (equations 5.2.21 and 5.2.23).\n"
+    "\n"
+    "We can verify these relations:\n"
+    "\n"
+    ">>> z = 2 - 3j\n"
+    ">>> sici(z)\n"
+    "((4.54751388956229-1.3991965806460565j),\n"
+    "(1.408292501520851+2.9836177420296055j))\n"
+    "\n"
+    ">>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2  # Same as sine integral\n"
+    "(4.54751388956229-1.3991965806460565j)\n"
+    "\n"
+    ">>> -(exp1(1j*z) + exp1(-1j*z))/2            # Same as cosine integral\n"
+    "(1.408292501520851+2.9836177420296055j)\n"
+    "\n"
+    "Plot the functions evaluated on the real axis; the dotted horizontal\n"
+    "lines are at pi/2 and -pi/2:\n"
+    "\n"
+    ">>> x = np.linspace(-16, 16, 150)\n"
+    ">>> si, ci = sici(x)\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, si, label='Si(x)')\n"
+    ">>> ax.plot(x, ci, '--', label='Ci(x)')\n"
+    ">>> ax.legend(shadow=True, framealpha=1, loc='upper left')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('Sine and Cosine Integrals')\n"
+    ">>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')\n"
+    ">>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')\n"
+    ">>> ax.grid(True)\n"
+    ">>> plt.show()")
+ufunc_sici_loops[0] = loop_i_d_dd_As_f_ff
+ufunc_sici_loops[1] = loop_i_d_dd_As_d_dd
+ufunc_sici_loops[2] = loop_i_D_DD_As_F_FF
+ufunc_sici_loops[3] = loop_i_D_DD_As_D_DD
+ufunc_sici_types[0] = NPY_FLOAT
+ufunc_sici_types[1] = NPY_FLOAT
+ufunc_sici_types[2] = NPY_FLOAT
+ufunc_sici_types[3] = NPY_DOUBLE
+ufunc_sici_types[4] = NPY_DOUBLE
+ufunc_sici_types[5] = NPY_DOUBLE
+ufunc_sici_types[6] = NPY_CFLOAT
+ufunc_sici_types[7] = NPY_CFLOAT
+ufunc_sici_types[8] = NPY_CFLOAT
+ufunc_sici_types[9] = NPY_CDOUBLE
+ufunc_sici_types[10] = NPY_CDOUBLE
+ufunc_sici_types[11] = NPY_CDOUBLE
+ufunc_sici_ptr[2*0] = _func_xsf_sici
+ufunc_sici_ptr[2*0+1] = ("sici")
+ufunc_sici_ptr[2*1] = _func_xsf_sici
+ufunc_sici_ptr[2*1+1] = ("sici")
+ufunc_sici_ptr[2*2] = _func_xsf_csici
+ufunc_sici_ptr[2*2+1] = ("sici")
+ufunc_sici_ptr[2*3] = _func_xsf_csici
+ufunc_sici_ptr[2*3+1] = ("sici")
+ufunc_sici_data[0] = &ufunc_sici_ptr[2*0]
+ufunc_sici_data[1] = &ufunc_sici_ptr[2*1]
+ufunc_sici_data[2] = &ufunc_sici_ptr[2*2]
+ufunc_sici_data[3] = &ufunc_sici_ptr[2*3]
+sici = np.PyUFunc_FromFuncAndData(ufunc_sici_loops, ufunc_sici_data, ufunc_sici_types, 4, 1, 2, 0, "sici", ufunc_sici_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_smirnov_loops[3]
+cdef void *ufunc_smirnov_ptr[6]
+cdef void *ufunc_smirnov_data[3]
+cdef char ufunc_smirnov_types[9]
+cdef char *ufunc_smirnov_doc = (
+    "smirnov(n, d, out=None)\n"
+    "\n"
+    "Kolmogorov-Smirnov complementary cumulative distribution function\n"
+    "\n"
+    "Returns the exact Kolmogorov-Smirnov complementary cumulative\n"
+    "distribution function,(aka the Survival Function) of Dn+ (or Dn-)\n"
+    "for a one-sided test of equality between an empirical and a\n"
+    "theoretical distribution. It is equal to the probability that the\n"
+    "maximum difference between a theoretical distribution and an empirical\n"
+    "one based on `n` samples is greater than d.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "  Number of samples\n"
+    "d : float array_like\n"
+    "  Deviation between the Empirical CDF (ECDF) and the target CDF.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "smirnovi : The Inverse Survival Function for the distribution\n"
+    "scipy.stats.ksone : Provides the functionality as a continuous distribution\n"
+    "kolmogorov, kolmogi : Functions for the two-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`smirnov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.ksone` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import smirnov\n"
+    ">>> from scipy.stats import norm\n"
+    "\n"
+    "Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a\n"
+    "sample of size 5.\n"
+    "\n"
+    ">>> smirnov(5, [0, 0.5, 1.0])\n"
+    "array([ 1.   ,  0.056,  0.   ])\n"
+    "\n"
+    "Compare a sample of size 5 against N(0, 1), the standard normal\n"
+    "distribution with mean 0 and standard deviation 1.\n"
+    "\n"
+    "`x` is the sample.\n"
+    "\n"
+    ">>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])\n"
+    "\n"
+    ">>> target = norm(0, 1)\n"
+    ">>> cdfs = target.cdf(x)\n"
+    ">>> cdfs\n"
+    "array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])\n"
+    "\n"
+    "Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).\n"
+    "\n"
+    ">>> n = len(x)\n"
+    ">>> ecdfs = np.arange(n+1, dtype=float)/n\n"
+    ">>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],\n"
+    "...                        ecdfs[1:] - cdfs])\n"
+    ">>> with np.printoptions(precision=3):\n"
+    "...    print(cols)\n"
+    "[[-1.392  0.2    0.082  0.082  0.118]\n"
+    " [-0.135  0.4    0.446  0.246 -0.046]\n"
+    " [ 0.114  0.6    0.545  0.145  0.055]\n"
+    " [ 0.19   0.8    0.575 -0.025  0.225]\n"
+    " [ 1.82   1.     0.966  0.166  0.034]]\n"
+    ">>> gaps = cols[:, -2:]\n"
+    ">>> Dnpm = np.max(gaps, axis=0)\n"
+    ">>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')\n"
+    "Dn-=0.246306, Dn+=0.224655\n"
+    ">>> probs = smirnov(n, Dnpm)\n"
+    ">>> print(f'For a sample of size {n} drawn from N(0, 1):',\n"
+    "...       f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',\n"
+    "...       f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',\n"
+    "...       sep='\\n')\n"
+    "For a sample of size 5 drawn from N(0, 1):\n"
+    " Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711\n"
+    " Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245\n"
+    "\n"
+    "Plot the empirical CDF and the standard normal CDF.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> plt.step(np.concatenate(([-2.5], x, [2.5])),\n"
+    "...          np.concatenate((ecdfs, [1])),\n"
+    "...          where='post', label='Empirical CDF')\n"
+    ">>> xx = np.linspace(-2.5, 2.5, 100)\n"
+    ">>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')\n"
+    "\n"
+    "Add vertical lines marking Dn+ and Dn-.\n"
+    "\n"
+    ">>> iminus, iplus = np.argmax(gaps, axis=0)\n"
+    ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',\n"
+    "...            alpha=0.5, lw=4)\n"
+    ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',\n"
+    "...            alpha=0.5, lw=4)\n"
+    "\n"
+    ">>> plt.grid(True)\n"
+    ">>> plt.legend(framealpha=1, shadow=True)\n"
+    ">>> plt.show()")
+ufunc_smirnov_loops[0] = loop_d_pd__As_pd_d
+ufunc_smirnov_loops[1] = loop_d_dd__As_ff_f
+ufunc_smirnov_loops[2] = loop_d_dd__As_dd_d
+ufunc_smirnov_types[0] = NPY_INTP
+ufunc_smirnov_types[1] = NPY_DOUBLE
+ufunc_smirnov_types[2] = NPY_DOUBLE
+ufunc_smirnov_types[3] = NPY_FLOAT
+ufunc_smirnov_types[4] = NPY_FLOAT
+ufunc_smirnov_types[5] = NPY_FLOAT
+ufunc_smirnov_types[6] = NPY_DOUBLE
+ufunc_smirnov_types[7] = NPY_DOUBLE
+ufunc_smirnov_types[8] = NPY_DOUBLE
+ufunc_smirnov_ptr[2*0] = _func_cephes_smirnov_wrap
+ufunc_smirnov_ptr[2*0+1] = ("smirnov")
+ufunc_smirnov_ptr[2*1] = _func_smirnov_unsafe
+ufunc_smirnov_ptr[2*1+1] = ("smirnov")
+ufunc_smirnov_ptr[2*2] = _func_smirnov_unsafe
+ufunc_smirnov_ptr[2*2+1] = ("smirnov")
+ufunc_smirnov_data[0] = &ufunc_smirnov_ptr[2*0]
+ufunc_smirnov_data[1] = &ufunc_smirnov_ptr[2*1]
+ufunc_smirnov_data[2] = &ufunc_smirnov_ptr[2*2]
+smirnov = np.PyUFunc_FromFuncAndData(ufunc_smirnov_loops, ufunc_smirnov_data, ufunc_smirnov_types, 3, 2, 1, 0, "smirnov", ufunc_smirnov_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_smirnovi_loops[3]
+cdef void *ufunc_smirnovi_ptr[6]
+cdef void *ufunc_smirnovi_data[3]
+cdef char ufunc_smirnovi_types[9]
+cdef char *ufunc_smirnovi_doc = (
+    "smirnovi(n, p, out=None)\n"
+    "\n"
+    "Inverse to `smirnov`\n"
+    "\n"
+    "Returns `d` such that ``smirnov(n, d) == p``, the critical value\n"
+    "corresponding to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "  Number of samples\n"
+    "p : float array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of smirnovi(n, p), the critical values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "smirnov : The Survival Function (SF) for the distribution\n"
+    "scipy.stats.ksone : Provides the functionality as a continuous distribution\n"
+    "kolmogorov, kolmogi : Functions for the two-sided distribution\n"
+    "scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`smirnov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.ksone` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import smirnovi, smirnov\n"
+    "\n"
+    ">>> n = 24\n"
+    ">>> deviations = [0.1, 0.2, 0.3]\n"
+    "\n"
+    "Use `smirnov` to compute the complementary CDF of the Smirnov\n"
+    "distribution for the given number of samples and deviations.\n"
+    "\n"
+    ">>> p = smirnov(n, deviations)\n"
+    ">>> p\n"
+    "array([0.58105083, 0.12826832, 0.01032231])\n"
+    "\n"
+    "The inverse function ``smirnovi(n, p)`` returns ``deviations``.\n"
+    "\n"
+    ">>> smirnovi(n, p)\n"
+    "array([0.1, 0.2, 0.3])")
+ufunc_smirnovi_loops[0] = loop_d_pd__As_pd_d
+ufunc_smirnovi_loops[1] = loop_d_dd__As_ff_f
+ufunc_smirnovi_loops[2] = loop_d_dd__As_dd_d
+ufunc_smirnovi_types[0] = NPY_INTP
+ufunc_smirnovi_types[1] = NPY_DOUBLE
+ufunc_smirnovi_types[2] = NPY_DOUBLE
+ufunc_smirnovi_types[3] = NPY_FLOAT
+ufunc_smirnovi_types[4] = NPY_FLOAT
+ufunc_smirnovi_types[5] = NPY_FLOAT
+ufunc_smirnovi_types[6] = NPY_DOUBLE
+ufunc_smirnovi_types[7] = NPY_DOUBLE
+ufunc_smirnovi_types[8] = NPY_DOUBLE
+ufunc_smirnovi_ptr[2*0] = _func_cephes_smirnovi_wrap
+ufunc_smirnovi_ptr[2*0+1] = ("smirnovi")
+ufunc_smirnovi_ptr[2*1] = _func_smirnovi_unsafe
+ufunc_smirnovi_ptr[2*1+1] = ("smirnovi")
+ufunc_smirnovi_ptr[2*2] = _func_smirnovi_unsafe
+ufunc_smirnovi_ptr[2*2+1] = ("smirnovi")
+ufunc_smirnovi_data[0] = &ufunc_smirnovi_ptr[2*0]
+ufunc_smirnovi_data[1] = &ufunc_smirnovi_ptr[2*1]
+ufunc_smirnovi_data[2] = &ufunc_smirnovi_ptr[2*2]
+smirnovi = np.PyUFunc_FromFuncAndData(ufunc_smirnovi_loops, ufunc_smirnovi_data, ufunc_smirnovi_types, 3, 2, 1, 0, "smirnovi", ufunc_smirnovi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_spence_loops[4]
+cdef void *ufunc_spence_ptr[8]
+cdef void *ufunc_spence_data[4]
+cdef char ufunc_spence_types[8]
+cdef char *ufunc_spence_doc = (
+    "spence(z, out=None)\n"
+    "\n"
+    "Spence's function, also known as the dilogarithm.\n"
+    "\n"
+    "It is defined to be\n"
+    "\n"
+    ".. math::\n"
+    "  \\int_1^z \\frac{\\log(t)}{1 - t}dt\n"
+    "\n"
+    "for complex :math:`z`, where the contour of integration is taken\n"
+    "to avoid the branch cut of the logarithm. Spence's function is\n"
+    "analytic everywhere except the negative real axis where it has a\n"
+    "branch cut.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Points at which to evaluate Spence's function\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "s : scalar or ndarray\n"
+    "    Computed values of Spence's function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "There is a different convention which defines Spence's function by\n"
+    "the integral\n"
+    "\n"
+    ".. math::\n"
+    "  -\\int_0^z \\frac{\\log(1 - t)}{t}dt;\n"
+    "\n"
+    "this is our ``spence(1 - z)``.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import spence\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "The function is defined for complex inputs:\n"
+    "\n"
+    ">>> spence([1-1j, 1.5+2j, 3j, -10-5j])\n"
+    "array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,\n"
+    "       -0.59422064-2.49129918j, -1.14044398+6.80075924j])\n"
+    "\n"
+    "For complex inputs on the branch cut, which is the negative real axis,\n"
+    "the function returns the limit for ``z`` with positive imaginary part.\n"
+    "For example, in the following, note the sign change of the imaginary\n"
+    "part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:\n"
+    "\n"
+    ">>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])\n"
+    "array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,\n"
+    "       2.32018041+3.45139229j])\n"
+    "\n"
+    "The function returns ``nan`` for real inputs on the branch cut:\n"
+    "\n"
+    ">>> spence(-1.5)\n"
+    "nan\n"
+    "\n"
+    "Verify some particular values: ``spence(0) = pi**2/6``,\n"
+    "``spence(1) = 0`` and ``spence(2) = -pi**2/12``.\n"
+    "\n"
+    ">>> spence([0, 1, 2])\n"
+    "array([ 1.64493407,  0.        , -0.82246703])\n"
+    ">>> np.pi**2/6, -np.pi**2/12\n"
+    "(1.6449340668482264, -0.8224670334241132)\n"
+    "\n"
+    "Verify the identity::\n"
+    "\n"
+    "    spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)\n"
+    "\n"
+    ">>> z = 3 + 4j\n"
+    ">>> spence(z) + spence(1 - z)\n"
+    "(-2.6523186143876067+1.8853470951513935j)\n"
+    ">>> np.pi**2/6 - np.log(z)*np.log(1 - z)\n"
+    "(-2.652318614387606+1.885347095151394j)\n"
+    "\n"
+    "Plot the function for positive real input.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(0, 6, 400)\n"
+    ">>> ax.plot(x, spence(x))\n"
+    ">>> ax.grid()\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('spence(x)')\n"
+    ">>> plt.show()")
+ufunc_spence_loops[0] = loop_d_d__As_f_f
+ufunc_spence_loops[1] = loop_d_d__As_d_d
+ufunc_spence_loops[2] = loop_D_D__As_F_F
+ufunc_spence_loops[3] = loop_D_D__As_D_D
+ufunc_spence_types[0] = NPY_FLOAT
+ufunc_spence_types[1] = NPY_FLOAT
+ufunc_spence_types[2] = NPY_DOUBLE
+ufunc_spence_types[3] = NPY_DOUBLE
+ufunc_spence_types[4] = NPY_CFLOAT
+ufunc_spence_types[5] = NPY_CFLOAT
+ufunc_spence_types[6] = NPY_CDOUBLE
+ufunc_spence_types[7] = NPY_CDOUBLE
+ufunc_spence_ptr[2*0] = _func_cephes_spence
+ufunc_spence_ptr[2*0+1] = ("spence")
+ufunc_spence_ptr[2*1] = _func_cephes_spence
+ufunc_spence_ptr[2*1+1] = ("spence")
+ufunc_spence_ptr[2*2] = _func_cspence
+ufunc_spence_ptr[2*2+1] = ("spence")
+ufunc_spence_ptr[2*3] = _func_cspence
+ufunc_spence_ptr[2*3+1] = ("spence")
+ufunc_spence_data[0] = &ufunc_spence_ptr[2*0]
+ufunc_spence_data[1] = &ufunc_spence_ptr[2*1]
+ufunc_spence_data[2] = &ufunc_spence_ptr[2*2]
+ufunc_spence_data[3] = &ufunc_spence_ptr[2*3]
+spence = np.PyUFunc_FromFuncAndData(ufunc_spence_loops, ufunc_spence_data, ufunc_spence_types, 4, 1, 1, 0, "spence", ufunc_spence_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtr_loops[2]
+cdef void *ufunc_stdtr_ptr[4]
+cdef void *ufunc_stdtr_data[2]
+cdef char ufunc_stdtr_types[6]
+cdef char *ufunc_stdtr_doc = (
+    "stdtr(df, t, out=None)\n"
+    "\n"
+    "Student t distribution cumulative distribution function\n"
+    "\n"
+    "Returns the integral:\n"
+    "\n"
+    ".. math::\n"
+    "    \\frac{\\Gamma((df+1)/2)}{\\sqrt{\\pi df} \\Gamma(df/2)}\n"
+    "    \\int_{-\\infty}^t (1+x^2/df)^{-(df+1)/2}\\, dx\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom\n"
+    "t : array_like\n"
+    "    Upper bound of the integral\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Student t CDF at t\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtridf : inverse of stdtr with respect to `df`\n"
+    "stdtrit : inverse of stdtr with respect to `t`\n"
+    "scipy.stats.t : student t distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The student t distribution is also available as `scipy.stats.t`.\n"
+    "Calling `stdtr` directly can improve performance compared to the\n"
+    "``cdf`` method of `scipy.stats.t` (see last example below).\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``df=3`` at ``t=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import stdtr\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> stdtr(3, 1)\n"
+    "0.8044988905221148\n"
+    "\n"
+    "Plot the function for three different degrees of freedom.\n"
+    "\n"
+    ">>> x = np.linspace(-10, 10, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> parameters = [(1, \"solid\"), (3, \"dashed\"), (10, \"dotted\")]\n"
+    ">>> for (df, linestyle) in parameters:\n"
+    "...     ax.plot(x, stdtr(df, x), ls=linestyle, label=f\"$df={df}$\")\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_title(\"Student t distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The function can be computed for several degrees of freedom at the same\n"
+    "time by providing a NumPy array or list for `df`:\n"
+    "\n"
+    ">>> stdtr([1, 2, 3], 1)\n"
+    "array([0.75      , 0.78867513, 0.80449889])\n"
+    "\n"
+    "It is possible to calculate the function at several points for several\n"
+    "different degrees of freedom simultaneously by providing arrays for `df`\n"
+    "and `t` with shapes compatible for broadcasting. Compute `stdtr` at\n"
+    "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n"
+    "\n"
+    ">>> dfs = np.array([[1], [2], [3]])\n"
+    ">>> t = np.array([2, 4, 6, 8])\n"
+    ">>> dfs.shape, t.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> stdtr(dfs, t)\n"
+    "array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],\n"
+    "       [0.90824829, 0.97140452, 0.98666426, 0.99236596],\n"
+    "       [0.93033702, 0.98599577, 0.99536364, 0.99796171]])\n"
+    "\n"
+    "The t distribution is also available as `scipy.stats.t`. Calling `stdtr`\n"
+    "directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.t`. To get the same results, one must use the following\n"
+    "parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import t\n"
+    ">>> df, x = 3, 1\n"
+    ">>> stdtr_result = stdtr(df, x)  # this can be faster than below\n"
+    ">>> stats_result = t(df).cdf(x)\n"
+    ">>> stats_result == stdtr_result  # test that results are equal\n"
+    "True")
+ufunc_stdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtr_types[0] = NPY_FLOAT
+ufunc_stdtr_types[1] = NPY_FLOAT
+ufunc_stdtr_types[2] = NPY_FLOAT
+ufunc_stdtr_types[3] = NPY_DOUBLE
+ufunc_stdtr_types[4] = NPY_DOUBLE
+ufunc_stdtr_types[5] = NPY_DOUBLE
+ufunc_stdtr_ptr[2*0] = _func_stdtr
+ufunc_stdtr_ptr[2*0+1] = ("stdtr")
+ufunc_stdtr_ptr[2*1] = _func_stdtr
+ufunc_stdtr_ptr[2*1+1] = ("stdtr")
+ufunc_stdtr_data[0] = &ufunc_stdtr_ptr[2*0]
+ufunc_stdtr_data[1] = &ufunc_stdtr_ptr[2*1]
+stdtr = np.PyUFunc_FromFuncAndData(ufunc_stdtr_loops, ufunc_stdtr_data, ufunc_stdtr_types, 2, 2, 1, 0, "stdtr", ufunc_stdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtridf_loops[2]
+cdef void *ufunc_stdtridf_ptr[4]
+cdef void *ufunc_stdtridf_data[2]
+cdef char ufunc_stdtridf_types[6]
+cdef char *ufunc_stdtridf_doc = (
+    "stdtridf(p, t, out=None)\n"
+    "\n"
+    "Inverse of `stdtr` vs df\n"
+    "\n"
+    "Returns the argument df such that stdtr(df, t) is equal to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "t : array_like\n"
+    "    Upper bound of the integral\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    Value of `df` such that ``stdtr(df, t) == p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtr : Student t CDF\n"
+    "stdtrit : inverse of stdtr with respect to `t`\n"
+    "scipy.stats.t : Student t distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the student t cumulative distribution function for one\n"
+    "parameter set.\n"
+    "\n"
+    ">>> from scipy.special import stdtr, stdtridf\n"
+    ">>> df, x = 5, 2\n"
+    ">>> cdf_value = stdtr(df, x)\n"
+    ">>> cdf_value\n"
+    "0.9490302605850709\n"
+    "\n"
+    "Verify that `stdtridf` recovers the original value for `df` given\n"
+    "the CDF value and `x`.\n"
+    "\n"
+    ">>> stdtridf(cdf_value, x)\n"
+    "5.0")
+ufunc_stdtridf_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtridf_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtridf_types[0] = NPY_FLOAT
+ufunc_stdtridf_types[1] = NPY_FLOAT
+ufunc_stdtridf_types[2] = NPY_FLOAT
+ufunc_stdtridf_types[3] = NPY_DOUBLE
+ufunc_stdtridf_types[4] = NPY_DOUBLE
+ufunc_stdtridf_types[5] = NPY_DOUBLE
+ufunc_stdtridf_ptr[2*0] = _func_stdtridf
+ufunc_stdtridf_ptr[2*0+1] = ("stdtridf")
+ufunc_stdtridf_ptr[2*1] = _func_stdtridf
+ufunc_stdtridf_ptr[2*1+1] = ("stdtridf")
+ufunc_stdtridf_data[0] = &ufunc_stdtridf_ptr[2*0]
+ufunc_stdtridf_data[1] = &ufunc_stdtridf_ptr[2*1]
+stdtridf = np.PyUFunc_FromFuncAndData(ufunc_stdtridf_loops, ufunc_stdtridf_data, ufunc_stdtridf_types, 2, 2, 1, 0, "stdtridf", ufunc_stdtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtrit_loops[2]
+cdef void *ufunc_stdtrit_ptr[4]
+cdef void *ufunc_stdtrit_data[2]
+cdef char ufunc_stdtrit_types[6]
+cdef char *ufunc_stdtrit_doc = (
+    "stdtrit(df, p, out=None)\n"
+    "\n"
+    "The `p`-th quantile of the student t distribution.\n"
+    "\n"
+    "This function is the inverse of the student t distribution cumulative\n"
+    "distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.\n"
+    "\n"
+    "Returns the argument `t` such that stdtr(df, t) is equal to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t : scalar or ndarray\n"
+    "    Value of `t` such that ``stdtr(df, t) == p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtr : Student t CDF\n"
+    "stdtridf : inverse of stdtr with respect to `df`\n"
+    "scipy.stats.t : Student t distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The student t distribution is also available as `scipy.stats.t`. Calling\n"
+    "`stdtrit` directly can improve performance compared to the ``ppf``\n"
+    "method of `scipy.stats.t` (see last example below).\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`stdtrit` represents the inverse of the student t distribution CDF which\n"
+    "is available as `stdtr`. Here, we calculate the CDF for ``df`` at\n"
+    "``x=1``. `stdtrit` then returns ``1`` up to floating point errors\n"
+    "given the same value for `df` and the computed CDF value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import stdtr, stdtrit\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> df = 3\n"
+    ">>> x = 1\n"
+    ">>> cdf_value = stdtr(df, x)\n"
+    ">>> stdtrit(df, cdf_value)\n"
+    "0.9999999994418539\n"
+    "\n"
+    "Plot the function for three different degrees of freedom.\n"
+    "\n"
+    ">>> x = np.linspace(0, 1, 1000)\n"
+    ">>> parameters = [(1, \"solid\"), (2, \"dashed\"), (5, \"dotted\")]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for (df, linestyle) in parameters:\n"
+    "...     ax.plot(x, stdtrit(df, x), ls=linestyle, label=f\"$df={df}$\")\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylim(-10, 10)\n"
+    ">>> ax.set_title(\"Student t distribution quantile function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The function can be computed for several degrees of freedom at the same\n"
+    "time by providing a NumPy array or list for `df`:\n"
+    "\n"
+    ">>> stdtrit([1, 2, 3], 0.7)\n"
+    "array([0.72654253, 0.6172134 , 0.58438973])\n"
+    "\n"
+    "It is possible to calculate the function at several points for several\n"
+    "different degrees of freedom simultaneously by providing arrays for `df`\n"
+    "and `p` with shapes compatible for broadcasting. Compute `stdtrit` at\n"
+    "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n"
+    "\n"
+    ">>> dfs = np.array([[1], [2], [3]])\n"
+    ">>> p = np.array([0.2, 0.4, 0.7, 0.8])\n"
+    ">>> dfs.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> stdtrit(dfs, p)\n"
+    "array([[-1.37638192, -0.3249197 ,  0.72654253,  1.37638192],\n"
+    "       [-1.06066017, -0.28867513,  0.6172134 ,  1.06066017],\n"
+    "       [-0.97847231, -0.27667066,  0.58438973,  0.97847231]])\n"
+    "\n"
+    "The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`\n"
+    "directly can be much faster than calling the ``ppf`` method of\n"
+    "`scipy.stats.t`. To get the same results, one must use the following\n"
+    "parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import t\n"
+    ">>> df, x = 3, 0.5\n"
+    ">>> stdtrit_result = stdtrit(df, x)  # this can be faster than below\n"
+    ">>> stats_result = t(df).ppf(x)\n"
+    ">>> stats_result == stdtrit_result  # test that results are equal\n"
+    "True")
+ufunc_stdtrit_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtrit_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtrit_types[0] = NPY_FLOAT
+ufunc_stdtrit_types[1] = NPY_FLOAT
+ufunc_stdtrit_types[2] = NPY_FLOAT
+ufunc_stdtrit_types[3] = NPY_DOUBLE
+ufunc_stdtrit_types[4] = NPY_DOUBLE
+ufunc_stdtrit_types[5] = NPY_DOUBLE
+ufunc_stdtrit_ptr[2*0] = _func_stdtrit
+ufunc_stdtrit_ptr[2*0+1] = ("stdtrit")
+ufunc_stdtrit_ptr[2*1] = _func_stdtrit
+ufunc_stdtrit_ptr[2*1+1] = ("stdtrit")
+ufunc_stdtrit_data[0] = &ufunc_stdtrit_ptr[2*0]
+ufunc_stdtrit_data[1] = &ufunc_stdtrit_ptr[2*1]
+stdtrit = np.PyUFunc_FromFuncAndData(ufunc_stdtrit_loops, ufunc_stdtrit_data, ufunc_stdtrit_types, 2, 2, 1, 0, "stdtrit", ufunc_stdtrit_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_tklmbda_loops[2]
+cdef void *ufunc_tklmbda_ptr[4]
+cdef void *ufunc_tklmbda_data[2]
+cdef char ufunc_tklmbda_types[6]
+cdef char *ufunc_tklmbda_doc = (
+    "tklmbda(x, lmbda, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the Tukey lambda distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, lmbda : array_like\n"
+    "    Parameters\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    Value of the Tukey lambda CDF\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.tukeylambda : Tukey lambda distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import tklmbda, expit\n"
+    "\n"
+    "Compute the cumulative distribution function (CDF) of the Tukey lambda\n"
+    "distribution at several ``x`` values for `lmbda` = -1.5.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 9)\n"
+    ">>> x\n"
+    "array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])\n"
+    ">>> tklmbda(x, -1.5)\n"
+    "array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5       ,\n"
+    "       0.54370263, 0.58471195, 0.6213446 , 0.65311266])\n"
+    "\n"
+    "When `lmbda` is 0, the function is the logistic sigmoid function,\n"
+    "which is implemented in `scipy.special` as `expit`.\n"
+    "\n"
+    ">>> tklmbda(x, 0)\n"
+    "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,\n"
+    "       0.62245933, 0.73105858, 0.81757448, 0.88079708])\n"
+    ">>> expit(x)\n"
+    "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,\n"
+    "       0.62245933, 0.73105858, 0.81757448, 0.88079708])\n"
+    "\n"
+    "When `lmbda` is 1, the Tukey lambda distribution is uniform on the\n"
+    "interval [-1, 1], so the CDF increases linearly.\n"
+    "\n"
+    ">>> t = np.linspace(-1, 1, 9)\n"
+    ">>> tklmbda(t, 1)\n"
+    "array([0.   , 0.125, 0.25 , 0.375, 0.5  , 0.625, 0.75 , 0.875, 1.   ])\n"
+    "\n"
+    "In the following, we generate plots for several values of `lmbda`.\n"
+    "\n"
+    "The first figure shows graphs for `lmbda` <= 0.\n"
+    "\n"
+    ">>> styles = ['-', '-.', '--', ':']\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(-12, 12, 500)\n"
+    ">>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):\n"
+    "...     y = tklmbda(x, lmbda)\n"
+    "...     ax.plot(x, y, styles[k], label=rf'$\\lambda$ = {lmbda:-4.1f}')\n"
+    "\n"
+    ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n"
+    ">>> ax.set_label('x')\n"
+    ">>> ax.legend(framealpha=1, shadow=True)\n"
+    ">>> ax.grid(True)\n"
+    "\n"
+    "The second figure shows graphs for `lmbda` > 0.  The dots in the\n"
+    "graphs show the bounds of the support of the distribution.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(-4.2, 4.2, 500)\n"
+    ">>> lmbdas = [0.25, 0.5, 1.0, 1.5]\n"
+    ">>> for k, lmbda in enumerate(lmbdas):\n"
+    "...     y = tklmbda(x, lmbda)\n"
+    "...     ax.plot(x, y, styles[k], label=fr'$\\lambda$ = {lmbda}')\n"
+    "\n"
+    ">>> ax.set_prop_cycle(None)\n"
+    ">>> for lmbda in lmbdas:\n"
+    "...     ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)\n"
+    "\n"
+    ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.legend(framealpha=1, shadow=True)\n"
+    ">>> ax.grid(True)\n"
+    "\n"
+    ">>> plt.tight_layout()\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The CDF of the Tukey lambda distribution is also implemented as the\n"
+    "``cdf`` method of `scipy.stats.tukeylambda`.  In the following,\n"
+    "``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the\n"
+    "same values:\n"
+    "\n"
+    ">>> from scipy.stats import tukeylambda\n"
+    ">>> x = np.linspace(-2, 2, 9)\n"
+    "\n"
+    ">>> tukeylambda.cdf(x, -0.5)\n"
+    "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,\n"
+    "       0.58671839, 0.66458323, 0.72906142, 0.78004843])\n"
+    "\n"
+    ">>> tklmbda(x, -0.5)\n"
+    "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,\n"
+    "       0.58671839, 0.66458323, 0.72906142, 0.78004843])\n"
+    "\n"
+    "The implementation in ``tukeylambda`` also provides location and scale\n"
+    "parameters, and other methods such as ``pdf()`` (the probability\n"
+    "density function) and ``ppf()`` (the inverse of the CDF), so for\n"
+    "working with the Tukey lambda distribution, ``tukeylambda`` is more\n"
+    "generally useful.  The primary advantage of ``tklmbda`` is that it is\n"
+    "significantly faster than ``tukeylambda.cdf``.")
+ufunc_tklmbda_loops[0] = loop_d_dd__As_ff_f
+ufunc_tklmbda_loops[1] = loop_d_dd__As_dd_d
+ufunc_tklmbda_types[0] = NPY_FLOAT
+ufunc_tklmbda_types[1] = NPY_FLOAT
+ufunc_tklmbda_types[2] = NPY_FLOAT
+ufunc_tklmbda_types[3] = NPY_DOUBLE
+ufunc_tklmbda_types[4] = NPY_DOUBLE
+ufunc_tklmbda_types[5] = NPY_DOUBLE
+ufunc_tklmbda_ptr[2*0] = _func_xsf_tukeylambdacdf
+ufunc_tklmbda_ptr[2*0+1] = ("tklmbda")
+ufunc_tklmbda_ptr[2*1] = _func_xsf_tukeylambdacdf
+ufunc_tklmbda_ptr[2*1+1] = ("tklmbda")
+ufunc_tklmbda_data[0] = &ufunc_tklmbda_ptr[2*0]
+ufunc_tklmbda_data[1] = &ufunc_tklmbda_ptr[2*1]
+tklmbda = np.PyUFunc_FromFuncAndData(ufunc_tklmbda_loops, ufunc_tklmbda_data, ufunc_tklmbda_types, 2, 2, 1, 0, "tklmbda", ufunc_tklmbda_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_voigt_profile_loops[2]
+cdef void *ufunc_voigt_profile_ptr[4]
+cdef void *ufunc_voigt_profile_data[2]
+cdef char ufunc_voigt_profile_types[8]
+cdef char *ufunc_voigt_profile_doc = (
+    "voigt_profile(x, sigma, gamma, out=None)\n"
+    "\n"
+    "Voigt profile.\n"
+    "\n"
+    "The Voigt profile is a convolution of a 1-D Normal distribution with\n"
+    "standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at\n"
+    "half-maximum ``gamma``.\n"
+    "\n"
+    "If ``sigma = 0``, PDF of Cauchy distribution is returned.\n"
+    "Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.\n"
+    "If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,\n"
+    "and ``0`` for all other ``x``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real argument\n"
+    "sigma : array_like\n"
+    "    The standard deviation of the Normal distribution part\n"
+    "gamma : array_like\n"
+    "    The half-width at half-maximum of the Cauchy distribution part\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The Voigt profile at the given arguments\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "wofz : Faddeeva function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "It can be expressed in terms of Faddeeva function\n"
+    "\n"
+    ".. math:: V(x; \\sigma, \\gamma) = \\frac{Re[w(z)]}{\\sigma\\sqrt{2\\pi}},\n"
+    ".. math:: z = \\frac{x + i\\gamma}{\\sqrt{2}\\sigma}\n"
+    "\n"
+    "where :math:`w(z)` is the Faddeeva function.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Voigt_profile\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.\n"
+    "\n"
+    ">>> from scipy.special import voigt_profile\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> voigt_profile(2, 1., 1.)\n"
+    "0.09071519942627544\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array\n"
+    "for `x`.\n"
+    "\n"
+    ">>> values = np.array([-2., 0., 5])\n"
+    ">>> voigt_profile(values, 1., 1.)\n"
+    "array([0.0907152 , 0.20870928, 0.01388492])\n"
+    "\n"
+    "Plot the function for different parameter sets.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> x = np.linspace(-10, 10, 500)\n"
+    ">>> parameters_list = [(1.5, 0., \"solid\"), (1.3, 0.5, \"dashed\"),\n"
+    "...                    (0., 1.8, \"dotted\"), (1., 1., \"dashdot\")]\n"
+    ">>> for params in parameters_list:\n"
+    "...     sigma, gamma, linestyle = params\n"
+    "...     voigt = voigt_profile(x, sigma, gamma)\n"
+    "...     ax.plot(x, voigt, label=rf\"$\\sigma={sigma},\\, \\gamma={gamma}$\",\n"
+    "...             ls=linestyle)\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Verify visually that the Voigt profile indeed arises as the convolution\n"
+    "of a normal and a Cauchy distribution.\n"
+    "\n"
+    ">>> from scipy.signal import convolve\n"
+    ">>> x, dx = np.linspace(-10, 10, 500, retstep=True)\n"
+    ">>> def gaussian(x, sigma):\n"
+    "...     return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))\n"
+    ">>> def cauchy(x, gamma):\n"
+    "...     return gamma/(np.pi * (np.square(x)+gamma**2))\n"
+    ">>> sigma = 2\n"
+    ">>> gamma = 1\n"
+    ">>> gauss_profile = gaussian(x, sigma)\n"
+    ">>> cauchy_profile = cauchy(x, gamma)\n"
+    ">>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode=\"same\")\n"
+    ">>> voigt = voigt_profile(x, sigma, gamma)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> ax.plot(x, gauss_profile, label=\"Gauss: $G$\", c='b')\n"
+    ">>> ax.plot(x, cauchy_profile, label=\"Cauchy: $C$\", c='y', ls=\"dashed\")\n"
+    ">>> xx = 0.5*(x[1:] + x[:-1])  # midpoints\n"
+    ">>> ax.plot(xx, convolved[1:], label=\"Convolution: $G * C$\", ls='dashdot',\n"
+    "...         c='k')\n"
+    ">>> ax.plot(x, voigt, label=\"Voigt\", ls='dotted', c='r')\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()")
+ufunc_voigt_profile_loops[0] = loop_d_ddd__As_fff_f
+ufunc_voigt_profile_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_voigt_profile_types[0] = NPY_FLOAT
+ufunc_voigt_profile_types[1] = NPY_FLOAT
+ufunc_voigt_profile_types[2] = NPY_FLOAT
+ufunc_voigt_profile_types[3] = NPY_FLOAT
+ufunc_voigt_profile_types[4] = NPY_DOUBLE
+ufunc_voigt_profile_types[5] = NPY_DOUBLE
+ufunc_voigt_profile_types[6] = NPY_DOUBLE
+ufunc_voigt_profile_types[7] = NPY_DOUBLE
+ufunc_voigt_profile_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile
+ufunc_voigt_profile_ptr[2*0+1] = ("voigt_profile")
+ufunc_voigt_profile_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile
+ufunc_voigt_profile_ptr[2*1+1] = ("voigt_profile")
+ufunc_voigt_profile_data[0] = &ufunc_voigt_profile_ptr[2*0]
+ufunc_voigt_profile_data[1] = &ufunc_voigt_profile_ptr[2*1]
+voigt_profile = np.PyUFunc_FromFuncAndData(ufunc_voigt_profile_loops, ufunc_voigt_profile_data, ufunc_voigt_profile_types, 2, 3, 1, 0, "voigt_profile", ufunc_voigt_profile_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_wofz_loops[2]
+cdef void *ufunc_wofz_ptr[4]
+cdef void *ufunc_wofz_data[2]
+cdef char ufunc_wofz_types[4]
+cdef char *ufunc_wofz_doc = (
+    "wofz(z, out=None)\n"
+    "\n"
+    "Faddeeva function\n"
+    "\n"
+    "Returns the value of the Faddeeva function for complex argument::\n"
+    "\n"
+    "    exp(-z**2) * erfc(-i*z)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    complex argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Faddeeva function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "dawsn, erf, erfc, erfcx, erfi\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> z = special.wofz(x)\n"
+    "\n"
+    ">>> plt.plot(x, z.real, label='wofz(x).real')\n"
+    ">>> plt.plot(x, z.imag, label='wofz(x).imag')\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.legend(framealpha=1, shadow=True)\n"
+    ">>> plt.grid(alpha=0.25)\n"
+    ">>> plt.show()")
+ufunc_wofz_loops[0] = loop_D_D__As_F_F
+ufunc_wofz_loops[1] = loop_D_D__As_D_D
+ufunc_wofz_types[0] = NPY_CFLOAT
+ufunc_wofz_types[1] = NPY_CFLOAT
+ufunc_wofz_types[2] = NPY_CDOUBLE
+ufunc_wofz_types[3] = NPY_CDOUBLE
+ufunc_wofz_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_w
+ufunc_wofz_ptr[2*0+1] = ("wofz")
+ufunc_wofz_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_w
+ufunc_wofz_ptr[2*1+1] = ("wofz")
+ufunc_wofz_data[0] = &ufunc_wofz_ptr[2*0]
+ufunc_wofz_data[1] = &ufunc_wofz_ptr[2*1]
+wofz = np.PyUFunc_FromFuncAndData(ufunc_wofz_loops, ufunc_wofz_data, ufunc_wofz_types, 2, 1, 1, 0, "wofz", ufunc_wofz_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_wrightomega_loops[4]
+cdef void *ufunc_wrightomega_ptr[8]
+cdef void *ufunc_wrightomega_data[4]
+cdef char ufunc_wrightomega_types[8]
+cdef char *ufunc_wrightomega_doc = (
+    "wrightomega(z, out=None)\n"
+    "\n"
+    "Wright Omega function.\n"
+    "\n"
+    "Defined as the solution to\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\omega + \\log(\\omega) = z\n"
+    "\n"
+    "where :math:`\\log` is the principal branch of the complex logarithm.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Points at which to evaluate the Wright Omega function\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "omega : scalar or ndarray\n"
+    "    Values of the Wright Omega function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "lambertw : The Lambert W function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.19.0\n"
+    "\n"
+    "The function can also be defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\omega(z) = W_{K(z)}(e^z)\n"
+    "\n"
+    "where :math:`K(z) = \\lceil (\\Im(z) - \\pi)/(2\\pi) \\rceil` is the\n"
+    "unwinding number and :math:`W` is the Lambert W function.\n"
+    "\n"
+    "The implementation here is taken from [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Lawrence, Corless, and Jeffrey, \"Algorithm 917: Complex\n"
+    "       Double-Precision Evaluation of the Wright :math:`\\omega`\n"
+    "       Function.\" ACM Transactions on Mathematical Software,\n"
+    "       2012. :doi:`10.1145/2168773.2168779`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import wrightomega, lambertw\n"
+    "\n"
+    ">>> wrightomega([-2, -1, 0, 1, 2])\n"
+    "array([0.12002824, 0.27846454, 0.56714329, 1.        , 1.5571456 ])\n"
+    "\n"
+    "Complex input:\n"
+    "\n"
+    ">>> wrightomega(3 + 5j)\n"
+    "(1.5804428632097158+3.8213626783287937j)\n"
+    "\n"
+    "Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:\n"
+    "\n"
+    ">>> w = -5 + 4j\n"
+    ">>> wrightomega(w + np.log(w))\n"
+    "(-5+4j)\n"
+    "\n"
+    "Verify the connection to ``lambertw``:\n"
+    "\n"
+    ">>> z = 0.5 + 3j\n"
+    ">>> wrightomega(z)\n"
+    "(0.0966015889280649+1.4937828458191993j)\n"
+    ">>> lambertw(np.exp(z))\n"
+    "(0.09660158892806493+1.4937828458191993j)\n"
+    "\n"
+    ">>> z = 0.5 + 4j\n"
+    ">>> wrightomega(z)\n"
+    "(-0.3362123489037213+2.282986001579032j)\n"
+    ">>> lambertw(np.exp(z), k=1)\n"
+    "(-0.33621234890372115+2.282986001579032j)")
+ufunc_wrightomega_loops[0] = loop_d_d__As_f_f
+ufunc_wrightomega_loops[1] = loop_d_d__As_d_d
+ufunc_wrightomega_loops[2] = loop_D_D__As_F_F
+ufunc_wrightomega_loops[3] = loop_D_D__As_D_D
+ufunc_wrightomega_types[0] = NPY_FLOAT
+ufunc_wrightomega_types[1] = NPY_FLOAT
+ufunc_wrightomega_types[2] = NPY_DOUBLE
+ufunc_wrightomega_types[3] = NPY_DOUBLE
+ufunc_wrightomega_types[4] = NPY_CFLOAT
+ufunc_wrightomega_types[5] = NPY_CFLOAT
+ufunc_wrightomega_types[6] = NPY_CDOUBLE
+ufunc_wrightomega_types[7] = NPY_CDOUBLE
+ufunc_wrightomega_ptr[2*0] = scipy.special._ufuncs_cxx._export_wrightomega_real
+ufunc_wrightomega_ptr[2*0+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*1] = scipy.special._ufuncs_cxx._export_wrightomega_real
+ufunc_wrightomega_ptr[2*1+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*2] = scipy.special._ufuncs_cxx._export_wrightomega
+ufunc_wrightomega_ptr[2*2+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*3] = scipy.special._ufuncs_cxx._export_wrightomega
+ufunc_wrightomega_ptr[2*3+1] = ("wrightomega")
+ufunc_wrightomega_data[0] = &ufunc_wrightomega_ptr[2*0]
+ufunc_wrightomega_data[1] = &ufunc_wrightomega_ptr[2*1]
+ufunc_wrightomega_data[2] = &ufunc_wrightomega_ptr[2*2]
+ufunc_wrightomega_data[3] = &ufunc_wrightomega_ptr[2*3]
+wrightomega = np.PyUFunc_FromFuncAndData(ufunc_wrightomega_loops, ufunc_wrightomega_data, ufunc_wrightomega_types, 4, 1, 1, 0, "wrightomega", ufunc_wrightomega_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_xlog1py_loops[4]
+cdef void *ufunc_xlog1py_ptr[8]
+cdef void *ufunc_xlog1py_data[4]
+cdef char ufunc_xlog1py_types[12]
+cdef char *ufunc_xlog1py_doc = (
+    "xlog1py(x, y, out=None)\n"
+    "\n"
+    "Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Multiplier\n"
+    "y : array_like\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "z : scalar or ndarray\n"
+    "    Computed x*log1p(y)\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.13.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "This example shows how the function can be used to calculate the log of\n"
+    "the probability mass function for a geometric discrete random variable.\n"
+    "The probability mass function of the geometric distribution is defined\n"
+    "as follows:\n"
+    "\n"
+    ".. math:: f(k) = (1-p)^{k-1} p\n"
+    "\n"
+    "where :math:`p` is the probability of a single success\n"
+    "and :math:`1-p` is the probability of a single failure\n"
+    "and :math:`k` is the number of trials to get the first success.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import xlog1py\n"
+    ">>> p = 0.5\n"
+    ">>> k = 100\n"
+    ">>> _pmf = np.power(1 - p, k - 1) * p\n"
+    ">>> _pmf\n"
+    "7.888609052210118e-31\n"
+    "\n"
+    "If we take k as a relatively large number the value of the probability\n"
+    "mass function can become very low. In such cases taking the log of the\n"
+    "pmf would be more suitable as the log function can change the values\n"
+    "to a scale that is more appropriate to work with.\n"
+    "\n"
+    ">>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)\n"
+    ">>> _log_pmf\n"
+    "-69.31471805599453\n"
+    "\n"
+    "We can confirm that we get a value close to the original pmf value by\n"
+    "taking the exponential of the log pmf.\n"
+    "\n"
+    ">>> _orig_pmf = np.exp(_log_pmf)\n"
+    ">>> np.isclose(_pmf, _orig_pmf)\n"
+    "True")
+ufunc_xlog1py_loops[0] = loop_d_dd__As_ff_f
+ufunc_xlog1py_loops[1] = loop_d_dd__As_dd_d
+ufunc_xlog1py_loops[2] = loop_D_DD__As_FF_F
+ufunc_xlog1py_loops[3] = loop_D_DD__As_DD_D
+ufunc_xlog1py_types[0] = NPY_FLOAT
+ufunc_xlog1py_types[1] = NPY_FLOAT
+ufunc_xlog1py_types[2] = NPY_FLOAT
+ufunc_xlog1py_types[3] = NPY_DOUBLE
+ufunc_xlog1py_types[4] = NPY_DOUBLE
+ufunc_xlog1py_types[5] = NPY_DOUBLE
+ufunc_xlog1py_types[6] = NPY_CFLOAT
+ufunc_xlog1py_types[7] = NPY_CFLOAT
+ufunc_xlog1py_types[8] = NPY_CFLOAT
+ufunc_xlog1py_types[9] = NPY_CDOUBLE
+ufunc_xlog1py_types[10] = NPY_CDOUBLE
+ufunc_xlog1py_types[11] = NPY_CDOUBLE
+ufunc_xlog1py_ptr[2*0] = _func_xlog1py[double]
+ufunc_xlog1py_ptr[2*0+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*1] = _func_xlog1py[double]
+ufunc_xlog1py_ptr[2*1+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*2] = _func_xlog1py[double_complex]
+ufunc_xlog1py_ptr[2*2+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*3] = _func_xlog1py[double_complex]
+ufunc_xlog1py_ptr[2*3+1] = ("xlog1py")
+ufunc_xlog1py_data[0] = &ufunc_xlog1py_ptr[2*0]
+ufunc_xlog1py_data[1] = &ufunc_xlog1py_ptr[2*1]
+ufunc_xlog1py_data[2] = &ufunc_xlog1py_ptr[2*2]
+ufunc_xlog1py_data[3] = &ufunc_xlog1py_ptr[2*3]
+xlog1py = np.PyUFunc_FromFuncAndData(ufunc_xlog1py_loops, ufunc_xlog1py_data, ufunc_xlog1py_types, 4, 2, 1, 0, "xlog1py", ufunc_xlog1py_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_xlogy_loops[4]
+cdef void *ufunc_xlogy_ptr[8]
+cdef void *ufunc_xlogy_data[4]
+cdef char ufunc_xlogy_types[12]
+cdef char *ufunc_xlogy_doc = (
+    "xlogy(x, y, out=None)\n"
+    "\n"
+    "Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Multiplier\n"
+    "y : array_like\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "z : scalar or ndarray\n"
+    "    Computed x*log(y)\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The log function used in the computation is the natural log.\n"
+    "\n"
+    ".. versionadded:: 0.13.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "We can use this function to calculate the binary logistic loss also\n"
+    "known as the binary cross entropy. This loss function is used for\n"
+    "binary classification problems and is defined as:\n"
+    "\n"
+    ".. math::\n"
+    "    L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))\n"
+    "\n"
+    "We can define the parameters `x` and `y` as y and y_pred respectively.\n"
+    "y is the array of the actual labels which over here can be either 0 or 1.\n"
+    "y_pred is the array of the predicted probabilities with respect to\n"
+    "the positive class (1).\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import xlogy\n"
+    ">>> y = np.array([0, 1, 0, 1, 1, 0])\n"
+    ">>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])\n"
+    ">>> n = len(y)\n"
+    ">>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()\n"
+    ">>> loss /= n\n"
+    ">>> loss\n"
+    "0.29597052165495025\n"
+    "\n"
+    "A lower loss is usually better as it indicates that the predictions are\n"
+    "similar to the actual labels. In this example since our predicted\n"
+    "probabilities are close to the actual labels, we get an overall loss\n"
+    "that is reasonably low and appropriate.")
+ufunc_xlogy_loops[0] = loop_d_dd__As_ff_f
+ufunc_xlogy_loops[1] = loop_d_dd__As_dd_d
+ufunc_xlogy_loops[2] = loop_D_DD__As_FF_F
+ufunc_xlogy_loops[3] = loop_D_DD__As_DD_D
+ufunc_xlogy_types[0] = NPY_FLOAT
+ufunc_xlogy_types[1] = NPY_FLOAT
+ufunc_xlogy_types[2] = NPY_FLOAT
+ufunc_xlogy_types[3] = NPY_DOUBLE
+ufunc_xlogy_types[4] = NPY_DOUBLE
+ufunc_xlogy_types[5] = NPY_DOUBLE
+ufunc_xlogy_types[6] = NPY_CFLOAT
+ufunc_xlogy_types[7] = NPY_CFLOAT
+ufunc_xlogy_types[8] = NPY_CFLOAT
+ufunc_xlogy_types[9] = NPY_CDOUBLE
+ufunc_xlogy_types[10] = NPY_CDOUBLE
+ufunc_xlogy_types[11] = NPY_CDOUBLE
+ufunc_xlogy_ptr[2*0] = _func_xlogy[double]
+ufunc_xlogy_ptr[2*0+1] = ("xlogy")
+ufunc_xlogy_ptr[2*1] = _func_xlogy[double]
+ufunc_xlogy_ptr[2*1+1] = ("xlogy")
+ufunc_xlogy_ptr[2*2] = _func_xlogy[double_complex]
+ufunc_xlogy_ptr[2*2+1] = ("xlogy")
+ufunc_xlogy_ptr[2*3] = _func_xlogy[double_complex]
+ufunc_xlogy_ptr[2*3+1] = ("xlogy")
+ufunc_xlogy_data[0] = &ufunc_xlogy_ptr[2*0]
+ufunc_xlogy_data[1] = &ufunc_xlogy_ptr[2*1]
+ufunc_xlogy_data[2] = &ufunc_xlogy_ptr[2*2]
+ufunc_xlogy_data[3] = &ufunc_xlogy_ptr[2*3]
+xlogy = np.PyUFunc_FromFuncAndData(ufunc_xlogy_loops, ufunc_xlogy_data, ufunc_xlogy_types, 4, 2, 1, 0, "xlogy", ufunc_xlogy_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_yn_loops[3]
+cdef void *ufunc_yn_ptr[6]
+cdef void *ufunc_yn_data[3]
+cdef char ufunc_yn_types[9]
+cdef char *ufunc_yn_doc = (
+    "yn(n, x, out=None)\n"
+    "\n"
+    "Bessel function of the second kind of integer order and real argument.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Order (integer).\n"
+    "x : array_like\n"
+    "    Argument (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "Y : scalar or ndarray\n"
+    "    Value of the Bessel function, :math:`Y_n(x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "yv : For real order and real or complex argument.\n"
+    "y0: faster implementation of this function for order 0\n"
+    "y1: faster implementation of this function for order 1\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the Cephes [1]_ routine `yn`.\n"
+    "\n"
+    "The function is evaluated by forward recurrence on `n`, starting with\n"
+    "values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,\n"
+    "the routine for `y0` or `y1` is called directly.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Evaluate the function of order 0 at one point.\n"
+    "\n"
+    ">>> from scipy.special import yn\n"
+    ">>> yn(0, 1.)\n"
+    "0.08825696421567697\n"
+    "\n"
+    "Evaluate the function at one point for different orders.\n"
+    "\n"
+    ">>> yn(0, 1.), yn(1, 1.), yn(2, 1.)\n"
+    "(0.08825696421567697, -0.7812128213002888, -1.6506826068162546)\n"
+    "\n"
+    "The evaluation for different orders can be carried out in one call by\n"
+    "providing a list or NumPy array as argument for the `v` parameter:\n"
+    "\n"
+    ">>> yn([0, 1, 2], 1.)\n"
+    "array([ 0.08825696, -0.78121282, -1.65068261])\n"
+    "\n"
+    "Evaluate the function at several points for order 0 by providing an\n"
+    "array for `z`.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> points = np.array([0.5, 3., 8.])\n"
+    ">>> yn(0, points)\n"
+    "array([-0.44451873,  0.37685001,  0.22352149])\n"
+    "\n"
+    "If `z` is an array, the order parameter `v` must be broadcastable to\n"
+    "the correct shape if different orders shall be computed in one call.\n"
+    "To calculate the orders 0 and 1 for an 1D array:\n"
+    "\n"
+    ">>> orders = np.array([[0], [1]])\n"
+    ">>> orders.shape\n"
+    "(2, 1)\n"
+    "\n"
+    ">>> yn(orders, points)\n"
+    "array([[-0.44451873,  0.37685001,  0.22352149],\n"
+    "       [-1.47147239,  0.32467442, -0.15806046]])\n"
+    "\n"
+    "Plot the functions of order 0 to 3 from 0 to 10.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(0., 10., 1000)\n"
+    ">>> for i in range(4):\n"
+    "...     ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')\n"
+    ">>> ax.set_ylim(-3, 1)\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()")
+ufunc_yn_loops[0] = loop_d_pd__As_pd_d
+ufunc_yn_loops[1] = loop_d_dd__As_ff_f
+ufunc_yn_loops[2] = loop_d_dd__As_dd_d
+ufunc_yn_types[0] = NPY_INTP
+ufunc_yn_types[1] = NPY_DOUBLE
+ufunc_yn_types[2] = NPY_DOUBLE
+ufunc_yn_types[3] = NPY_FLOAT
+ufunc_yn_types[4] = NPY_FLOAT
+ufunc_yn_types[5] = NPY_FLOAT
+ufunc_yn_types[6] = NPY_DOUBLE
+ufunc_yn_types[7] = NPY_DOUBLE
+ufunc_yn_types[8] = NPY_DOUBLE
+ufunc_yn_ptr[2*0] = _func_cephes_yn_wrap
+ufunc_yn_ptr[2*0+1] = ("yn")
+ufunc_yn_ptr[2*1] = _func_yn_unsafe
+ufunc_yn_ptr[2*1+1] = ("yn")
+ufunc_yn_ptr[2*2] = _func_yn_unsafe
+ufunc_yn_ptr[2*2+1] = ("yn")
+ufunc_yn_data[0] = &ufunc_yn_ptr[2*0]
+ufunc_yn_data[1] = &ufunc_yn_ptr[2*1]
+ufunc_yn_data[2] = &ufunc_yn_ptr[2*2]
+yn = np.PyUFunc_FromFuncAndData(ufunc_yn_loops, ufunc_yn_data, ufunc_yn_types, 3, 2, 1, 0, "yn", ufunc_yn_doc, 0)
+
+from ._special_ufuncs import (_cospi, _lambertw, _scaled_exp1, _sinpi, _spherical_jn, _spherical_jn_d, _spherical_yn, _spherical_yn_d, _spherical_in, _spherical_in_d, _spherical_kn, _spherical_kn_d, airy, airye, bei, beip, ber, berp, binom, exp1, expi, expit, exprel, gamma, gammaln, hankel1, hankel1e, hankel2, hankel2e, hyp2f1, it2i0k0, it2j0y0, it2struve0, itairy, iti0k0, itj0y0, itmodstruve0, itstruve0, iv, _iv_ratio, _iv_ratio_c, ive, jv, jve, kei, keip, kelvin, ker, kerp, kv, kve, log_expit, log_wright_bessel, loggamma, logit, mathieu_a, mathieu_b, mathieu_cem, mathieu_modcem1, mathieu_modcem2, mathieu_modsem1, mathieu_modsem2, mathieu_sem, modfresnelm, modfresnelp, obl_ang1, obl_ang1_cv, obl_cv, obl_rad1, obl_rad1_cv, obl_rad2, obl_rad2_cv, pbdv, pbvv, pbwa, pro_ang1, pro_ang1_cv, pro_cv, pro_rad1, pro_rad1_cv, pro_rad2, pro_rad2_cv, psi, rgamma, sph_harm, wright_bessel, yv, yve, zetac, _zeta, sindg, cosdg, tandg, cotdg, i0, i0e, i1, i1e, k0, k0e, k1, k1e, y0, y1, j0, j1, struve, modstruve, beta, betaln, besselpoly, gammaln, gammasgn, cbrt, radian, cosm1, gammainc, gammaincinv, gammaincc, gammainccinv, fresnel, ellipe, ellipeinc, ellipk, ellipkinc, ellipkm1, ellipj, _riemann_zeta)
+
+#
+# Aliases
+#
+jn = jv
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..a2fffff86812d1a7ca547a71a19078b6d5f59716
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd
@@ -0,0 +1,155 @@
+from . cimport sf_error
+cdef void _set_action(sf_error.sf_error_t, sf_error.sf_action_t) noexcept nogil
+cdef void *_export_beta_pdf_float
+cdef void *_export_beta_pdf_double
+cdef void *_export_beta_ppf_float
+cdef void *_export_beta_ppf_double
+cdef void *_export_binom_cdf_float
+cdef void *_export_binom_cdf_double
+cdef void *_export_binom_isf_float
+cdef void *_export_binom_isf_double
+cdef void *_export_binom_pmf_float
+cdef void *_export_binom_pmf_double
+cdef void *_export_binom_ppf_float
+cdef void *_export_binom_ppf_double
+cdef void *_export_binom_sf_float
+cdef void *_export_binom_sf_double
+cdef void *_export_cauchy_isf_float
+cdef void *_export_cauchy_isf_double
+cdef void *_export_cauchy_ppf_float
+cdef void *_export_cauchy_ppf_double
+cdef void *_export_hypergeom_cdf_float
+cdef void *_export_hypergeom_cdf_double
+cdef void *_export_hypergeom_mean_float
+cdef void *_export_hypergeom_mean_double
+cdef void *_export_hypergeom_pmf_float
+cdef void *_export_hypergeom_pmf_double
+cdef void *_export_hypergeom_sf_float
+cdef void *_export_hypergeom_sf_double
+cdef void *_export_hypergeom_skewness_float
+cdef void *_export_hypergeom_skewness_double
+cdef void *_export_hypergeom_variance_float
+cdef void *_export_hypergeom_variance_double
+cdef void *_export_invgauss_isf_float
+cdef void *_export_invgauss_isf_double
+cdef void *_export_invgauss_ppf_float
+cdef void *_export_invgauss_ppf_double
+cdef void *_export_landau_cdf_float
+cdef void *_export_landau_cdf_double
+cdef void *_export_landau_isf_float
+cdef void *_export_landau_isf_double
+cdef void *_export_landau_pdf_float
+cdef void *_export_landau_pdf_double
+cdef void *_export_landau_ppf_float
+cdef void *_export_landau_ppf_double
+cdef void *_export_landau_sf_float
+cdef void *_export_landau_sf_double
+cdef void *_export_nbinom_cdf_float
+cdef void *_export_nbinom_cdf_double
+cdef void *_export_nbinom_isf_float
+cdef void *_export_nbinom_isf_double
+cdef void *_export_nbinom_kurtosis_excess_float
+cdef void *_export_nbinom_kurtosis_excess_double
+cdef void *_export_nbinom_mean_float
+cdef void *_export_nbinom_mean_double
+cdef void *_export_nbinom_pmf_float
+cdef void *_export_nbinom_pmf_double
+cdef void *_export_nbinom_ppf_float
+cdef void *_export_nbinom_ppf_double
+cdef void *_export_nbinom_sf_float
+cdef void *_export_nbinom_sf_double
+cdef void *_export_nbinom_skewness_float
+cdef void *_export_nbinom_skewness_double
+cdef void *_export_nbinom_variance_float
+cdef void *_export_nbinom_variance_double
+cdef void *_export_ncf_isf_float
+cdef void *_export_ncf_isf_double
+cdef void *_export_ncf_kurtosis_excess_float
+cdef void *_export_ncf_kurtosis_excess_double
+cdef void *_export_ncf_mean_float
+cdef void *_export_ncf_mean_double
+cdef void *_export_ncf_pdf_float
+cdef void *_export_ncf_pdf_double
+cdef void *_export_ncf_sf_float
+cdef void *_export_ncf_sf_double
+cdef void *_export_ncf_skewness_float
+cdef void *_export_ncf_skewness_double
+cdef void *_export_ncf_variance_float
+cdef void *_export_ncf_variance_double
+cdef void *_export_nct_isf_float
+cdef void *_export_nct_isf_double
+cdef void *_export_nct_kurtosis_excess_float
+cdef void *_export_nct_kurtosis_excess_double
+cdef void *_export_nct_mean_float
+cdef void *_export_nct_mean_double
+cdef void *_export_nct_pdf_float
+cdef void *_export_nct_pdf_double
+cdef void *_export_nct_ppf_float
+cdef void *_export_nct_ppf_double
+cdef void *_export_nct_sf_float
+cdef void *_export_nct_sf_double
+cdef void *_export_nct_skewness_float
+cdef void *_export_nct_skewness_double
+cdef void *_export_nct_variance_float
+cdef void *_export_nct_variance_double
+cdef void *_export_ncx2_cdf_float
+cdef void *_export_ncx2_cdf_double
+cdef void *_export_ncx2_isf_float
+cdef void *_export_ncx2_isf_double
+cdef void *_export_ncx2_pdf_float
+cdef void *_export_ncx2_pdf_double
+cdef void *_export_ncx2_ppf_float
+cdef void *_export_ncx2_ppf_double
+cdef void *_export_ncx2_sf_float
+cdef void *_export_ncx2_sf_double
+cdef void *_export_skewnorm_cdf_float
+cdef void *_export_skewnorm_cdf_double
+cdef void *_export_skewnorm_isf_float
+cdef void *_export_skewnorm_isf_double
+cdef void *_export_skewnorm_ppf_float
+cdef void *_export_skewnorm_ppf_double
+cdef void *_export__stirling2_inexact
+cdef void *_export_ibeta_float
+cdef void *_export_ibeta_double
+cdef void *_export_ibetac_float
+cdef void *_export_ibetac_double
+cdef void *_export_ibetac_inv_float
+cdef void *_export_ibetac_inv_double
+cdef void *_export_ibeta_inv_float
+cdef void *_export_ibeta_inv_double
+cdef void *_export_faddeeva_dawsn
+cdef void *_export_faddeeva_dawsn_complex
+cdef void *_export_fellint_RC
+cdef void *_export_cellint_RC
+cdef void *_export_fellint_RD
+cdef void *_export_cellint_RD
+cdef void *_export_fellint_RF
+cdef void *_export_cellint_RF
+cdef void *_export_fellint_RG
+cdef void *_export_cellint_RG
+cdef void *_export_fellint_RJ
+cdef void *_export_cellint_RJ
+cdef void *_export_faddeeva_erf
+cdef void *_export_faddeeva_erfc_complex
+cdef void *_export_faddeeva_erfcx
+cdef void *_export_faddeeva_erfcx_complex
+cdef void *_export_faddeeva_erfi
+cdef void *_export_faddeeva_erfi_complex
+cdef void *_export_erfinv_float
+cdef void *_export_erfinv_double
+cdef void *_export_hyp1f1_double
+cdef void *_export_faddeeva_log_ndtr
+cdef void *_export_faddeeva_log_ndtr_complex
+cdef void *_export_ncf_cdf_float
+cdef void *_export_ncf_cdf_double
+cdef void *_export_ncf_ppf_float
+cdef void *_export_ncf_ppf_double
+cdef void *_export_nct_cdf_float
+cdef void *_export_nct_cdf_double
+cdef void *_export_faddeeva_ndtr
+cdef void *_export_powm1_float
+cdef void *_export_powm1_double
+cdef void *_export_faddeeva_voigt_profile
+cdef void *_export_faddeeva_w
+cdef void *_export_wrightomega
+cdef void *_export_wrightomega_real
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..19cbd36c4707bb593e7e5638b9a158df504d3001
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx
@@ -0,0 +1,466 @@
+# This file is automatically generated by _generate_pyx.py.
+# Do not edit manually!
+
+from libc.math cimport NAN
+
+include "_ufuncs_extra_code_common.pxi"
+
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_beta_pdf_float "beta_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_beta_pdf_float = _func_beta_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_beta_pdf_double "beta_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_beta_pdf_double = _func_beta_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_beta_ppf_float "beta_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_beta_ppf_float = _func_beta_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_beta_ppf_double "beta_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_beta_ppf_double = _func_beta_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_cdf_float "binom_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_cdf_float = _func_binom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_cdf_double "binom_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_cdf_double = _func_binom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_isf_float "binom_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_isf_float = _func_binom_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_isf_double "binom_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_isf_double = _func_binom_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_pmf_float "binom_pmf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_pmf_float = _func_binom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_pmf_double "binom_pmf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_pmf_double = _func_binom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_ppf_float "binom_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_ppf_float = _func_binom_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_ppf_double "binom_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_ppf_double = _func_binom_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_sf_float "binom_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_sf_float = _func_binom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_sf_double "binom_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_sf_double = _func_binom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_cauchy_isf_float "cauchy_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_cauchy_isf_float = _func_cauchy_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_cauchy_isf_double "cauchy_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_cauchy_isf_double = _func_cauchy_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_cauchy_ppf_float "cauchy_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_cauchy_ppf_float = _func_cauchy_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_cauchy_ppf_double "cauchy_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_cauchy_ppf_double = _func_cauchy_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_cdf_float "hypergeom_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_cdf_float = _func_hypergeom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_cdf_double "hypergeom_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_cdf_double = _func_hypergeom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_mean_float "hypergeom_mean_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_mean_float = _func_hypergeom_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_mean_double "hypergeom_mean_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_mean_double = _func_hypergeom_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_pmf_float "hypergeom_pmf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_pmf_float = _func_hypergeom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_pmf_double "hypergeom_pmf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_pmf_double = _func_hypergeom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_sf_float "hypergeom_sf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_sf_float = _func_hypergeom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_sf_double "hypergeom_sf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_sf_double = _func_hypergeom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_skewness_float "hypergeom_skewness_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_skewness_float = _func_hypergeom_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_skewness_double "hypergeom_skewness_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_skewness_double = _func_hypergeom_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_variance_float "hypergeom_variance_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_variance_float = _func_hypergeom_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_variance_double "hypergeom_variance_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_variance_double = _func_hypergeom_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_invgauss_isf_float "invgauss_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_invgauss_isf_float = _func_invgauss_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_invgauss_isf_double "invgauss_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_invgauss_isf_double = _func_invgauss_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_invgauss_ppf_float "invgauss_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_invgauss_ppf_float = _func_invgauss_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_invgauss_ppf_double "invgauss_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_invgauss_ppf_double = _func_invgauss_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_cdf_float "landau_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_cdf_float = _func_landau_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_cdf_double "landau_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_cdf_double = _func_landau_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_isf_float "landau_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_isf_float = _func_landau_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_isf_double "landau_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_isf_double = _func_landau_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_pdf_float "landau_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_pdf_float = _func_landau_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_pdf_double "landau_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_pdf_double = _func_landau_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_ppf_float "landau_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_ppf_float = _func_landau_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_ppf_double "landau_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_ppf_double = _func_landau_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_sf_float "landau_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_sf_float = _func_landau_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_sf_double "landau_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_sf_double = _func_landau_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_cdf_float "nbinom_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_cdf_float = _func_nbinom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_cdf_double "nbinom_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_cdf_double = _func_nbinom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_isf_float "nbinom_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_isf_float = _func_nbinom_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_isf_double "nbinom_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_isf_double = _func_nbinom_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_kurtosis_excess_float "nbinom_kurtosis_excess_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_kurtosis_excess_float = _func_nbinom_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_kurtosis_excess_double "nbinom_kurtosis_excess_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_kurtosis_excess_double = _func_nbinom_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_mean_float "nbinom_mean_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_mean_float = _func_nbinom_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_mean_double "nbinom_mean_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_mean_double = _func_nbinom_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_pmf_float "nbinom_pmf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_pmf_float = _func_nbinom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_pmf_double "nbinom_pmf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_pmf_double = _func_nbinom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_ppf_float "nbinom_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_ppf_float = _func_nbinom_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_ppf_double "nbinom_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_ppf_double = _func_nbinom_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_sf_float "nbinom_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_sf_float = _func_nbinom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_sf_double "nbinom_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_sf_double = _func_nbinom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_skewness_float "nbinom_skewness_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_skewness_float = _func_nbinom_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_skewness_double "nbinom_skewness_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_skewness_double = _func_nbinom_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_variance_float "nbinom_variance_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_variance_float = _func_nbinom_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_variance_double "nbinom_variance_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_variance_double = _func_nbinom_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_isf_float "ncf_isf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_isf_float = _func_ncf_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_isf_double "ncf_isf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_isf_double = _func_ncf_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_kurtosis_excess_float "ncf_kurtosis_excess_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_kurtosis_excess_float = _func_ncf_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_kurtosis_excess_double "ncf_kurtosis_excess_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_kurtosis_excess_double = _func_ncf_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_mean_float "ncf_mean_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_mean_float = _func_ncf_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_mean_double "ncf_mean_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_mean_double = _func_ncf_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_pdf_float "ncf_pdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_pdf_float = _func_ncf_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_pdf_double "ncf_pdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_pdf_double = _func_ncf_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_sf_float "ncf_sf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_sf_float = _func_ncf_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_sf_double "ncf_sf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_sf_double = _func_ncf_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_skewness_float "ncf_skewness_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_skewness_float = _func_ncf_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_skewness_double "ncf_skewness_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_skewness_double = _func_ncf_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_variance_float "ncf_variance_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_variance_float = _func_ncf_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_variance_double "ncf_variance_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_variance_double = _func_ncf_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_isf_float "nct_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_isf_float = _func_nct_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_isf_double "nct_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_isf_double = _func_nct_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_kurtosis_excess_float "nct_kurtosis_excess_float"(float, float) noexcept nogil
+cdef void *_export_nct_kurtosis_excess_float = _func_nct_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_kurtosis_excess_double "nct_kurtosis_excess_double"(double, double) noexcept nogil
+cdef void *_export_nct_kurtosis_excess_double = _func_nct_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_mean_float "nct_mean_float"(float, float) noexcept nogil
+cdef void *_export_nct_mean_float = _func_nct_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_mean_double "nct_mean_double"(double, double) noexcept nogil
+cdef void *_export_nct_mean_double = _func_nct_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_pdf_float "nct_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_pdf_float = _func_nct_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_pdf_double "nct_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_pdf_double = _func_nct_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_ppf_float "nct_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_ppf_float = _func_nct_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_ppf_double "nct_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_ppf_double = _func_nct_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_sf_float "nct_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_sf_float = _func_nct_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_sf_double "nct_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_sf_double = _func_nct_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_skewness_float "nct_skewness_float"(float, float) noexcept nogil
+cdef void *_export_nct_skewness_float = _func_nct_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_skewness_double "nct_skewness_double"(double, double) noexcept nogil
+cdef void *_export_nct_skewness_double = _func_nct_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_variance_float "nct_variance_float"(float, float) noexcept nogil
+cdef void *_export_nct_variance_float = _func_nct_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_variance_double "nct_variance_double"(double, double) noexcept nogil
+cdef void *_export_nct_variance_double = _func_nct_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_cdf_float "ncx2_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_cdf_float = _func_ncx2_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_cdf_double "ncx2_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_cdf_double = _func_ncx2_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_isf_float "ncx2_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_isf_float = _func_ncx2_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_isf_double "ncx2_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_isf_double = _func_ncx2_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_pdf_float "ncx2_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_pdf_float = _func_ncx2_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_pdf_double "ncx2_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_pdf_double = _func_ncx2_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_ppf_float "ncx2_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_ppf_float = _func_ncx2_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_ppf_double "ncx2_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_ppf_double = _func_ncx2_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_sf_float "ncx2_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_sf_float = _func_ncx2_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_sf_double "ncx2_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_sf_double = _func_ncx2_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_cdf_float "skewnorm_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_cdf_float = _func_skewnorm_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_cdf_double "skewnorm_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_cdf_double = _func_skewnorm_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_isf_float "skewnorm_isf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_isf_float = _func_skewnorm_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_isf_double "skewnorm_isf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_isf_double = _func_skewnorm_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_ppf_float "skewnorm_ppf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_ppf_float = _func_skewnorm_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_ppf_double "skewnorm_ppf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_ppf_double = _func_skewnorm_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogil
+cdef void *_export__stirling2_inexact = _func__stirling2_inexact
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogil
+cdef void *_export_ibeta_float = _func_ibeta_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogil
+cdef void *_export_ibeta_double = _func_ibeta_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogil
+cdef void *_export_ibetac_float = _func_ibetac_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogil
+cdef void *_export_ibetac_double = _func_ibetac_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogil
+cdef void *_export_ibetac_inv_float = _func_ibetac_inv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogil
+cdef void *_export_ibetac_inv_double = _func_ibetac_inv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogil
+cdef void *_export_ibeta_inv_float = _func_ibeta_inv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogil
+cdef void *_export_ibeta_inv_double = _func_ibeta_inv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogil
+cdef void *_export_faddeeva_dawsn = _func_faddeeva_dawsn
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_dawsn_complex = _func_faddeeva_dawsn_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogil
+cdef void *_export_fellint_RC = _func_fellint_RC
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RC = _func_cellint_RC
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RD = _func_fellint_RD
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RD = _func_cellint_RD
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RF = _func_fellint_RF
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RF = _func_cellint_RF
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RG = _func_fellint_RG
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RG = _func_cellint_RG
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogil
+cdef void *_export_fellint_RJ = _func_fellint_RJ
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RJ = _func_cellint_RJ
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erf = _func_faddeeva_erf
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfc_complex = _func_faddeeva_erfc_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogil
+cdef void *_export_faddeeva_erfcx = _func_faddeeva_erfcx
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfcx_complex = _func_faddeeva_erfcx_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogil
+cdef void *_export_faddeeva_erfi = _func_faddeeva_erfi
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfi_complex = _func_faddeeva_erfi_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogil
+cdef void *_export_erfinv_float = _func_erfinv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogil
+cdef void *_export_erfinv_double = _func_erfinv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogil
+cdef void *_export_hyp1f1_double = _func_hyp1f1_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogil
+cdef void *_export_faddeeva_log_ndtr = _func_faddeeva_log_ndtr
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_log_ndtr_complex = _func_faddeeva_log_ndtr_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_cdf_float "ncf_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_cdf_float = _func_ncf_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_cdf_double "ncf_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_cdf_double = _func_ncf_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_ppf_float "ncf_ppf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_ppf_float = _func_ncf_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_ppf_double "ncf_ppf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_ppf_double = _func_ncf_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_cdf_float "nct_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_cdf_float = _func_nct_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_cdf_double "nct_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_cdf_double = _func_nct_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogil
+cdef void *_export_faddeeva_ndtr = _func_faddeeva_ndtr
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogil
+cdef void *_export_powm1_float = _func_powm1_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogil
+cdef void *_export_powm1_double = _func_powm1_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogil
+cdef void *_export_faddeeva_voigt_profile = _func_faddeeva_voigt_profile
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogil
+cdef void *_export_faddeeva_w = _func_faddeeva_w
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogil
+cdef void *_export_wrightomega = _func_wrightomega
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogil
+cdef void *_export_wrightomega_real = _func_wrightomega_real
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..4e916ce565742ecd949c2c6f9c1a1891e734a96d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h
@@ -0,0 +1,161 @@
+#ifndef UFUNCS_PROTO_H
+#define UFUNCS_PROTO_H 1
+#include "boost_special_functions.h"
+npy_float beta_pdf_float(npy_float, npy_float, npy_float);
+npy_double beta_pdf_double(npy_double, npy_double, npy_double);
+npy_float beta_ppf_float(npy_float, npy_float, npy_float);
+npy_double beta_ppf_double(npy_double, npy_double, npy_double);
+npy_float binom_cdf_float(npy_float, npy_float, npy_float);
+npy_double binom_cdf_double(npy_double, npy_double, npy_double);
+npy_float binom_isf_float(npy_float, npy_float, npy_float);
+npy_double binom_isf_double(npy_double, npy_double, npy_double);
+npy_float binom_pmf_float(npy_float, npy_float, npy_float);
+npy_double binom_pmf_double(npy_double, npy_double, npy_double);
+npy_float binom_ppf_float(npy_float, npy_float, npy_float);
+npy_double binom_ppf_double(npy_double, npy_double, npy_double);
+npy_float binom_sf_float(npy_float, npy_float, npy_float);
+npy_double binom_sf_double(npy_double, npy_double, npy_double);
+npy_float cauchy_isf_float(npy_float, npy_float, npy_float);
+npy_double cauchy_isf_double(npy_double, npy_double, npy_double);
+npy_float cauchy_ppf_float(npy_float, npy_float, npy_float);
+npy_double cauchy_ppf_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_mean_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_mean_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_pmf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_pmf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_sf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_sf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_skewness_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_skewness_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_variance_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_variance_double(npy_double, npy_double, npy_double);
+npy_float invgauss_isf_float(npy_float, npy_float, npy_float);
+npy_double invgauss_isf_double(npy_double, npy_double, npy_double);
+npy_float invgauss_ppf_float(npy_float, npy_float, npy_float);
+npy_double invgauss_ppf_double(npy_double, npy_double, npy_double);
+npy_float landau_cdf_float(npy_float, npy_float, npy_float);
+npy_double landau_cdf_double(npy_double, npy_double, npy_double);
+npy_float landau_isf_float(npy_float, npy_float, npy_float);
+npy_double landau_isf_double(npy_double, npy_double, npy_double);
+npy_float landau_pdf_float(npy_float, npy_float, npy_float);
+npy_double landau_pdf_double(npy_double, npy_double, npy_double);
+npy_float landau_ppf_float(npy_float, npy_float, npy_float);
+npy_double landau_ppf_double(npy_double, npy_double, npy_double);
+npy_float landau_sf_float(npy_float, npy_float, npy_float);
+npy_double landau_sf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_cdf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_cdf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_isf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_isf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_kurtosis_excess_float(npy_float, npy_float);
+npy_double nbinom_kurtosis_excess_double(npy_double, npy_double);
+npy_float nbinom_mean_float(npy_float, npy_float);
+npy_double nbinom_mean_double(npy_double, npy_double);
+npy_float nbinom_pmf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_pmf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_ppf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_ppf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_sf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_sf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_skewness_float(npy_float, npy_float);
+npy_double nbinom_skewness_double(npy_double, npy_double);
+npy_float nbinom_variance_float(npy_float, npy_float);
+npy_double nbinom_variance_double(npy_double, npy_double);
+npy_float ncf_isf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_isf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_kurtosis_excess_float(npy_float, npy_float, npy_float);
+npy_double ncf_kurtosis_excess_double(npy_double, npy_double, npy_double);
+npy_float ncf_mean_float(npy_float, npy_float, npy_float);
+npy_double ncf_mean_double(npy_double, npy_double, npy_double);
+npy_float ncf_pdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_pdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_sf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_sf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_skewness_float(npy_float, npy_float, npy_float);
+npy_double ncf_skewness_double(npy_double, npy_double, npy_double);
+npy_float ncf_variance_float(npy_float, npy_float, npy_float);
+npy_double ncf_variance_double(npy_double, npy_double, npy_double);
+npy_float nct_isf_float(npy_float, npy_float, npy_float);
+npy_double nct_isf_double(npy_double, npy_double, npy_double);
+npy_float nct_kurtosis_excess_float(npy_float, npy_float);
+npy_double nct_kurtosis_excess_double(npy_double, npy_double);
+npy_float nct_mean_float(npy_float, npy_float);
+npy_double nct_mean_double(npy_double, npy_double);
+npy_float nct_pdf_float(npy_float, npy_float, npy_float);
+npy_double nct_pdf_double(npy_double, npy_double, npy_double);
+npy_float nct_ppf_float(npy_float, npy_float, npy_float);
+npy_double nct_ppf_double(npy_double, npy_double, npy_double);
+npy_float nct_sf_float(npy_float, npy_float, npy_float);
+npy_double nct_sf_double(npy_double, npy_double, npy_double);
+npy_float nct_skewness_float(npy_float, npy_float);
+npy_double nct_skewness_double(npy_double, npy_double);
+npy_float nct_variance_float(npy_float, npy_float);
+npy_double nct_variance_double(npy_double, npy_double);
+npy_float ncx2_cdf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_cdf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_isf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_isf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_pdf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_pdf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_ppf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_ppf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_sf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_sf_double(npy_double, npy_double, npy_double);
+npy_float skewnorm_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float skewnorm_isf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_isf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float skewnorm_ppf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_ppf_double(npy_double, npy_double, npy_double, npy_double);
+#include "stirling2.h"
+npy_double _stirling2_inexact(npy_double, npy_double);
+npy_float ibeta_float(npy_float, npy_float, npy_float);
+npy_double ibeta_double(npy_double, npy_double, npy_double);
+npy_float ibetac_float(npy_float, npy_float, npy_float);
+npy_double ibetac_double(npy_double, npy_double, npy_double);
+npy_float ibetac_inv_float(npy_float, npy_float, npy_float);
+npy_double ibetac_inv_double(npy_double, npy_double, npy_double);
+npy_float ibeta_inv_float(npy_float, npy_float, npy_float);
+npy_double ibeta_inv_double(npy_double, npy_double, npy_double);
+#include "_faddeeva.h"
+npy_double faddeeva_dawsn(npy_double);
+npy_cdouble faddeeva_dawsn_complex(npy_cdouble);
+#include "ellint_carlson_wrap.hh"
+npy_double fellint_RC(npy_double, npy_double);
+npy_cdouble cellint_RC(npy_cdouble, npy_cdouble);
+npy_double fellint_RD(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RD(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RF(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RF(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RG(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RG(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RJ(npy_double, npy_double, npy_double, npy_double);
+npy_cdouble cellint_RJ(npy_cdouble, npy_cdouble, npy_cdouble, npy_cdouble);
+npy_cdouble faddeeva_erf(npy_cdouble);
+npy_cdouble faddeeva_erfc_complex(npy_cdouble);
+npy_double faddeeva_erfcx(npy_double);
+npy_cdouble faddeeva_erfcx_complex(npy_cdouble);
+npy_double faddeeva_erfi(npy_double);
+npy_cdouble faddeeva_erfi_complex(npy_cdouble);
+npy_float erfinv_float(npy_float);
+npy_double erfinv_double(npy_double);
+npy_double hyp1f1_double(npy_double, npy_double, npy_double);
+npy_double faddeeva_log_ndtr(npy_double);
+npy_cdouble faddeeva_log_ndtr_complex(npy_cdouble);
+npy_float ncf_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_ppf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_ppf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float nct_cdf_float(npy_float, npy_float, npy_float);
+npy_double nct_cdf_double(npy_double, npy_double, npy_double);
+npy_cdouble faddeeva_ndtr(npy_cdouble);
+npy_float powm1_float(npy_float, npy_float);
+npy_double powm1_double(npy_double, npy_double);
+npy_double faddeeva_voigt_profile(npy_double, npy_double, npy_double);
+npy_cdouble faddeeva_w(npy_cdouble);
+#include "_wright.h"
+npy_cdouble wrightomega(npy_cdouble);
+npy_double wrightomega_real(npy_double);
+#endif
diff --git a/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..86d2349d2b7881b71bfdec2a60a78e2bfc18f9fe
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h
@@ -0,0 +1,65 @@
+#ifndef UFUNCS_PROTO_H
+#define UFUNCS_PROTO_H 1
+#include "_cosine.h"
+npy_double cosine_cdf(npy_double);
+npy_double cosine_invcdf(npy_double);
+#include "xsf_wrappers.h"
+npy_double cephes_igam_fac(npy_double, npy_double);
+npy_double xsf_kolmogc(npy_double);
+npy_double xsf_kolmogci(npy_double);
+npy_double xsf_kolmogp(npy_double);
+npy_double cephes_lanczos_sum_expg_scaled(npy_double);
+npy_double cephes_lgam1p(npy_double);
+npy_double cephes_log1pmx(npy_double);
+npy_double cephes_smirnovc_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovci_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovp_wrap(npy_intp, npy_double);
+npy_double cephes__struve_asymp_large_z(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes__struve_bessel_series(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes__struve_power_series(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes_bdtr_wrap(npy_double, npy_intp, npy_double);
+npy_double cephes_bdtrc_wrap(npy_double, npy_intp, npy_double);
+npy_double cephes_bdtri_wrap(npy_double, npy_intp, npy_double);
+npy_double xsf_chdtr(npy_double, npy_double);
+npy_double xsf_chdtrc(npy_double, npy_double);
+npy_double xsf_chdtri(npy_double, npy_double);
+npy_double cephes_erf(npy_double);
+npy_double cephes_erfc(npy_double);
+npy_double cephes_erfcinv(npy_double);
+npy_double cephes_exp10(npy_double);
+npy_double cephes_exp2(npy_double);
+npy_double cephes_expm1(npy_double);
+npy_double cephes_expn_wrap(npy_intp, npy_double);
+npy_double xsf_fdtr(npy_double, npy_double, npy_double);
+npy_double xsf_fdtrc(npy_double, npy_double, npy_double);
+npy_double xsf_fdtri(npy_double, npy_double, npy_double);
+npy_double xsf_gdtr(npy_double, npy_double, npy_double);
+npy_double xsf_gdtrc(npy_double, npy_double, npy_double);
+npy_double xsf_gdtrib(npy_double, npy_double, npy_double);
+npy_cdouble chyp1f1_wrap(npy_double, npy_double, npy_cdouble);
+npy_double special_cyl_bessel_k_int(npy_intp, npy_double);
+npy_double xsf_kolmogi(npy_double);
+npy_double xsf_kolmogorov(npy_double);
+npy_double cephes_log1p(npy_double);
+npy_double pmv_wrap(npy_double, npy_double, npy_double);
+npy_double cephes_nbdtr_wrap(npy_intp, npy_intp, npy_double);
+npy_double cephes_nbdtrc_wrap(npy_intp, npy_intp, npy_double);
+npy_double cephes_nbdtri_wrap(npy_intp, npy_intp, npy_double);
+npy_double xsf_ndtr(npy_double);
+npy_double xsf_ndtri(npy_double);
+npy_double xsf_owens_t(npy_double, npy_double);
+npy_double xsf_pdtr(npy_double, npy_double);
+npy_double xsf_pdtrc(npy_double, npy_double);
+npy_double cephes_pdtri_wrap(npy_intp, npy_double);
+npy_double cephes_poch(npy_double, npy_double);
+npy_double cephes_round(npy_double);
+npy_int xsf_cshichi(npy_cdouble, npy_cdouble *, npy_cdouble *);
+npy_int xsf_shichi(npy_double, npy_double *, npy_double *);
+npy_int xsf_csici(npy_cdouble, npy_cdouble *, npy_cdouble *);
+npy_int xsf_sici(npy_double, npy_double *, npy_double *);
+npy_double cephes_smirnov_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovi_wrap(npy_intp, npy_double);
+npy_double cephes_spence(npy_double);
+npy_double xsf_tukeylambdacdf(npy_double, npy_double);
+npy_double cephes_yn_wrap(npy_intp, npy_double);
+#endif
diff --git a/venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py b/venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5549717d35710d71655e42c836625cde9346bcc3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="add_newdocs",
+                                   private_modules=["_add_newdocs"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/basic.py b/venv/lib/python3.10/site-packages/scipy/special/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e55695f44d05187d6c83f1ebefd70270af2c2d76
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/basic.py
@@ -0,0 +1,87 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'ai_zeros',
+    'assoc_laguerre',
+    'bei_zeros',
+    'beip_zeros',
+    'ber_zeros',
+    'bernoulli',
+    'berp_zeros',
+    'bi_zeros',
+    'clpmn',
+    'comb',
+    'digamma',
+    'diric',
+    'erf_zeros',
+    'euler',
+    'factorial',
+    'factorial2',
+    'factorialk',
+    'fresnel_zeros',
+    'fresnelc_zeros',
+    'fresnels_zeros',
+    'gamma',
+    'h1vp',
+    'h2vp',
+    'hankel1',
+    'hankel2',
+    'iv',
+    'ivp',
+    'jn_zeros',
+    'jnjnp_zeros',
+    'jnp_zeros',
+    'jnyn_zeros',
+    'jv',
+    'jvp',
+    'kei_zeros',
+    'keip_zeros',
+    'kelvin_zeros',
+    'ker_zeros',
+    'kerp_zeros',
+    'kv',
+    'kvp',
+    'lmbda',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'lqn',
+    'mathieu_a',
+    'mathieu_b',
+    'mathieu_even_coef',
+    'mathieu_odd_coef',
+    'obl_cv_seq',
+    'pbdn_seq',
+    'pbdv_seq',
+    'pbvv_seq',
+    'perm',
+    'polygamma',
+    'pro_cv_seq',
+    'psi',
+    'riccati_jn',
+    'riccati_yn',
+    'sinc',
+    'y0_zeros',
+    'y1_zeros',
+    'y1p_zeros',
+    'yn_zeros',
+    'ynp_zeros',
+    'yv',
+    'yvp',
+    'zeta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="basic",
+                                   private_modules=["_basic", "_ufuncs"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd b/venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..c5d323fbd5f04ec56749505bc24feb080a851506
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd
@@ -0,0 +1,259 @@
+
+ctypedef fused number_t:
+    double complex
+    double
+
+cpdef number_t spherical_jn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_yn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_in(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_kn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+
+ctypedef fused Dd_number_t:
+    double complex
+    double
+
+ctypedef fused df_number_t:
+    double
+    float
+
+ctypedef fused dfg_number_t:
+    double
+    float
+    long double
+
+ctypedef fused dlp_number_t:
+    double
+    long
+    Py_ssize_t
+
+cpdef double voigt_profile(double x0, double x1, double x2) noexcept nogil
+cpdef double agm(double x0, double x1) noexcept nogil
+cdef void airy(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil
+cdef void airye(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil
+cpdef double bdtr(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtrc(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtri(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtrik(double x0, double x1, double x2) noexcept nogil
+cpdef double bdtrin(double x0, double x1, double x2) noexcept nogil
+cpdef double bei(double x0) noexcept nogil
+cpdef double beip(double x0) noexcept nogil
+cpdef double ber(double x0) noexcept nogil
+cpdef double berp(double x0) noexcept nogil
+cpdef double besselpoly(double x0, double x1, double x2) noexcept nogil
+cpdef double beta(double x0, double x1) noexcept nogil
+cpdef df_number_t betainc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betaincc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betaincinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betainccinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef double betaln(double x0, double x1) noexcept nogil
+cpdef double binom(double x0, double x1) noexcept nogil
+cpdef double boxcox(double x0, double x1) noexcept nogil
+cpdef double boxcox1p(double x0, double x1) noexcept nogil
+cpdef double btdtria(double x0, double x1, double x2) noexcept nogil
+cpdef double btdtrib(double x0, double x1, double x2) noexcept nogil
+cpdef double cbrt(double x0) noexcept nogil
+cpdef double chdtr(double x0, double x1) noexcept nogil
+cpdef double chdtrc(double x0, double x1) noexcept nogil
+cpdef double chdtri(double x0, double x1) noexcept nogil
+cpdef double chdtriv(double x0, double x1) noexcept nogil
+cpdef double chndtr(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtridf(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtrinc(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtrix(double x0, double x1, double x2) noexcept nogil
+cpdef double cosdg(double x0) noexcept nogil
+cpdef double cosm1(double x0) noexcept nogil
+cpdef double cotdg(double x0) noexcept nogil
+cpdef Dd_number_t dawsn(Dd_number_t x0) noexcept nogil
+cpdef double ellipe(double x0) noexcept nogil
+cpdef double ellipeinc(double x0, double x1) noexcept nogil
+cdef void ellipj(double x0, double x1, double *y0, double *y1, double *y2, double *y3) noexcept nogil
+cpdef double ellipkinc(double x0, double x1) noexcept nogil
+cpdef double ellipkm1(double x0) noexcept nogil
+cpdef double ellipk(double x0) noexcept nogil
+cpdef Dd_number_t elliprc(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t elliprd(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprf(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprg(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprj(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2, Dd_number_t x3) noexcept nogil
+cpdef double entr(double x0) noexcept nogil
+cpdef Dd_number_t erf(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfc(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfcx(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfi(Dd_number_t x0) noexcept nogil
+cpdef df_number_t erfinv(df_number_t x0) noexcept nogil
+cpdef double erfcinv(double x0) noexcept nogil
+cpdef Dd_number_t eval_chebyc(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebys(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_gegenbauer(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t eval_genlaguerre(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef double eval_hermite(Py_ssize_t x0, double x1) noexcept nogil
+cpdef double eval_hermitenorm(Py_ssize_t x0, double x1) noexcept nogil
+cpdef Dd_number_t eval_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef Dd_number_t eval_laguerre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef Dd_number_t eval_sh_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t exp1(Dd_number_t x0) noexcept nogil
+cpdef double exp10(double x0) noexcept nogil
+cpdef double exp2(double x0) noexcept nogil
+cpdef Dd_number_t expi(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t expit(dfg_number_t x0) noexcept nogil
+cpdef Dd_number_t expm1(Dd_number_t x0) noexcept nogil
+cpdef double expn(dlp_number_t x0, double x1) noexcept nogil
+cpdef double exprel(double x0) noexcept nogil
+cpdef double fdtr(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtrc(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtri(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtridfd(double x0, double x1, double x2) noexcept nogil
+cdef void fresnel(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cpdef Dd_number_t gamma(Dd_number_t x0) noexcept nogil
+cpdef double gammainc(double x0, double x1) noexcept nogil
+cpdef double gammaincc(double x0, double x1) noexcept nogil
+cpdef double gammainccinv(double x0, double x1) noexcept nogil
+cpdef double gammaincinv(double x0, double x1) noexcept nogil
+cpdef double gammaln(double x0) noexcept nogil
+cpdef double gammasgn(double x0) noexcept nogil
+cpdef double gdtr(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrc(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtria(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrib(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrix(double x0, double x1, double x2) noexcept nogil
+cpdef double complex hankel1(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel1e(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel2(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel2e(double x0, double complex x1) noexcept nogil
+cpdef double huber(double x0, double x1) noexcept nogil
+cpdef Dd_number_t hyp0f1(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t hyp1f1(double x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t hyp2f1(double x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef double hyperu(double x0, double x1, double x2) noexcept nogil
+cpdef double i0(double x0) noexcept nogil
+cpdef double i0e(double x0) noexcept nogil
+cpdef double i1(double x0) noexcept nogil
+cpdef double i1e(double x0) noexcept nogil
+cpdef double inv_boxcox(double x0, double x1) noexcept nogil
+cpdef double inv_boxcox1p(double x0, double x1) noexcept nogil
+cdef void it2i0k0(double x0, double *y0, double *y1) noexcept nogil
+cdef void it2j0y0(double x0, double *y0, double *y1) noexcept nogil
+cpdef double it2struve0(double x0) noexcept nogil
+cdef void itairy(double x0, double *y0, double *y1, double *y2, double *y3) noexcept nogil
+cdef void iti0k0(double x0, double *y0, double *y1) noexcept nogil
+cdef void itj0y0(double x0, double *y0, double *y1) noexcept nogil
+cpdef double itmodstruve0(double x0) noexcept nogil
+cpdef double itstruve0(double x0) noexcept nogil
+cpdef Dd_number_t iv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t ive(double x0, Dd_number_t x1) noexcept nogil
+cpdef double j0(double x0) noexcept nogil
+cpdef double j1(double x0) noexcept nogil
+cpdef Dd_number_t jv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t jve(double x0, Dd_number_t x1) noexcept nogil
+cpdef double k0(double x0) noexcept nogil
+cpdef double k0e(double x0) noexcept nogil
+cpdef double k1(double x0) noexcept nogil
+cpdef double k1e(double x0) noexcept nogil
+cpdef double kei(double x0) noexcept nogil
+cpdef double keip(double x0) noexcept nogil
+cdef void kelvin(double x0, double complex *y0, double complex *y1, double complex *y2, double complex *y3) noexcept nogil
+cpdef double ker(double x0) noexcept nogil
+cpdef double kerp(double x0) noexcept nogil
+cpdef double kl_div(double x0, double x1) noexcept nogil
+cpdef double kn(dlp_number_t x0, double x1) noexcept nogil
+cpdef double kolmogi(double x0) noexcept nogil
+cpdef double kolmogorov(double x0) noexcept nogil
+cpdef Dd_number_t kv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t kve(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t log1p(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t log_expit(dfg_number_t x0) noexcept nogil
+cpdef Dd_number_t log_ndtr(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t loggamma(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t logit(dfg_number_t x0) noexcept nogil
+cpdef double lpmv(double x0, double x1, double x2) noexcept nogil
+cpdef double mathieu_a(double x0, double x1) noexcept nogil
+cpdef double mathieu_b(double x0, double x1) noexcept nogil
+cdef void mathieu_cem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modcem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modcem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modsem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modsem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_sem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void modfresnelm(double x0, double complex *y0, double complex *y1) noexcept nogil
+cdef void modfresnelp(double x0, double complex *y0, double complex *y1) noexcept nogil
+cpdef double modstruve(double x0, double x1) noexcept nogil
+cpdef double nbdtr(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtrc(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtri(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtrik(double x0, double x1, double x2) noexcept nogil
+cpdef double nbdtrin(double x0, double x1, double x2) noexcept nogil
+cpdef df_number_t ncfdtr(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil
+cpdef df_number_t ncfdtri(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil
+cpdef double ncfdtridfd(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef double ncfdtridfn(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef double ncfdtrinc(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef df_number_t nctdtr(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef double nctdtridf(double x0, double x1, double x2) noexcept nogil
+cpdef double nctdtrinc(double x0, double x1, double x2) noexcept nogil
+cpdef double nctdtrit(double x0, double x1, double x2) noexcept nogil
+cpdef Dd_number_t ndtr(Dd_number_t x0) noexcept nogil
+cpdef double ndtri(double x0) noexcept nogil
+cpdef double nrdtrimn(double x0, double x1, double x2) noexcept nogil
+cpdef double nrdtrisd(double x0, double x1, double x2) noexcept nogil
+cdef void obl_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double obl_cv(double x0, double x1, double x2) noexcept nogil
+cdef void obl_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cdef void obl_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double owens_t(double x0, double x1) noexcept nogil
+cdef void pbdv(double x0, double x1, double *y0, double *y1) noexcept nogil
+cdef void pbvv(double x0, double x1, double *y0, double *y1) noexcept nogil
+cdef void pbwa(double x0, double x1, double *y0, double *y1) noexcept nogil
+cpdef double pdtr(double x0, double x1) noexcept nogil
+cpdef double pdtrc(double x0, double x1) noexcept nogil
+cpdef double pdtri(dlp_number_t x0, double x1) noexcept nogil
+cpdef double pdtrik(double x0, double x1) noexcept nogil
+cpdef double poch(double x0, double x1) noexcept nogil
+cpdef df_number_t powm1(df_number_t x0, df_number_t x1) noexcept nogil
+cdef void pro_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double pro_cv(double x0, double x1, double x2) noexcept nogil
+cdef void pro_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cdef void pro_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double pseudo_huber(double x0, double x1) noexcept nogil
+cpdef Dd_number_t psi(Dd_number_t x0) noexcept nogil
+cpdef double radian(double x0, double x1, double x2) noexcept nogil
+cpdef double rel_entr(double x0, double x1) noexcept nogil
+cpdef Dd_number_t rgamma(Dd_number_t x0) noexcept nogil
+cpdef double round(double x0) noexcept nogil
+cdef void shichi(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cdef void sici(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cpdef double sindg(double x0) noexcept nogil
+cpdef double smirnov(dlp_number_t x0, double x1) noexcept nogil
+cpdef double smirnovi(dlp_number_t x0, double x1) noexcept nogil
+cpdef Dd_number_t spence(Dd_number_t x0) noexcept nogil
+cpdef double complex sph_harm(dlp_number_t x0, dlp_number_t x1, double x2, double x3) noexcept nogil
+cpdef double stdtr(double x0, double x1) noexcept nogil
+cpdef double stdtridf(double x0, double x1) noexcept nogil
+cpdef double stdtrit(double x0, double x1) noexcept nogil
+cpdef double struve(double x0, double x1) noexcept nogil
+cpdef double tandg(double x0) noexcept nogil
+cpdef double tklmbda(double x0, double x1) noexcept nogil
+cpdef double complex wofz(double complex x0) noexcept nogil
+cpdef Dd_number_t wrightomega(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t xlog1py(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t xlogy(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef double y0(double x0) noexcept nogil
+cpdef double y1(double x0) noexcept nogil
+cpdef double yn(dlp_number_t x0, double x1) noexcept nogil
+cpdef Dd_number_t yv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t yve(double x0, Dd_number_t x1) noexcept nogil
+cpdef double zetac(double x0) noexcept nogil
+cpdef double wright_bessel(double x0, double x1, double x2) noexcept nogil
+cpdef double log_wright_bessel(double x0, double x1, double x2) noexcept nogil
+cpdef double ndtri_exp(double x0) noexcept nogil
diff --git a/venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi b/venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..024e962b10df8892631eaad20223f7fc8378ea83
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name) -> Any: ...
diff --git a/venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so b/venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so
new file mode 100644
index 0000000000000000000000000000000000000000..84e37bedbdfcc83bb65efc5d7f1961f2b749ebeb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/orthogonal.py b/venv/lib/python3.10/site-packages/scipy/special/orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b13a08a96cb683d72a4a00d6962446e1779c88a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/orthogonal.py
@@ -0,0 +1,45 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
+             'jacobi', 'laguerre', 'genlaguerre', 'hermite',
+             'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
+             'sh_chebyu', 'sh_jacobi']
+
+# Correspondence between new and old names of root functions
+_rootfuns_map = {'roots_legendre': 'p_roots',
+               'roots_chebyt': 't_roots',
+               'roots_chebyu': 'u_roots',
+               'roots_chebyc': 'c_roots',
+               'roots_chebys': 's_roots',
+               'roots_jacobi': 'j_roots',
+               'roots_laguerre': 'l_roots',
+               'roots_genlaguerre': 'la_roots',
+               'roots_hermite': 'h_roots',
+               'roots_hermitenorm': 'he_roots',
+               'roots_gegenbauer': 'cg_roots',
+               'roots_sh_legendre': 'ps_roots',
+               'roots_sh_chebyt': 'ts_roots',
+               'roots_sh_chebyu': 'us_roots',
+               'roots_sh_jacobi': 'js_roots'}
+
+
+__all__ = _polyfuns + list(_rootfuns_map.keys()) + [  # noqa: F822
+    'airy', 'p_roots', 't_roots', 'u_roots', 'c_roots', 's_roots',
+    'j_roots', 'l_roots', 'la_roots', 'h_roots', 'he_roots', 'cg_roots',
+    'ps_roots', 'ts_roots', 'us_roots', 'js_roots'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="orthogonal",
+                                   private_modules=["_orthogonal"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/sf_error.py b/venv/lib/python3.10/site-packages/scipy/special/sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ff73756acd4219a4ba94eb089bce7d4c32266d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/sf_error.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'SpecialFunctionWarning',
+    'SpecialFunctionError'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="sf_error",
+                                   private_modules=["_sf_error"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/specfun.py b/venv/lib/python3.10/site-packages/scipy/special/specfun.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fca00415a6406b8cdf41a42b6fbf991cea1f53f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/specfun.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.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+# ruff: noqa: F822
+__all__ = [
+    'clpmn',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'pbdv'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="specfun",
+                                   private_modules=["_basic", "_specfun"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py b/venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1e58487aaa547483c9f2531ac4efc2ad5e4795c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/spfun_stats.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.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['multigammaln']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="spfun_stats",
+                                   private_modules=["_spfun_stats"], all=__all__,
+                                   attribute=name)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f910ab94c266c99d78f939a78d3b7aceb784bd89
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_bdtr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_bdtr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43bc79adcfb8f7abedf17b479646cdc89b0721a2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_bdtr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boost_ufuncs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boost_ufuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93c51c66519b3c664945fc52fdcbde4becd1b405
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boost_ufuncs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d121db58c43df8e6d0625a369e28afbbebd358c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdflib.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdflib.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d93f0fe533567334ef1d8872b9352a947e915112
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdflib.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..057404720d8c7fe5085c6c4cba7dbecf9b6c50af
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cephes_intp_cast.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cephes_intp_cast.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d928f9d8bf87a0f708f40447c8a137446fc9c49
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cephes_intp_cast.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cosine_distr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cosine_distr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a7bdd5490d6f049159374190e41b7f672c32898
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cosine_distr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cython_special.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cython_special.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..850f23e94c5ecdcc0b95cfc6a3ca9ef89d882353
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cython_special.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97dbb2b43c91a327addb7a4843a0a9bb73cf33e1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_data.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_dd.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_dd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e7a668950a5b611b1bf5281626faf2f88c67844
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_dd.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_digamma.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_digamma.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddc326655c26a541197c15ad994e4e1707f9f8e6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_digamma.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ellip_harm.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ellip_harm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef411a2383bd7dc94e2eebdbecc4c6087cf3df4a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ellip_harm.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_erfinv.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_erfinv.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b73e4022ac847ad92c06fef2aa22f287dcf54ab6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_erfinv.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_exponential_integrals.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_exponential_integrals.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cca0234872602b147ae961f05fb32cc36cde917
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_exponential_integrals.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_extending.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_extending.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b454c46fc566c53f4dc0e657828ab7f20344098f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_extending.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_faddeeva.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_faddeeva.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f54c9a59e6b019cb21cdb3d56e51430c22614d1d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_faddeeva.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_gamma.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_gamma.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05e91b233d69081e985af8b39b798250a788b174
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_gamma.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_gammainc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_gammainc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bb326ca7ff24936c6d9165e527ce44516f64238
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_gammainc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hyp2f1.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hyp2f1.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d7ae78487f01c9eadde57a9f9baddb29f3936ef
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hyp2f1.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hypergeometric.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hypergeometric.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1ca90dcca7866cf07260e19cde364e8341aaaa5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hypergeometric.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_iv_ratio.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_iv_ratio.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d8137224a05357d29ab528691d148aace0561fe
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_iv_ratio.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_kolmogorov.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_kolmogorov.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20b9b715afa65d7bfdace28ecf87c0d0cc3b143d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_kolmogorov.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_lambertw.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_lambertw.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61c9819c55af29679db74e4b4b3e2ed28aa7b14e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_lambertw.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15d069a0cd2a3141296b350429975681a16aa170
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_log_softmax.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_log_softmax.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bd1f19ce87c19c42e61c16a930bc447dac46b23
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_log_softmax.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78805c5110bbb0a12abad5b58535e5190bceaf85
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logit.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logit.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..380c5545fa951274bed12cbe4d57aa97f9eb6c59
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logit.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logsumexp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logsumexp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..599543c38ad1cdbc20758a6b47f4302fc51f1c92
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logsumexp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..802a5adfbea5dc13e7c31212d3bccabe04fb4c35
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_nan_inputs.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_nan_inputs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1fbef362c9b99f980facf323d7369a8eb1f9370
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_nan_inputs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ndtr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ndtr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f8d7fe8728bb13925b76111b9d8a681d3242e42
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ndtr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ndtri_exp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ndtri_exp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18412dca76b56726309b7d80733f37d98bd0c20b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ndtri_exp.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fca37190d3deaff07085cd4d1705f73379ebdc93
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3da4f5bd87bb2929ecbf400305502733acd19fab
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_owens_t.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_owens_t.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4b1f5be571c01d0e27dc3c46c2f6307067bd2a9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_owens_t.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pcf.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pcf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e378c2916f41da3a43045d8b2f3799b0d80d5a0c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pcf.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pdtr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pdtr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0835cd8f281938098dda16d4341135e0291da800
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pdtr.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_powm1.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_powm1.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f038b66b83b804f05792c1ba7ead622bb9601e5d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_powm1.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_expn_asy.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_expn_asy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a075c0fe583e080cc091dc2421bdb1dfb3d4f4f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_expn_asy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_gammainc.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_gammainc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd6b06c62247a2afc39798a2fe941d36e19b6298
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_gammainc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12a286b3c4e52114bae422cc554a980f45f21fee
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_precompute_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_round.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_round.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1164e33275f559c6c97aedcf772c2991d88651b9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_round.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sf_error.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sf_error.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..057f98a2b0c0a6e61a2da06c27f69d1de40e321f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sf_error.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sici.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sici.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89b31b6bc04b989481739643f452986d6af491ac
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sici.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_specfun.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_specfun.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d3c412e3668c02626151d7a7abfcf44cc339d88
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_specfun.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spence.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spence.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78b5932c87a3cc7edd666cd8099d667e3b23a5b1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spence.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spfun_stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spfun_stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83287741cd856d3ce7f5085750c15e5d630d7a79
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spfun_stats.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sph_harm.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sph_harm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9d36eb68d986ded901db2e4f3e9103979bd7152
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sph_harm.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spherical_bessel.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spherical_bessel.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42f4f10845b5ea6c430da87400fd585c60332d88
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spherical_bessel.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_support_alternative_backends.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_support_alternative_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13938400ba038f7737b65b9bd5674e6914442ee3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_support_alternative_backends.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_trig.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_trig.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbfe50f5ce59ce0a5ec2e361a8144478fd7a0ffe
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_trig.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ufunc_signatures.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ufunc_signatures.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6110e61dde834ad745aaff980ee78d2d1db79bd6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ufunc_signatures.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wright_bessel.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wright_bessel.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6aa287aa2a0aa4a1a08cb2f4aa02e35853fedbc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wright_bessel.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wrightomega.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wrightomega.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91a9e60182507fc1e870079f61d067a9b49303d6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wrightomega.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_xsf_cuda.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_xsf_cuda.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5d102c5534bce577cd1ed35bcbac24ff3f2f7bf
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_xsf_cuda.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_zeta.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_zeta.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96c93aa599a2afb3f833fed83b6fcd1c6159e57c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_zeta.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx b/venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..ca3bf2167f0f7726f8b0acb60ed8b8798a518d79
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+
+from scipy.special.cython_special cimport beta, gamma
+
+cpdef double cy_beta(double a, double b):
+    return beta(a, b)
+
+cpdef double complex cy_gamma(double complex z):
+    return gamma(z)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build b/venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..2a5e1535a16f840f31ca0207513e7c060767ea12
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build
@@ -0,0 +1,25 @@
+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.0.8')
+  error('tests requires Cython >= 3.0.8')
+endif
+
+py3.extension_module(
+  'extending',
+  'extending.pyx',
+  install: false,
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+  'extending_cpp',
+  extending_cpp,
+  install: false,
+  override_options : ['cython_language=cpp']
+)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py b/venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/data/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/data/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbd9def389188e2a69430e710bc82ceb3af232ef
Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/data/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..67bb83f1f1682e5eb83cc66f052ea51e3caf8757
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py
@@ -0,0 +1,4682 @@
+# this program corresponds to special.py
+
+### Means test is not done yet
+# E   Means test is giving error (E)
+# F   Means test is failing (F)
+# EF  Means test is giving error and Failing
+#!   Means test is segfaulting
+# 8   Means test runs forever
+
+###  test_besselpoly
+###  test_mathieu_a
+###  test_mathieu_even_coef
+###  test_mathieu_odd_coef
+###  test_modfresnelp
+###  test_modfresnelm
+#    test_pbdv_seq
+###  test_pbvv_seq
+###  test_sph_harm
+
+import functools
+import itertools
+import operator
+import platform
+import sys
+
+import numpy as np
+from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp,
+        log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, double,
+        array_equal)
+
+import pytest
+from pytest import raises as assert_raises
+from numpy.testing import (assert_equal, assert_almost_equal,
+        assert_array_equal, assert_array_almost_equal, assert_approx_equal,
+        assert_, assert_allclose, assert_array_almost_equal_nulp,
+        suppress_warnings)
+
+from scipy import special
+import scipy.special._ufuncs as cephes
+from scipy.special import ellipe, ellipk, ellipkm1
+from scipy.special import elliprc, elliprd, elliprf, elliprg, elliprj
+from scipy.special import softplus
+from scipy.special import mathieu_odd_coef, mathieu_even_coef, stirling2
+from scipy.special import lpn, lpmn, clpmn
+from scipy._lib._util import np_long, np_ulong
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal, SCIPY_ARRAY_API
+
+from scipy.special._basic import (
+    _FACTORIALK_LIMITS_64BITS, _FACTORIALK_LIMITS_32BITS, _is_subdtype
+)
+from scipy.special._testutils import with_special_errors, \
+     assert_func_equal, FuncData
+
+import math
+
+
+native_int = np.int32 if (
+    sys.platform == 'win32'
+    or platform.architecture()[0] == "32bit"
+) else np.int64
+
+
+class TestCephes:
+    def test_airy(self):
+        cephes.airy(0)
+
+    def test_airye(self):
+        cephes.airye(0)
+
+    def test_binom(self):
+        n = np.array([0.264, 4, 5.2, 17])
+        k = np.array([2, 0.4, 7, 3.3])
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+        rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389,
+            -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846],
+            [10.92, 2.22993515861399, -0.00585728, 10.468891352063146],
+            [136, 3.5252179590758828, 19448, 1024.5526916174495]])
+        assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13)
+
+        # Test branches in implementation
+        rng = np.random.RandomState(1234)
+        n = np.r_[np.arange(-7, 30), 1000*rng.rand(30) - 500]
+        k = np.arange(0, 102)
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+
+        assert_func_equal(cephes.binom,
+                          cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)),
+                          nk,
+                          atol=1e-10, rtol=1e-10)
+
+    def test_binom_2(self):
+        # Test branches in implementation
+        np.random.seed(1234)
+        n = np.r_[np.logspace(1, 300, 20)]
+        k = np.arange(0, 102)
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+
+        assert_func_equal(cephes.binom,
+                          cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)),
+                          nk,
+                          atol=1e-10, rtol=1e-10)
+
+    def test_binom_exact(self):
+        @np.vectorize
+        def binom_int(n, k):
+            n = int(n)
+            k = int(k)
+            num = 1
+            den = 1
+            for i in range(1, k+1):
+                num *= i + n - k
+                den *= i
+            return float(num/den)
+
+        np.random.seed(1234)
+        n = np.arange(1, 15)
+        k = np.arange(0, 15)
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+        nk = nk[nk[:,0] >= nk[:,1]]
+        assert_func_equal(cephes.binom,
+                          binom_int(nk[:,0], nk[:,1]),
+                          nk,
+                          atol=0, rtol=0)
+
+    def test_binom_nooverflow_8346(self):
+        # Test (binom(n, k) doesn't overflow prematurely */
+        dataset = [
+            (1000, 500, 2.70288240945436551e+299),
+            (1002, 501, 1.08007396880791225e+300),
+            (1004, 502, 4.31599279169058121e+300),
+            (1006, 503, 1.72468101616263781e+301),
+            (1008, 504, 6.89188009236419153e+301),
+            (1010, 505, 2.75402257948335448e+302),
+            (1012, 506, 1.10052048531923757e+303),
+            (1014, 507, 4.39774063758732849e+303),
+            (1016, 508, 1.75736486108312519e+304),
+            (1018, 509, 7.02255427788423734e+304),
+            (1020, 510, 2.80626776829962255e+305),
+            (1022, 511, 1.12140876377061240e+306),
+            (1024, 512, 4.48125455209897109e+306),
+            (1026, 513, 1.79075474304149900e+307),
+            (1028, 514, 7.15605105487789676e+307)
+        ]
+        dataset = np.asarray(dataset)
+        FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check()
+
+    def test_bdtr(self):
+        assert_equal(cephes.bdtr(1,1,0.5),1.0)
+
+    def test_bdtri(self):
+        assert_equal(cephes.bdtri(1,3,0.5),0.5)
+
+    def test_bdtrc(self):
+        assert_equal(cephes.bdtrc(1,3,0.5),0.5)
+
+    def test_bdtrin(self):
+        assert_equal(cephes.bdtrin(1,0,1),5.0)
+
+    def test_bdtrik(self):
+        cephes.bdtrik(1,3,0.5)
+
+    def test_bei(self):
+        assert_equal(cephes.bei(0),0.0)
+
+    def test_beip(self):
+        assert_equal(cephes.beip(0),0.0)
+
+    def test_ber(self):
+        assert_equal(cephes.ber(0),1.0)
+
+    def test_berp(self):
+        assert_equal(cephes.berp(0),0.0)
+
+    def test_besselpoly(self):
+        assert_equal(cephes.besselpoly(0,0,0),1.0)
+
+    def test_btdtria(self):
+        assert_equal(cephes.btdtria(1,1,1),5.0)
+
+    def test_btdtrib(self):
+        assert_equal(cephes.btdtrib(1,1,1),5.0)
+
+    def test_cbrt(self):
+        assert_approx_equal(cephes.cbrt(1),1.0)
+
+    def test_chdtr(self):
+        assert_equal(cephes.chdtr(1,0),0.0)
+
+    def test_chdtrc(self):
+        assert_equal(cephes.chdtrc(1,0),1.0)
+
+    def test_chdtri(self):
+        assert_equal(cephes.chdtri(1,1),0.0)
+
+    def test_chdtriv(self):
+        assert_equal(cephes.chdtriv(0,0),5.0)
+
+    def test_chndtr(self):
+        assert_equal(cephes.chndtr(0,1,0),0.0)
+
+        # Each row holds (x, nu, lam, expected_value)
+        # These values were computed using Wolfram Alpha with
+        #     CDF[NoncentralChiSquareDistribution[nu, lam], x]
+        values = np.array([
+            [25.00, 20.0, 400, 4.1210655112396197139e-57],
+            [25.00, 8.00, 250, 2.3988026526832425878e-29],
+            [0.001, 8.00, 40., 5.3761806201366039084e-24],
+            [0.010, 8.00, 40., 5.45396231055999457039e-20],
+            [20.00, 2.00, 107, 1.39390743555819597802e-9],
+            [22.50, 2.00, 107, 7.11803307138105870671e-9],
+            [25.00, 2.00, 107, 3.11041244829864897313e-8],
+            [3.000, 2.00, 1.0, 0.62064365321954362734],
+            [350.0, 300., 10., 0.93880128006276407710],
+            [100.0, 13.5, 10., 0.99999999650104210949],
+            [700.0, 20.0, 400, 0.99999999925680650105],
+            [150.0, 13.5, 10., 0.99999999999999983046],
+            [160.0, 13.5, 10., 0.99999999999999999518],  # 1.0
+        ])
+        cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2])
+        assert_allclose(cdf, values[:, 3], rtol=1e-12)
+
+        assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0)
+        assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0)
+        assert_(np.isnan(cephes.chndtr(np.nan, 1, 2)))
+        assert_(np.isnan(cephes.chndtr(5, np.nan, 2)))
+        assert_(np.isnan(cephes.chndtr(5, 1, np.nan)))
+
+    def test_chndtridf(self):
+        assert_equal(cephes.chndtridf(0,0,1),5.0)
+
+    def test_chndtrinc(self):
+        assert_equal(cephes.chndtrinc(0,1,0),5.0)
+
+    def test_chndtrix(self):
+        assert_equal(cephes.chndtrix(0,1,0),0.0)
+
+    def test_cosdg(self):
+        assert_equal(cephes.cosdg(0),1.0)
+
+    def test_cosm1(self):
+        assert_equal(cephes.cosm1(0),0.0)
+
+    def test_cotdg(self):
+        assert_almost_equal(cephes.cotdg(45),1.0)
+
+    def test_dawsn(self):
+        assert_equal(cephes.dawsn(0),0.0)
+        assert_allclose(cephes.dawsn(1.23), 0.50053727749081767)
+
+    def test_diric(self):
+        # Test behavior near multiples of 2pi.  Regression test for issue
+        # described in gh-4001.
+        n_odd = [1, 5, 25]
+        x = np.array(2*np.pi + 5e-5).astype(np.float32)
+        assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7)
+        x = np.array(2*np.pi + 1e-9).astype(np.float64)
+        assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15)
+        x = np.array(2*np.pi + 1e-15).astype(np.float64)
+        assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15)
+        if hasattr(np, 'float128'):
+            # No float128 available in 32-bit numpy
+            x = np.array(2*np.pi + 1e-12).astype(np.float128)
+            assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19)
+
+        n_even = [2, 4, 24]
+        x = np.array(2*np.pi + 1e-9).astype(np.float64)
+        assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15)
+
+        # Test at some values not near a multiple of pi
+        x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi)
+        octave_result = [0.872677996249965, 0.539344662916632,
+                         0.127322003750035, -0.206011329583298]
+        assert_almost_equal(special.diric(x, 3), octave_result, decimal=15)
+
+    def test_diric_broadcasting(self):
+        x = np.arange(5)
+        n = np.array([1, 3, 7])
+        assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size))
+
+    def test_ellipe(self):
+        assert_equal(cephes.ellipe(1),1.0)
+
+    def test_ellipeinc(self):
+        assert_equal(cephes.ellipeinc(0,1),0.0)
+
+    def test_ellipj(self):
+        cephes.ellipj(0,1)
+
+    def test_ellipk(self):
+        assert_allclose(ellipk(0), pi/2)
+
+    def test_ellipkinc(self):
+        assert_equal(cephes.ellipkinc(0,0),0.0)
+
+    def test_erf(self):
+        assert_equal(cephes.erf(0), 0.0)
+
+    def test_erf_symmetry(self):
+        x = 5.905732037710919
+        assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0)
+
+    def test_erfc(self):
+        assert_equal(cephes.erfc(0), 1.0)
+
+    def test_exp10(self):
+        assert_approx_equal(cephes.exp10(2),100.0)
+
+    def test_exp2(self):
+        assert_equal(cephes.exp2(2),4.0)
+
+    def test_expm1(self):
+        assert_equal(cephes.expm1(0),0.0)
+        assert_equal(cephes.expm1(np.inf), np.inf)
+        assert_equal(cephes.expm1(-np.inf), -1)
+        assert_equal(cephes.expm1(np.nan), np.nan)
+
+    def test_expm1_complex(self):
+        expm1 = cephes.expm1
+        assert_equal(expm1(0 + 0j), 0 + 0j)
+        assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0))
+        assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf))
+        assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf))
+        assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf))
+        assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf))
+        assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan))
+        assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0))
+        assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0))
+        assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan))
+        assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan))
+
+    @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points')
+    def test_expm1_complex_hard(self):
+        # The real part of this function is difficult to evaluate when
+        # z.real = -log(cos(z.imag)).
+        y = np.array([0.1, 0.2, 0.3, 5, 11, 20])
+        x = -np.log(np.cos(y))
+        z = x + 1j*y
+
+        # evaluate using mpmath.expm1 with dps=1000
+        expected = np.array([-5.5507901846769623e-17+0.10033467208545054j,
+                              2.4289354732893695e-18+0.20271003550867248j,
+                              4.5235500262585768e-17+0.30933624960962319j,
+                              7.8234305217489006e-17-3.3805150062465863j,
+                             -1.3685191953697676e-16-225.95084645419513j,
+                              8.7175620481291045e-17+2.2371609442247422j])
+        found = cephes.expm1(z)
+        # this passes.
+        assert_array_almost_equal_nulp(found.imag, expected.imag, 3)
+        # this fails.
+        assert_array_almost_equal_nulp(found.real, expected.real, 20)
+
+    def test_fdtr(self):
+        assert_equal(cephes.fdtr(1, 1, 0), 0.0)
+        # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10]
+        assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488,
+                        rtol=1e-12)
+
+    def test_fdtrc(self):
+        assert_equal(cephes.fdtrc(1, 1, 0), 1.0)
+        # Computed using Wolfram Alpha:
+        #   1 - CDF[FRatioDistribution[2, 1/10], 1e10]
+        assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512,
+                        rtol=1e-12)
+
+    def test_fdtri(self):
+        assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]),
+                        array([0.9937365, 1.00630298]), rtol=1e-6)
+        # From Wolfram Alpha:
+        #   CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874...
+        p = 0.8756751669632105666874
+        assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12)
+
+    @pytest.mark.xfail(reason='Returns nan on i686.')
+    def test_fdtri_mysterious_failure(self):
+        assert_allclose(cephes.fdtri(1, 1, 0.5), 1)
+
+    def test_fdtridfd(self):
+        assert_equal(cephes.fdtridfd(1,0,0),5.0)
+
+    def test_fresnel(self):
+        assert_equal(cephes.fresnel(0),(0.0,0.0))
+
+    def test_gamma(self):
+        assert_equal(cephes.gamma(5),24.0)
+
+    def test_gammainccinv(self):
+        assert_equal(cephes.gammainccinv(5,1),0.0)
+
+    def test_gammaln(self):
+        cephes.gammaln(10)
+
+    def test_gammasgn(self):
+        vals = np.array(
+            [-np.inf, -4, -3.5, -2.3, -0.0, 0.0, 1, 4.2, np.inf], np.float64
+        )
+        reference = np.array(
+            [np.nan, np.nan, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0], np.float64
+        )
+        assert_array_equal(cephes.gammasgn(vals), reference)
+
+    def test_gdtr(self):
+        assert_equal(cephes.gdtr(1,1,0),0.0)
+
+    def test_gdtr_inf(self):
+        assert_equal(cephes.gdtr(1,1,np.inf),1.0)
+
+    def test_gdtrc(self):
+        assert_equal(cephes.gdtrc(1,1,0),1.0)
+
+    def test_gdtria(self):
+        assert_equal(cephes.gdtria(0,1,1),0.0)
+
+    def test_gdtrib(self):
+        cephes.gdtrib(1,0,1)
+        # assert_equal(cephes.gdtrib(1,0,1),5.0)
+
+    def test_gdtrix(self):
+        cephes.gdtrix(1,1,.1)
+
+    def test_hankel1(self):
+        cephes.hankel1(1,1)
+
+    def test_hankel1e(self):
+        cephes.hankel1e(1,1)
+
+    def test_hankel2(self):
+        cephes.hankel2(1,1)
+
+    def test_hankel2e(self):
+        cephes.hankel2e(1,1)
+
+    def test_hyp1f1(self):
+        assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0))
+        assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095)
+        cephes.hyp1f1(1,1,1)
+
+    def test_hyp2f1(self):
+        assert_equal(cephes.hyp2f1(1,1,1,0),1.0)
+
+    def test_i0(self):
+        assert_equal(cephes.i0(0),1.0)
+
+    def test_i0e(self):
+        assert_equal(cephes.i0e(0),1.0)
+
+    def test_i1(self):
+        assert_equal(cephes.i1(0),0.0)
+
+    def test_i1e(self):
+        assert_equal(cephes.i1e(0),0.0)
+
+    def test_it2i0k0(self):
+        cephes.it2i0k0(1)
+
+    def test_it2j0y0(self):
+        cephes.it2j0y0(1)
+
+    def test_it2struve0(self):
+        cephes.it2struve0(1)
+
+    def test_itairy(self):
+        cephes.itairy(1)
+
+    def test_iti0k0(self):
+        assert_equal(cephes.iti0k0(0),(0.0,0.0))
+
+    def test_itj0y0(self):
+        assert_equal(cephes.itj0y0(0),(0.0,0.0))
+
+    def test_itmodstruve0(self):
+        assert_equal(cephes.itmodstruve0(0),0.0)
+
+    def test_itstruve0(self):
+        assert_equal(cephes.itstruve0(0),0.0)
+
+    def test_iv(self):
+        assert_equal(cephes.iv(1,0),0.0)
+
+    def test_ive(self):
+        assert_equal(cephes.ive(1,0),0.0)
+
+    def test_j0(self):
+        assert_equal(cephes.j0(0),1.0)
+
+    def test_j1(self):
+        assert_equal(cephes.j1(0),0.0)
+
+    def test_jn(self):
+        assert_equal(cephes.jn(0,0),1.0)
+
+    def test_jv(self):
+        assert_equal(cephes.jv(0,0),1.0)
+
+    def test_jve(self):
+        assert_equal(cephes.jve(0,0),1.0)
+
+    def test_k0(self):
+        cephes.k0(2)
+
+    def test_k0e(self):
+        cephes.k0e(2)
+
+    def test_k1(self):
+        cephes.k1(2)
+
+    def test_k1e(self):
+        cephes.k1e(2)
+
+    def test_kei(self):
+        cephes.kei(2)
+
+    def test_keip(self):
+        assert_equal(cephes.keip(0),0.0)
+
+    def test_ker(self):
+        cephes.ker(2)
+
+    def test_kerp(self):
+        cephes.kerp(2)
+
+    def test_kelvin(self):
+        cephes.kelvin(2)
+
+    def test_kn(self):
+        cephes.kn(1,1)
+
+    def test_kolmogi(self):
+        assert_equal(cephes.kolmogi(1),0.0)
+        assert_(np.isnan(cephes.kolmogi(np.nan)))
+
+    def test_kolmogorov(self):
+        assert_equal(cephes.kolmogorov(0), 1.0)
+
+    def test_kolmogp(self):
+        assert_equal(cephes._kolmogp(0), -0.0)
+
+    def test_kolmogc(self):
+        assert_equal(cephes._kolmogc(0), 0.0)
+
+    def test_kolmogci(self):
+        assert_equal(cephes._kolmogci(0), 0.0)
+        assert_(np.isnan(cephes._kolmogci(np.nan)))
+
+    def test_kv(self):
+        cephes.kv(1,1)
+
+    def test_kve(self):
+        cephes.kve(1,1)
+
+    def test_log1p(self):
+        log1p = cephes.log1p
+        assert_equal(log1p(0), 0.0)
+        assert_equal(log1p(-1), -np.inf)
+        assert_equal(log1p(-2), np.nan)
+        assert_equal(log1p(np.inf), np.inf)
+
+    def test_log1p_complex(self):
+        log1p = cephes.log1p
+        c = complex
+        assert_equal(log1p(0 + 0j), 0 + 0j)
+        assert_equal(log1p(c(-1, 0)), c(-np.inf, 0))
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2))
+            assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan))
+            assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi))
+            assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0))
+            assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4))
+            assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4))
+            assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan))
+            assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan))
+            assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan))
+            assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan))
+            assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan))
+
+    def test_lpmv(self):
+        assert_equal(cephes.lpmv(0,0,1),1.0)
+
+    def test_mathieu_a(self):
+        assert_equal(cephes.mathieu_a(1,0),1.0)
+
+    def test_mathieu_b(self):
+        assert_equal(cephes.mathieu_b(1,0),1.0)
+
+    def test_mathieu_cem(self):
+        assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0))
+
+        # Test AMS 20.2.27
+        @np.vectorize
+        def ce_smallq(m, q, z):
+            z *= np.pi/180
+            if m == 0:
+                # + O(q^2)
+                return 2**(-0.5) * (1 - .5*q*cos(2*z))
+            elif m == 1:
+                # + O(q^2)
+                return cos(z) - q/8 * cos(3*z)
+            elif m == 2:
+                # + O(q^2)
+                return cos(2*z) - q*(cos(4*z)/12 - 1/4)
+            else:
+                # + O(q^2)
+                return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1)))
+        m = np.arange(0, 100)
+        q = np.r_[0, np.logspace(-30, -9, 10)]
+        assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0],
+                        ce_smallq(m[:,None], q[None,:], 0.123),
+                        rtol=1e-14, atol=0)
+
+    def test_mathieu_sem(self):
+        assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0))
+
+        # Test AMS 20.2.27
+        @np.vectorize
+        def se_smallq(m, q, z):
+            z *= np.pi/180
+            if m == 1:
+                # + O(q^2)
+                return sin(z) - q/8 * sin(3*z)
+            elif m == 2:
+                # + O(q^2)
+                return sin(2*z) - q*sin(4*z)/12
+            else:
+                # + O(q^2)
+                return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1)))
+        m = np.arange(1, 100)
+        q = np.r_[0, np.logspace(-30, -9, 10)]
+        assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0],
+                        se_smallq(m[:,None], q[None,:], 0.123),
+                        rtol=1e-14, atol=0)
+
+    def test_mathieu_modcem1(self):
+        assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0))
+
+    def test_mathieu_modcem2(self):
+        cephes.mathieu_modcem2(1,1,1)
+
+        # Test reflection relation AMS 20.6.19
+        m = np.arange(0, 4)[:,None,None]
+        q = np.r_[np.logspace(-2, 2, 10)][None,:,None]
+        z = np.linspace(0, 1, 7)[None,None,:]
+
+        y1 = cephes.mathieu_modcem2(m, q, -z)[0]
+
+        fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0]
+        y2 = (-cephes.mathieu_modcem2(m, q, z)[0]
+              - 2*fr*cephes.mathieu_modcem1(m, q, z)[0])
+
+        assert_allclose(y1, y2, rtol=1e-10)
+
+    def test_mathieu_modsem1(self):
+        assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0))
+
+    def test_mathieu_modsem2(self):
+        cephes.mathieu_modsem2(1,1,1)
+
+        # Test reflection relation AMS 20.6.20
+        m = np.arange(1, 4)[:,None,None]
+        q = np.r_[np.logspace(-2, 2, 10)][None,:,None]
+        z = np.linspace(0, 1, 7)[None,None,:]
+
+        y1 = cephes.mathieu_modsem2(m, q, -z)[0]
+        fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1]
+        y2 = (cephes.mathieu_modsem2(m, q, z)[0]
+              - 2*fr*cephes.mathieu_modsem1(m, q, z)[0])
+        assert_allclose(y1, y2, rtol=1e-10)
+
+    def test_mathieu_overflow(self):
+        # Check that these return NaNs instead of causing a SEGV
+        assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan))
+
+    def test_mathieu_ticket_1847(self):
+        # Regression test --- this call had some out-of-bounds access
+        # and could return nan occasionally
+        for k in range(60):
+            v = cephes.mathieu_modsem2(2, 100, -1)
+            # Values from ACM TOMS 804 (derivate by numerical differentiation)
+            assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10)
+            assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4)
+
+    def test_modfresnelm(self):
+        cephes.modfresnelm(0)
+
+    def test_modfresnelp(self):
+        cephes.modfresnelp(0)
+
+    def test_modstruve(self):
+        assert_equal(cephes.modstruve(1,0),0.0)
+
+    def test_nbdtr(self):
+        assert_equal(cephes.nbdtr(1,1,1),1.0)
+
+    def test_nbdtrc(self):
+        assert_equal(cephes.nbdtrc(1,1,1),0.0)
+
+    def test_nbdtri(self):
+        assert_equal(cephes.nbdtri(1,1,1),1.0)
+
+    def test_nbdtrik(self):
+        cephes.nbdtrik(1,.4,.5)
+
+    def test_nbdtrin(self):
+        assert_equal(cephes.nbdtrin(1,0,0),5.0)
+
+    def test_ncfdtr(self):
+        assert_equal(cephes.ncfdtr(1,1,1,0),0.0)
+
+    def test_ncfdtri(self):
+        assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0)
+        f = [0.5, 1, 1.5]
+        p = cephes.ncfdtr(2, 3, 1.5, f)
+        assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f)
+
+    @pytest.mark.xfail(
+        reason=(
+            "ncfdtr uses a Boost math implementation but ncfdtridfd"
+            "inverts the less accurate cdflib implementation of ncfdtr."
+        )
+    )
+    def test_ncfdtridfd(self):
+        dfd = [1, 2, 3]
+        p = cephes.ncfdtr(2, dfd, 0.25, 15)
+        assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd)
+
+    @pytest.mark.xfail(
+        reason=(
+            "ncfdtr uses a Boost math implementation but ncfdtridfn"
+            "inverts the less accurate cdflib implementation of ncfdtr."
+        )
+    )
+    def test_ncfdtridfn(self):
+        dfn = [0.1, 1, 2, 3, 1e4]
+        p = cephes.ncfdtr(dfn, 2, 0.25, 15)
+        assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5)
+
+    @pytest.mark.xfail(
+        reason=(
+            "ncfdtr uses a Boost math implementation but ncfdtrinc"
+            "inverts the less accurate cdflib implementation of ncfdtr."
+        )
+    )
+    def test_ncfdtrinc(self):
+        nc = [0.5, 1.5, 2.0]
+        p = cephes.ncfdtr(2, 3, nc, 15)
+        assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc)
+
+    def test_nctdtr(self):
+        assert_equal(cephes.nctdtr(1,0,0),0.5)
+        assert_equal(cephes.nctdtr(9, 65536, 45), 0.0)
+
+        assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5)
+        assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.)))
+        assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.)
+
+        assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.)))
+        assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.)))
+        assert_(np.isnan(cephes.nctdtr(2., 1., np.nan)))
+
+    def test_nctdtridf(self):
+        cephes.nctdtridf(1,0.5,0)
+
+    def test_nctdtrinc(self):
+        cephes.nctdtrinc(1,0,0)
+
+    def test_nctdtrit(self):
+        cephes.nctdtrit(.1,0.2,.5)
+
+    def test_nrdtrimn(self):
+        assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0)
+
+    def test_nrdtrisd(self):
+        assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0,
+                         atol=0, rtol=0)
+
+    def test_obl_ang1(self):
+        cephes.obl_ang1(1,1,1,0)
+
+    def test_obl_ang1_cv(self):
+        result = cephes.obl_ang1_cv(1,1,1,1,0)
+        assert_almost_equal(result[0],1.0)
+        assert_almost_equal(result[1],0.0)
+
+    def test_obl_cv(self):
+        assert_equal(cephes.obl_cv(1,1,0),2.0)
+
+    def test_obl_rad1(self):
+        cephes.obl_rad1(1,1,1,0)
+
+    def test_obl_rad1_cv(self):
+        cephes.obl_rad1_cv(1,1,1,1,0)
+
+    def test_obl_rad2(self):
+        cephes.obl_rad2(1,1,1,0)
+
+    def test_obl_rad2_cv(self):
+        cephes.obl_rad2_cv(1,1,1,1,0)
+
+    def test_pbdv(self):
+        assert_equal(cephes.pbdv(1,0),(0.0,1.0))
+
+    def test_pbvv(self):
+        cephes.pbvv(1,0)
+
+    def test_pbwa(self):
+        cephes.pbwa(1,0)
+
+    def test_pdtr(self):
+        val = cephes.pdtr(0, 1)
+        assert_almost_equal(val, np.exp(-1))
+        # Edge case: m = 0.
+        val = cephes.pdtr([0, 1, 2], 0)
+        assert_array_equal(val, [1, 1, 1])
+
+    def test_pdtrc(self):
+        val = cephes.pdtrc(0, 1)
+        assert_almost_equal(val, 1 - np.exp(-1))
+        # Edge case: m = 0.
+        val = cephes.pdtrc([0, 1, 2], 0.0)
+        assert_array_equal(val, [0, 0, 0])
+
+    def test_pdtri(self):
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "floating point number truncated to an integer")
+            cephes.pdtri(0.5,0.5)
+
+    def test_pdtrik(self):
+        k = cephes.pdtrik(0.5, 1)
+        assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5)
+        # Edge case: m = 0 or very small.
+        k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6])
+        assert_array_equal(k, np.zeros((3, 3)))
+
+    def test_pro_ang1(self):
+        cephes.pro_ang1(1,1,1,0)
+
+    def test_pro_ang1_cv(self):
+        assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0),
+                                  array((1.0,0.0)))
+
+    def test_pro_cv(self):
+        assert_equal(cephes.pro_cv(1,1,0),2.0)
+
+    def test_pro_rad1(self):
+        cephes.pro_rad1(1,1,1,0.1)
+
+    def test_pro_rad1_cv(self):
+        cephes.pro_rad1_cv(1,1,1,1,0)
+
+    def test_pro_rad2(self):
+        cephes.pro_rad2(1,1,1,0)
+
+    def test_pro_rad2_cv(self):
+        cephes.pro_rad2_cv(1,1,1,1,0)
+
+    def test_psi(self):
+        cephes.psi(1)
+
+    def test_radian(self):
+        assert_equal(cephes.radian(0,0,0),0)
+
+    def test_rgamma(self):
+        assert_equal(cephes.rgamma(1),1.0)
+
+    def test_round(self):
+        assert_equal(cephes.round(3.4),3.0)
+        assert_equal(cephes.round(-3.4),-3.0)
+        assert_equal(cephes.round(3.6),4.0)
+        assert_equal(cephes.round(-3.6),-4.0)
+        assert_equal(cephes.round(3.5),4.0)
+        assert_equal(cephes.round(-3.5),-4.0)
+
+    def test_shichi(self):
+        cephes.shichi(1)
+
+    def test_sici(self):
+        cephes.sici(1)
+
+        s, c = cephes.sici(np.inf)
+        assert_almost_equal(s, np.pi * 0.5)
+        assert_almost_equal(c, 0)
+
+        s, c = cephes.sici(-np.inf)
+        assert_almost_equal(s, -np.pi * 0.5)
+        assert_(np.isnan(c), "cosine integral(-inf) is not nan")
+
+    def test_sindg(self):
+        assert_equal(cephes.sindg(90),1.0)
+
+    def test_smirnov(self):
+        assert_equal(cephes.smirnov(1,.1),0.9)
+        assert_(np.isnan(cephes.smirnov(1,np.nan)))
+
+    def test_smirnovp(self):
+        assert_equal(cephes._smirnovp(1, .1), -1)
+        assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1))
+        assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1))
+        assert_(np.isnan(cephes._smirnovp(1, np.nan)))
+
+    def test_smirnovc(self):
+        assert_equal(cephes._smirnovc(1,.1),0.1)
+        assert_(np.isnan(cephes._smirnovc(1,np.nan)))
+        x10 = np.linspace(0, 1, 11, endpoint=True)
+        assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10))
+        x4 = np.linspace(0, 1, 5, endpoint=True)
+        assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4))
+
+    def test_smirnovi(self):
+        assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4)
+        assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6)
+        assert_(np.isnan(cephes.smirnovi(1,np.nan)))
+
+    def test_smirnovci(self):
+        assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4)
+        assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6)
+        assert_(np.isnan(cephes._smirnovci(1,np.nan)))
+
+    def test_spence(self):
+        assert_equal(cephes.spence(1),0.0)
+
+    def test_stdtr(self):
+        assert_equal(cephes.stdtr(1,0),0.5)
+        assert_almost_equal(cephes.stdtr(1,1), 0.75)
+        assert_almost_equal(cephes.stdtr(1,2), 0.852416382349)
+
+    def test_stdtridf(self):
+        cephes.stdtridf(0.7,1)
+
+    def test_stdtrit(self):
+        cephes.stdtrit(1,0.7)
+
+    def test_struve(self):
+        assert_equal(cephes.struve(0,0),0.0)
+
+    def test_tandg(self):
+        assert_equal(cephes.tandg(45),1.0)
+
+    def test_tklmbda(self):
+        assert_almost_equal(cephes.tklmbda(1,1),1.0)
+
+    def test_y0(self):
+        cephes.y0(1)
+
+    def test_y1(self):
+        cephes.y1(1)
+
+    def test_yn(self):
+        cephes.yn(1,1)
+
+    def test_yv(self):
+        cephes.yv(1,1)
+
+    def test_yve(self):
+        cephes.yve(1,1)
+
+    def test_wofz(self):
+        z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.),
+             complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.),
+             complex(-0.0000000234545,1.1234), complex(-3.,5.1),
+             complex(-53,30.1), complex(0.0,0.12345),
+             complex(11,1), complex(-22,-2), complex(9,-28),
+             complex(21,-33), complex(1e5,1e5), complex(1e14,1e14)
+             ]
+        w = [
+            complex(-3.78270245518980507452677445620103199303131110e-7,
+                    0.000903861276433172057331093754199933411710053155),
+            complex(0.1764906227004816847297495349730234591778719532788,
+                    -0.02146550539468457616788719893991501311573031095617),
+            complex(0.2410250715772692146133539023007113781272362309451,
+                    0.06087579663428089745895459735240964093522265589350),
+            complex(0.30474420525691259245713884106959496013413834051768,
+                    -0.20821893820283162728743734725471561394145872072738),
+            complex(7.317131068972378096865595229600561710140617977e34,
+                    8.321873499714402777186848353320412813066170427e34),
+            complex(0.0615698507236323685519612934241429530190806818395,
+                    -0.00676005783716575013073036218018565206070072304635),
+            complex(0.3960793007699874918961319170187598400134746631,
+                    -5.593152259116644920546186222529802777409274656e-9),
+            complex(0.08217199226739447943295069917990417630675021771804,
+                    -0.04701291087643609891018366143118110965272615832184),
+            complex(0.00457246000350281640952328010227885008541748668738,
+                    -0.00804900791411691821818731763401840373998654987934),
+            complex(0.8746342859608052666092782112565360755791467973338452,
+                    0.),
+            complex(0.00468190164965444174367477874864366058339647648741,
+                    0.0510735563901306197993676329845149741675029197050),
+            complex(-0.0023193175200187620902125853834909543869428763219,
+                    -0.025460054739731556004902057663500272721780776336),
+            complex(9.11463368405637174660562096516414499772662584e304,
+                    3.97101807145263333769664875189354358563218932e305),
+            complex(-4.4927207857715598976165541011143706155432296e281,
+                    -2.8019591213423077494444700357168707775769028e281),
+            complex(2.820947917809305132678577516325951485807107151e-6,
+                    2.820947917668257736791638444590253942253354058e-6),
+            complex(2.82094791773878143474039725787438662716372268e-15,
+                    2.82094791773878143474039725773333923127678361e-15)
+        ]
+        assert_func_equal(cephes.wofz, w, z, rtol=1e-13)
+
+
+class TestAiry:
+    def test_airy(self):
+        # This tests the airy function to ensure 8 place accuracy in computation
+
+        x = special.airy(.99)
+        assert_array_almost_equal(
+            x,
+            array([0.13689066,-0.16050153,1.19815925,0.92046818]),
+            8,
+        )
+        x = special.airy(.41)
+        assert_array_almost_equal(
+            x,
+            array([0.25238916,-.23480512,0.80686202,0.51053919]),
+            8,
+        )
+        x = special.airy(-.36)
+        assert_array_almost_equal(
+            x,
+            array([0.44508477,-0.23186773,0.44939534,0.48105354]),
+            8,
+        )
+
+    def test_airye(self):
+        a = special.airye(0.01)
+        b = special.airy(0.01)
+        b1 = [None]*4
+        for n in range(2):
+            b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01))
+        for n in range(2,4):
+            b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01))))
+        assert_array_almost_equal(a,b1,6)
+
+    def test_bi_zeros(self):
+        bi = special.bi_zeros(2)
+        bia = (array([-1.17371322, -3.2710930]),
+               array([-2.29443968, -4.07315509]),
+               array([-0.45494438, 0.39652284]),
+               array([0.60195789, -0.76031014]))
+        assert_array_almost_equal(bi,bia,4)
+
+        bi = special.bi_zeros(5)
+        assert_array_almost_equal(bi[0],array([-1.173713222709127,
+                                               -3.271093302836352,
+                                               -4.830737841662016,
+                                               -6.169852128310251,
+                                               -7.376762079367764]),11)
+
+        assert_array_almost_equal(bi[1],array([-2.294439682614122,
+                                               -4.073155089071828,
+                                               -5.512395729663599,
+                                               -6.781294445990305,
+                                               -7.940178689168587]),10)
+
+        assert_array_almost_equal(bi[2],array([-0.454944383639657,
+                                               0.396522836094465,
+                                               -0.367969161486959,
+                                               0.349499116831805,
+                                               -0.336026240133662]),11)
+
+        assert_array_almost_equal(bi[3],array([0.601957887976239,
+                                               -0.760310141492801,
+                                               0.836991012619261,
+                                               -0.88947990142654,
+                                               0.929983638568022]),10)
+
+    def test_ai_zeros(self):
+        ai = special.ai_zeros(1)
+        assert_array_almost_equal(ai,(array([-2.33810741]),
+                                     array([-1.01879297]),
+                                     array([0.5357]),
+                                     array([0.7012])),4)
+
+    @pytest.mark.fail_slow(5)
+    def test_ai_zeros_big(self):
+        z, zp, ai_zpx, aip_zx = special.ai_zeros(50000)
+        ai_z, aip_z, _, _ = special.airy(z)
+        ai_zp, aip_zp, _, _ = special.airy(zp)
+
+        ai_envelope = 1/abs(z)**(1./4)
+        aip_envelope = abs(zp)**(1./4)
+
+        # Check values
+        assert_allclose(ai_zpx, ai_zp, rtol=1e-10)
+        assert_allclose(aip_zx, aip_z, rtol=1e-10)
+
+        # Check they are zeros
+        assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0)
+        assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0)
+
+        # Check first zeros, DLMF 9.9.1
+        assert_allclose(z[:6],
+            [-2.3381074105, -4.0879494441, -5.5205598281,
+             -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10)
+        assert_allclose(zp[:6],
+            [-1.0187929716, -3.2481975822, -4.8200992112,
+             -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10)
+
+    @pytest.mark.fail_slow(5)
+    def test_bi_zeros_big(self):
+        z, zp, bi_zpx, bip_zx = special.bi_zeros(50000)
+        _, _, bi_z, bip_z = special.airy(z)
+        _, _, bi_zp, bip_zp = special.airy(zp)
+
+        bi_envelope = 1/abs(z)**(1./4)
+        bip_envelope = abs(zp)**(1./4)
+
+        # Check values
+        assert_allclose(bi_zpx, bi_zp, rtol=1e-10)
+        assert_allclose(bip_zx, bip_z, rtol=1e-10)
+
+        # Check they are zeros
+        assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0)
+        assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0)
+
+        # Check first zeros, DLMF 9.9.2
+        assert_allclose(z[:6],
+            [-1.1737132227, -3.2710933028, -4.8307378417,
+             -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10)
+        assert_allclose(zp[:6],
+            [-2.2944396826, -4.0731550891, -5.5123957297,
+             -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10)
+
+
+class TestAssocLaguerre:
+    def test_assoc_laguerre(self):
+        a1 = special.genlaguerre(11,1)
+        a2 = special.assoc_laguerre(.2,11,1)
+        assert_array_almost_equal(a2,a1(.2),8)
+        a2 = special.assoc_laguerre(1,11,1)
+        assert_array_almost_equal(a2,a1(1),8)
+
+
+class TestBesselpoly:
+    def test_besselpoly(self):
+        pass
+
+
+class TestKelvin:
+    def test_bei(self):
+        mbei = special.bei(2)
+        assert_almost_equal(mbei, 0.9722916273066613,5)  # this may not be exact
+
+    def test_beip(self):
+        mbeip = special.beip(2)
+        assert_almost_equal(mbeip,0.91701361338403631,5)  # this may not be exact
+
+    def test_ber(self):
+        mber = special.ber(2)
+        assert_almost_equal(mber,0.75173418271380821,5)  # this may not be exact
+
+    def test_berp(self):
+        mberp = special.berp(2)
+        assert_almost_equal(mberp,-0.49306712470943909,5)  # this may not be exact
+
+    def test_bei_zeros(self):
+        # Abramowitz & Stegun, Table 9.12
+        bi = special.bei_zeros(5)
+        assert_array_almost_equal(bi,array([5.02622,
+                                            9.45541,
+                                            13.89349,
+                                            18.33398,
+                                            22.77544]),4)
+
+    def test_beip_zeros(self):
+        bip = special.beip_zeros(5)
+        assert_array_almost_equal(bip,array([3.772673304934953,
+                                               8.280987849760042,
+                                               12.742147523633703,
+                                               17.193431752512542,
+                                               21.641143941167325]),8)
+
+    def test_ber_zeros(self):
+        ber = special.ber_zeros(5)
+        assert_array_almost_equal(ber,array([2.84892,
+                                             7.23883,
+                                             11.67396,
+                                             16.11356,
+                                             20.55463]),4)
+
+    def test_berp_zeros(self):
+        brp = special.berp_zeros(5)
+        assert_array_almost_equal(brp,array([6.03871,
+                                             10.51364,
+                                             14.96844,
+                                             19.41758,
+                                             23.86430]),4)
+
+    def test_kelvin(self):
+        mkelv = special.kelvin(2)
+        assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j,
+                                         special.ker(2) + special.kei(2)*1j,
+                                         special.berp(2) + special.beip(2)*1j,
+                                         special.kerp(2) + special.keip(2)*1j),8)
+
+    def test_kei(self):
+        mkei = special.kei(2)
+        assert_almost_equal(mkei,-0.20240006776470432,5)
+
+    def test_keip(self):
+        mkeip = special.keip(2)
+        assert_almost_equal(mkeip,0.21980790991960536,5)
+
+    def test_ker(self):
+        mker = special.ker(2)
+        assert_almost_equal(mker,-0.041664513991509472,5)
+
+    def test_kerp(self):
+        mkerp = special.kerp(2)
+        assert_almost_equal(mkerp,-0.10660096588105264,5)
+
+    def test_kei_zeros(self):
+        kei = special.kei_zeros(5)
+        assert_array_almost_equal(kei,array([3.91467,
+                                              8.34422,
+                                              12.78256,
+                                              17.22314,
+                                              21.66464]),4)
+
+    def test_keip_zeros(self):
+        keip = special.keip_zeros(5)
+        assert_array_almost_equal(keip,array([4.93181,
+                                                9.40405,
+                                                13.85827,
+                                                18.30717,
+                                                22.75379]),4)
+
+    # numbers come from 9.9 of A&S pg. 381
+    def test_kelvin_zeros(self):
+        tmp = special.kelvin_zeros(5)
+        berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp
+        assert_array_almost_equal(berz,array([2.84892,
+                                               7.23883,
+                                               11.67396,
+                                               16.11356,
+                                               20.55463]),4)
+        assert_array_almost_equal(beiz,array([5.02622,
+                                               9.45541,
+                                               13.89349,
+                                               18.33398,
+                                               22.77544]),4)
+        assert_array_almost_equal(kerz,array([1.71854,
+                                               6.12728,
+                                               10.56294,
+                                               15.00269,
+                                               19.44382]),4)
+        assert_array_almost_equal(keiz,array([3.91467,
+                                               8.34422,
+                                               12.78256,
+                                               17.22314,
+                                               21.66464]),4)
+        assert_array_almost_equal(berpz,array([6.03871,
+                                                10.51364,
+                                                14.96844,
+                                                19.41758,
+                                                23.86430]),4)
+        assert_array_almost_equal(beipz,array([3.77267,
+                 # table from 1927 had 3.77320
+                 #  but this is more accurate
+                                                8.28099,
+                                                12.74215,
+                                                17.19343,
+                                                21.64114]),4)
+        assert_array_almost_equal(kerpz,array([2.66584,
+                                                7.17212,
+                                                11.63218,
+                                                16.08312,
+                                                20.53068]),4)
+        assert_array_almost_equal(keipz,array([4.93181,
+                                                9.40405,
+                                                13.85827,
+                                                18.30717,
+                                                22.75379]),4)
+
+    def test_ker_zeros(self):
+        ker = special.ker_zeros(5)
+        assert_array_almost_equal(ker,array([1.71854,
+                                               6.12728,
+                                               10.56294,
+                                               15.00269,
+                                               19.44381]),4)
+
+    def test_kerp_zeros(self):
+        kerp = special.kerp_zeros(5)
+        assert_array_almost_equal(kerp,array([2.66584,
+                                                7.17212,
+                                                11.63218,
+                                                16.08312,
+                                                20.53068]),4)
+
+
+class TestBernoulli:
+    def test_bernoulli(self):
+        brn = special.bernoulli(5)
+        assert_array_almost_equal(brn,array([1.0000,
+                                             -0.5000,
+                                             0.1667,
+                                             0.0000,
+                                             -0.0333,
+                                             0.0000]),4)
+
+
+class TestBeta:
+    """
+    Test beta and betaln.
+    """
+
+    def test_beta(self):
+        assert_equal(special.beta(1, 1), 1.0)
+        assert_allclose(special.beta(-100.3, 1e-200), special.gamma(1e-200))
+        assert_allclose(special.beta(0.0342, 171), 24.070498359873497,
+                        rtol=1e-13, atol=0)
+
+        bet = special.beta(2, 4)
+        betg = (special.gamma(2)*special.gamma(4))/special.gamma(6)
+        assert_allclose(bet, betg, rtol=1e-13)
+
+    def test_beta_inf(self):
+        assert_(np.isinf(special.beta(-1, 2)))
+
+    def test_betaln(self):
+        assert_equal(special.betaln(1, 1), 0.0)
+        assert_allclose(special.betaln(-100.3, 1e-200),
+                        special.gammaln(1e-200))
+        assert_allclose(special.betaln(0.0342, 170), 3.1811881124242447,
+                        rtol=1e-14, atol=0)
+
+        betln = special.betaln(2, 4)
+        bet = log(abs(special.beta(2, 4)))
+        assert_allclose(betln, bet, rtol=1e-13)
+
+
+class TestBetaInc:
+    """
+    Tests for betainc, betaincinv, betaincc, betainccinv.
+    """
+
+    def test_a1_b1(self):
+        # betainc(1, 1, x) is x.
+        x = np.array([0, 0.25, 1])
+        assert_equal(special.betainc(1, 1, x), x)
+        assert_equal(special.betaincinv(1, 1, x), x)
+        assert_equal(special.betaincc(1, 1, x), 1 - x)
+        assert_equal(special.betainccinv(1, 1, x), 1 - x)
+
+    # Nontrivial expected values computed with mpmath:
+    #    from mpmath import mp
+    #    mp.dps = 100
+    #    p = mp.betainc(a, b, 0, x, regularized=True)
+    #
+    # or, e.g.,
+    #
+    #    p = 0.25
+    #    a, b = 0.0342, 171
+    #    x = mp.findroot(
+    #        lambda t: mp.betainc(a, b, 0, t, regularized=True) - p,
+    #        (8e-21, 9e-21),
+    #        solver='anderson',
+    #    )
+    #
+    @pytest.mark.parametrize(
+        'a, b, x, p',
+        [(2, 4, 0.3138101704556974, 0.5),
+         (0.0342, 171.0, 1e-10, 0.552699169018070910641),
+         # gh-3761:
+         (0.0342, 171, 8.42313169354797e-21, 0.25),
+         # gh-4244:
+         (0.0002742794749792665, 289206.03125, 1.639984034231756e-56,
+          0.9688708782196045),
+         # gh-12796:
+         (4, 99997, 0.0001947841578892121, 0.999995)])
+    def test_betainc_betaincinv(self, a, b, x, p):
+        p1 = special.betainc(a, b, x)
+        assert_allclose(p1, p, rtol=1e-15)
+        x1 = special.betaincinv(a, b, p)
+        assert_allclose(x1, x, rtol=5e-13)
+
+    # Expected values computed with mpmath:
+    #     from mpmath import mp
+    #     mp.dps = 100
+    #     p = mp.betainc(a, b, x, 1, regularized=True)
+    @pytest.mark.parametrize('a, b, x, p',
+                             [(2.5, 3.0, 0.25, 0.833251953125),
+                              (7.5, 13.25, 0.375, 0.43298734645560368593),
+                              (0.125, 7.5, 0.425, 0.0006688257851314237),
+                              (0.125, 18.0, 1e-6, 0.72982359145096327654),
+                              (0.125, 18.0, 0.996, 7.2745875538380150586e-46),
+                              (0.125, 24.0, 0.75, 3.70853404816862016966e-17),
+                              (16.0, 0.75, 0.99999999975,
+                               5.4408759277418629909e-07),
+                              # gh-4677 (numbers from stackoverflow question):
+                              (0.4211959643503401, 16939.046996018118,
+                               0.000815296167195521, 1e-7)])
+    def test_betaincc_betainccinv(self, a, b, x, p):
+        p1 = special.betaincc(a, b, x)
+        assert_allclose(p1, p, rtol=5e-15)
+        x1 = special.betainccinv(a, b, p)
+        assert_allclose(x1, x, rtol=8e-15)
+
+    @pytest.mark.parametrize(
+        'a, b, y, ref',
+        [(14.208308325339239, 14.208308325339239, 7.703145458496392e-307,
+          8.566004561846704e-23),
+         (14.0, 14.5, 1e-280, 2.9343915006642424e-21),
+         (3.5, 15.0, 4e-95, 1.3290751429289227e-28),
+         (10.0, 1.25, 2e-234, 3.982659092143654e-24),
+         (4.0, 99997.0, 5e-88, 3.309800566862242e-27)]
+    )
+    def test_betaincinv_tiny_y(self, a, b, y, ref):
+        # Test with extremely small y values.  This test includes
+        # a regression test for an issue in the boost code;
+        # see https://github.com/boostorg/math/issues/961
+        #
+        # The reference values were computed with mpmath. For example,
+        #
+        #   from mpmath import mp
+        #   mp.dps = 1000
+        #   a = 14.208308325339239
+        #   p = 7.703145458496392e-307
+        #   x = mp.findroot(lambda t: mp.betainc(a, a, 0, t,
+        #                                        regularized=True) - p,
+        #                   x0=8.566e-23)
+        #   print(float(x))
+        #
+        x = special.betaincinv(a, b, y)
+        assert_allclose(x, ref, rtol=1e-14)
+
+    @pytest.mark.parametrize('func', [special.betainc, special.betaincinv,
+                                      special.betaincc, special.betainccinv])
+    @pytest.mark.parametrize('args', [(-1.0, 2, 0.5), (0, 2, 0.5),
+                                      (1.5, -2.0, 0.5), (1.5, 0, 0.5),
+                                      (1.5, 2.0, -0.3), (1.5, 2.0, 1.1)])
+    def test_betainc_domain_errors(self, func, args):
+        with special.errstate(domain='raise'):
+            with pytest.raises(special.SpecialFunctionError, match='domain'):
+                special.betainc(*args)
+
+    @pytest.mark.parametrize('dtype', [np.float32, np.float64])
+    def test_gh21426(self, dtype):
+        # Test for gh-21426: betaincinv must not return NaN
+        a = np.array([5.], dtype=dtype)
+        x = np.array([0.5], dtype=dtype)
+        result = special.betaincinv(a, a, x)
+        assert_allclose(result, x, rtol=10 * np.finfo(dtype).eps)
+
+
+class TestCombinatorics:
+    def test_comb(self):
+        assert_allclose(special.comb([10, 10], [3, 4]), [120., 210.])
+        assert_allclose(special.comb(10, 3), 120.)
+        assert_equal(special.comb(10, 3, exact=True), 120)
+        assert_equal(special.comb(10, 3, exact=True, repetition=True), 220)
+
+        assert_allclose([special.comb(20, k, exact=True) for k in range(21)],
+                        special.comb(20, list(range(21))), atol=1e-15)
+
+        ii = np.iinfo(int).max + 1
+        assert_equal(special.comb(ii, ii-1, exact=True), ii)
+
+        expected = 100891344545564193334812497256
+        assert special.comb(100, 50, exact=True) == expected
+
+    def test_comb_with_np_int64(self):
+        n = 70
+        k = 30
+        np_n = np.int64(n)
+        np_k = np.int64(k)
+        res_np = special.comb(np_n, np_k, exact=True)
+        res_py = special.comb(n, k, exact=True)
+        assert res_np == res_py
+
+    def test_comb_zeros(self):
+        assert_equal(special.comb(2, 3, exact=True), 0)
+        assert_equal(special.comb(-1, 3, exact=True), 0)
+        assert_equal(special.comb(2, -1, exact=True), 0)
+        assert_equal(special.comb(2, -1, exact=False), 0)
+        assert_allclose(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.])
+
+    @pytest.mark.thread_unsafe
+    def test_comb_exact_non_int_dep(self):
+        msg = "`exact=True`"
+        with pytest.deprecated_call(match=msg):
+            special.comb(3.4, 4, exact=True)
+
+    def test_perm(self):
+        assert_allclose(special.perm([10, 10], [3, 4]), [720., 5040.])
+        assert_almost_equal(special.perm(10, 3), 720.)
+        assert_equal(special.perm(10, 3, exact=True), 720)
+
+    def test_perm_zeros(self):
+        assert_equal(special.perm(2, 3, exact=True), 0)
+        assert_equal(special.perm(-1, 3, exact=True), 0)
+        assert_equal(special.perm(2, -1, exact=True), 0)
+        assert_equal(special.perm(2, -1, exact=False), 0)
+        assert_allclose(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.])
+
+    @pytest.mark.thread_unsafe
+    def test_perm_iv(self):
+        # currently `exact=True` only support scalars
+        with pytest.raises(ValueError, match="scalar integers"):
+            special.perm([1, 2], [4, 5], exact=True)
+
+        # Non-integral scalars with N < k, or N,k < 0 used to return 0, this is now
+        # deprecated and will raise an error in SciPy 1.16.0
+        with pytest.deprecated_call(match="Non-integer"):
+            special.perm(4.6, 6, exact=True)
+        with pytest.deprecated_call(match="Non-integer"):
+            special.perm(-4.6, 3, exact=True)
+        with pytest.deprecated_call(match="Non-integer"):
+            special.perm(4, -3.9, exact=True)
+
+        # Non-integral scalars which aren't included in the cases above an raise an
+        # error directly without deprecation as this code never worked
+        with pytest.raises(ValueError, match="Non-integer"):
+            special.perm(6.0, 4.6, exact=True)
+
+
+class TestTrigonometric:
+    def test_cbrt(self):
+        cb = special.cbrt(27)
+        cbrl = 27**(1.0/3.0)
+        assert_approx_equal(cb,cbrl)
+
+    def test_cbrtmore(self):
+        cb1 = special.cbrt(27.9)
+        cbrl1 = 27.9**(1.0/3.0)
+        assert_almost_equal(cb1,cbrl1,8)
+
+    def test_cosdg(self):
+        cdg = special.cosdg(90)
+        cdgrl = cos(pi/2.0)
+        assert_almost_equal(cdg,cdgrl,8)
+
+    def test_cosdgmore(self):
+        cdgm = special.cosdg(30)
+        cdgmrl = cos(pi/6.0)
+        assert_almost_equal(cdgm,cdgmrl,8)
+
+    def test_cosm1(self):
+        cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10))
+        csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1)
+        assert_array_almost_equal(cs,csrl,8)
+
+    def test_cotdg(self):
+        ct = special.cotdg(30)
+        ctrl = tan(pi/6.0)**(-1)
+        assert_almost_equal(ct,ctrl,8)
+
+    def test_cotdgmore(self):
+        ct1 = special.cotdg(45)
+        ctrl1 = tan(pi/4.0)**(-1)
+        assert_almost_equal(ct1,ctrl1,8)
+
+    def test_specialpoints(self):
+        assert_almost_equal(special.cotdg(45), 1.0, 14)
+        assert_almost_equal(special.cotdg(-45), -1.0, 14)
+        assert_almost_equal(special.cotdg(90), 0.0, 14)
+        assert_almost_equal(special.cotdg(-90), 0.0, 14)
+        assert_almost_equal(special.cotdg(135), -1.0, 14)
+        assert_almost_equal(special.cotdg(-135), 1.0, 14)
+        assert_almost_equal(special.cotdg(225), 1.0, 14)
+        assert_almost_equal(special.cotdg(-225), -1.0, 14)
+        assert_almost_equal(special.cotdg(270), 0.0, 14)
+        assert_almost_equal(special.cotdg(-270), 0.0, 14)
+        assert_almost_equal(special.cotdg(315), -1.0, 14)
+        assert_almost_equal(special.cotdg(-315), 1.0, 14)
+        assert_almost_equal(special.cotdg(765), 1.0, 14)
+
+    def test_sinc(self):
+        # the sinc implementation and more extensive sinc tests are in numpy
+        assert_array_equal(special.sinc([0]), 1)
+        assert_equal(special.sinc(0.0), 1.0)
+
+    def test_sindg(self):
+        sn = special.sindg(90)
+        assert_equal(sn,1.0)
+
+    def test_sindgmore(self):
+        snm = special.sindg(30)
+        snmrl = sin(pi/6.0)
+        assert_almost_equal(snm,snmrl,8)
+        snm1 = special.sindg(45)
+        snmrl1 = sin(pi/4.0)
+        assert_almost_equal(snm1,snmrl1,8)
+
+
+class TestTandg:
+
+    def test_tandg(self):
+        tn = special.tandg(30)
+        tnrl = tan(pi/6.0)
+        assert_almost_equal(tn,tnrl,8)
+
+    def test_tandgmore(self):
+        tnm = special.tandg(45)
+        tnmrl = tan(pi/4.0)
+        assert_almost_equal(tnm,tnmrl,8)
+        tnm1 = special.tandg(60)
+        tnmrl1 = tan(pi/3.0)
+        assert_almost_equal(tnm1,tnmrl1,8)
+
+    def test_specialpoints(self):
+        assert_almost_equal(special.tandg(0), 0.0, 14)
+        assert_almost_equal(special.tandg(45), 1.0, 14)
+        assert_almost_equal(special.tandg(-45), -1.0, 14)
+        assert_almost_equal(special.tandg(135), -1.0, 14)
+        assert_almost_equal(special.tandg(-135), 1.0, 14)
+        assert_almost_equal(special.tandg(180), 0.0, 14)
+        assert_almost_equal(special.tandg(-180), 0.0, 14)
+        assert_almost_equal(special.tandg(225), 1.0, 14)
+        assert_almost_equal(special.tandg(-225), -1.0, 14)
+        assert_almost_equal(special.tandg(315), -1.0, 14)
+        assert_almost_equal(special.tandg(-315), 1.0, 14)
+
+
+class TestEllip:
+    def test_ellipj_nan(self):
+        """Regression test for #912."""
+        special.ellipj(0.5, np.nan)
+
+    def test_ellipj(self):
+        el = special.ellipj(0.2,0)
+        rel = [sin(0.2),cos(0.2),1.0,0.20]
+        assert_array_almost_equal(el,rel,13)
+
+    def test_ellipk(self):
+        elk = special.ellipk(.2)
+        assert_almost_equal(elk,1.659623598610528,11)
+
+        assert_equal(special.ellipkm1(0.0), np.inf)
+        assert_equal(special.ellipkm1(1.0), pi/2)
+        assert_equal(special.ellipkm1(np.inf), 0.0)
+        assert_equal(special.ellipkm1(np.nan), np.nan)
+        assert_equal(special.ellipkm1(-1), np.nan)
+        assert_allclose(special.ellipk(-10), 0.7908718902387385)
+
+    def test_ellipkinc(self):
+        elkinc = special.ellipkinc(pi/2,.2)
+        elk = special.ellipk(0.2)
+        assert_almost_equal(elkinc,elk,15)
+        alpha = 20*pi/180
+        phi = 45*pi/180
+        m = sin(alpha)**2
+        elkinc = special.ellipkinc(phi,m)
+        assert_almost_equal(elkinc,0.79398143,8)
+        # From pg. 614 of A & S
+
+        assert_equal(special.ellipkinc(pi/2, 0.0), pi/2)
+        assert_equal(special.ellipkinc(pi/2, 1.0), np.inf)
+        assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0)
+        assert_equal(special.ellipkinc(pi/2, np.nan), np.nan)
+        assert_equal(special.ellipkinc(pi/2, 2), np.nan)
+        assert_equal(special.ellipkinc(0, 0.5), 0.0)
+        assert_equal(special.ellipkinc(np.inf, 0.5), np.inf)
+        assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf)
+        assert_equal(special.ellipkinc(np.inf, np.inf), np.nan)
+        assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan)
+        assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan)
+        assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan)
+        assert_equal(special.ellipkinc(np.nan, 0.5), np.nan)
+        assert_equal(special.ellipkinc(np.nan, np.nan), np.nan)
+
+        assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14)
+        assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946)
+
+    def test_ellipkinc_2(self):
+        # Regression test for gh-3550
+        # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value
+        mbad = 0.68359375000000011
+        phi = 0.9272952180016123
+        m = np.nextafter(mbad, 0)
+        mvals = []
+        for j in range(10):
+            mvals.append(m)
+            m = np.nextafter(m, 1)
+        f = special.ellipkinc(phi, mvals)
+        assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1)
+        # this bug also appears at phi + n * pi for at least small n
+        f1 = special.ellipkinc(phi + pi, mvals)
+        assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2)
+
+    def test_ellipkinc_singular(self):
+        # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2)
+        xlog = np.logspace(-300, -17, 25)
+        xlin = np.linspace(1e-17, 0.1, 25)
+        xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False)
+
+        assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)),
+                        rtol=1e14)
+        assert_equal(special.ellipkinc(np.pi/2, 1), np.inf)
+        assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)),
+                        rtol=1e14)
+        assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf)
+
+    def test_ellipe(self):
+        ele = special.ellipe(.2)
+        assert_almost_equal(ele,1.4890350580958529,8)
+
+        assert_equal(special.ellipe(0.0), pi/2)
+        assert_equal(special.ellipe(1.0), 1.0)
+        assert_equal(special.ellipe(-np.inf), np.inf)
+        assert_equal(special.ellipe(np.nan), np.nan)
+        assert_equal(special.ellipe(2), np.nan)
+        assert_allclose(special.ellipe(-10), 3.6391380384177689)
+
+    def test_ellipeinc(self):
+        eleinc = special.ellipeinc(pi/2,.2)
+        ele = special.ellipe(0.2)
+        assert_almost_equal(eleinc,ele,14)
+        # pg 617 of A & S
+        alpha, phi = 52*pi/180,35*pi/180
+        m = sin(alpha)**2
+        eleinc = special.ellipeinc(phi,m)
+        assert_almost_equal(eleinc, 0.58823065, 8)
+
+        assert_equal(special.ellipeinc(pi/2, 0.0), pi/2)
+        assert_equal(special.ellipeinc(pi/2, 1.0), 1.0)
+        assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf)
+        assert_equal(special.ellipeinc(pi/2, np.nan), np.nan)
+        assert_equal(special.ellipeinc(pi/2, 2), np.nan)
+        assert_equal(special.ellipeinc(0, 0.5), 0.0)
+        assert_equal(special.ellipeinc(np.inf, 0.5), np.inf)
+        assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf)
+        assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf)
+        assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf)
+        assert_equal(special.ellipeinc(np.inf, np.inf), np.nan)
+        assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan)
+        assert_equal(special.ellipeinc(np.nan, 0.5), np.nan)
+        assert_equal(special.ellipeinc(np.nan, np.nan), np.nan)
+        assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876)
+
+    def test_ellipeinc_2(self):
+        # Regression test for gh-3550
+        # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value
+        mbad = 0.68359375000000011
+        phi = 0.9272952180016123
+        m = np.nextafter(mbad, 0)
+        mvals = []
+        for j in range(10):
+            mvals.append(m)
+            m = np.nextafter(m, 1)
+        f = special.ellipeinc(phi, mvals)
+        assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2)
+        # this bug also appears at phi + n * pi for at least small n
+        f1 = special.ellipeinc(phi + pi, mvals)
+        assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4)
+
+
+class TestEllipCarlson:
+    """Test for Carlson elliptic integrals ellipr[cdfgj].
+    The special values used in these tests can be found in Sec. 3 of Carlson
+    (1994), https://arxiv.org/abs/math/9409227
+    """
+    def test_elliprc(self):
+        assert_allclose(elliprc(1, 1), 1)
+        assert elliprc(1, inf) == 0.0
+        assert isnan(elliprc(1, 0))
+        assert elliprc(1, complex(1, inf)) == 0.0
+        args = array([[0.0, 0.25],
+                      [2.25, 2.0],
+                      [0.0, 1.0j],
+                      [-1.0j, 1.0j],
+                      [0.25, -2.0],
+                      [1.0j, -1.0]])
+        expected_results = array([np.pi,
+                                  np.log(2.0),
+                                  1.1107207345396 * (1.0-1.0j),
+                                  1.2260849569072-0.34471136988768j,
+                                  np.log(2.0) / 3.0,
+                                  0.77778596920447+0.19832484993429j])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprc(*arr), expected_results[i])
+
+    def test_elliprd(self):
+        assert_allclose(elliprd(1, 1, 1), 1)
+        assert_allclose(elliprd(0, 2, 1) / 3.0, 0.59907011736779610371)
+        assert elliprd(1, 1, inf) == 0.0
+        assert np.isinf(elliprd(1, 1, 0))
+        assert np.isinf(elliprd(1, 1, complex(0, 0)))
+        assert np.isinf(elliprd(0, 1, complex(0, 0)))
+        assert isnan(elliprd(1, 1, -np.finfo(np.float64).tiny / 2.0))
+        assert isnan(elliprd(1, 1, complex(-1, 0)))
+        args = array([[0.0, 2.0, 1.0],
+                      [2.0, 3.0, 4.0],
+                      [1.0j, -1.0j, 2.0],
+                      [0.0, 1.0j, -1.0j],
+                      [0.0, -1.0+1.0j, 1.0j],
+                      [-2.0-1.0j, -1.0j, -1.0+1.0j]])
+        expected_results = array([1.7972103521034,
+                                  0.16510527294261,
+                                  0.65933854154220,
+                                  1.2708196271910+2.7811120159521j,
+                                  -1.8577235439239-0.96193450888839j,
+                                  1.8249027393704-1.2218475784827j])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprd(*arr), expected_results[i])
+
+    def test_elliprf(self):
+        assert_allclose(elliprf(1, 1, 1), 1)
+        assert_allclose(elliprf(0, 1, 2), 1.31102877714605990523)
+        assert elliprf(1, inf, 1) == 0.0
+        assert np.isinf(elliprf(0, 1, 0))
+        assert isnan(elliprf(1, 1, -1))
+        assert elliprf(complex(inf), 0, 1) == 0.0
+        assert isnan(elliprf(1, 1, complex(-inf, 1)))
+        args = array([[1.0, 2.0, 0.0],
+                      [1.0j, -1.0j, 0.0],
+                      [0.5, 1.0, 0.0],
+                      [-1.0+1.0j, 1.0j, 0.0],
+                      [2.0, 3.0, 4.0],
+                      [1.0j, -1.0j, 2.0],
+                      [-1.0+1.0j, 1.0j, 1.0-1.0j]])
+        expected_results = array([1.3110287771461,
+                                  1.8540746773014,
+                                  1.8540746773014,
+                                  0.79612586584234-1.2138566698365j,
+                                  0.58408284167715,
+                                  1.0441445654064,
+                                  0.93912050218619-0.53296252018635j])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprf(*arr), expected_results[i])
+
+    def test_elliprg(self):
+        assert_allclose(elliprg(1, 1, 1), 1)
+        assert_allclose(elliprg(0, 0, 1), 0.5)
+        assert_allclose(elliprg(0, 0, 0), 0)
+        assert np.isinf(elliprg(1, inf, 1))
+        assert np.isinf(elliprg(complex(inf), 1, 1))
+        args = array([[0.0, 16.0, 16.0],
+                      [2.0, 3.0, 4.0],
+                      [0.0, 1.0j, -1.0j],
+                      [-1.0+1.0j, 1.0j, 0.0],
+                      [-1.0j, -1.0+1.0j, 1.0j],
+                      [0.0, 0.0796, 4.0]])
+        expected_results = array([np.pi,
+                                  1.7255030280692,
+                                  0.42360654239699,
+                                  0.44660591677018+0.70768352357515j,
+                                  0.36023392184473+0.40348623401722j,
+                                  1.0284758090288])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprg(*arr), expected_results[i])
+
+    def test_elliprj(self):
+        assert_allclose(elliprj(1, 1, 1, 1), 1)
+        assert elliprj(1, 1, inf, 1) == 0.0
+        assert isnan(elliprj(1, 0, 0, 0))
+        assert isnan(elliprj(-1, 1, 1, 1))
+        assert elliprj(1, 1, 1, inf) == 0.0
+        args = array([[0.0, 1.0, 2.0, 3.0],
+                      [2.0, 3.0, 4.0, 5.0],
+                      [2.0, 3.0, 4.0, -1.0+1.0j],
+                      [1.0j, -1.0j, 0.0, 2.0],
+                      [-1.0+1.0j, -1.0-1.0j, 1.0, 2.0],
+                      [1.0j, -1.0j, 0.0, 1.0-1.0j],
+                      [-1.0+1.0j, -1.0-1.0j, 1.0, -3.0+1.0j],
+                      [2.0, 3.0, 4.0, -0.5],    # Cauchy principal value
+                      [2.0, 3.0, 4.0, -5.0]])   # Cauchy principal value
+        expected_results = array([0.77688623778582,
+                                  0.14297579667157,
+                                  0.13613945827771-0.38207561624427j,
+                                  1.6490011662711,
+                                  0.94148358841220,
+                                  1.8260115229009+1.2290661908643j,
+                                  -0.61127970812028-1.0684038390007j,
+                                  0.24723819703052,    # Cauchy principal value
+                                  -0.12711230042964])  # Caucny principal value
+        for i, arr in enumerate(args):
+            assert_allclose(elliprj(*arr), expected_results[i])
+
+    @pytest.mark.xfail(reason="Insufficient accuracy on 32-bit")
+    def test_elliprj_hard(self):
+        assert_allclose(elliprj(6.483625725195452e-08,
+                                1.1649136528196886e-27,
+                                3.6767340167168e+13,
+                                0.493704617023468),
+                        8.63426920644241857617477551054e-6,
+                        rtol=5e-15, atol=1e-20)
+        assert_allclose(elliprj(14.375105857849121,
+                                9.993988969725365e-11,
+                                1.72844262269944e-26,
+                                5.898871222598245e-06),
+                        829774.1424801627252574054378691828,
+                        rtol=5e-15, atol=1e-20)
+
+
+class TestEllipLegendreCarlsonIdentities:
+    """Test identities expressing the Legendre elliptic integrals in terms
+    of Carlson's symmetric integrals.  These identities can be found
+    in the DLMF https://dlmf.nist.gov/19.25#i .
+    """
+
+    def setup_class(self):
+        self.m_n1_1 = np.arange(-1., 1., 0.01)
+        # For double, this is -(2**1024)
+        self.max_neg = finfo(double).min
+        # Lots of very negative numbers
+        self.very_neg_m = -1. * 2.**arange(-1 +
+                                           np.log2(-self.max_neg), 0.,
+                                           -1.)
+        self.ms_up_to_1 = np.concatenate(([self.max_neg],
+                                          self.very_neg_m,
+                                          self.m_n1_1))
+
+    def test_k(self):
+        """Test identity:
+        K(m) = R_F(0, 1-m, 1)
+        """
+        m = self.ms_up_to_1
+        assert_allclose(ellipk(m), elliprf(0., 1.-m, 1.))
+
+    def test_km1(self):
+        """Test identity:
+        K(m) = R_F(0, 1-m, 1)
+        But with the ellipkm1 function
+        """
+        # For double, this is 2**-1022
+        tiny = finfo(double).tiny
+        # All these small powers of 2, up to 2**-1
+        m1 = tiny * 2.**arange(0., -np.log2(tiny))
+        assert_allclose(ellipkm1(m1), elliprf(0., m1, 1.))
+
+    def test_e(self):
+        """Test identity:
+        E(m) = 2*R_G(0, 1-k^2, 1)
+        """
+        m = self.ms_up_to_1
+        assert_allclose(ellipe(m), 2.*elliprg(0., 1.-m, 1.))
+
+
+class TestErf:
+
+    def test_erf(self):
+        er = special.erf(.25)
+        assert_almost_equal(er,0.2763263902,8)
+
+    def test_erf_zeros(self):
+        erz = special.erf_zeros(5)
+        erzr = array([1.45061616+1.88094300j,
+                     2.24465928+2.61657514j,
+                     2.83974105+3.17562810j,
+                     3.33546074+3.64617438j,
+                     3.76900557+4.06069723j])
+        assert_array_almost_equal(erz,erzr,4)
+
+    def _check_variant_func(self, func, other_func, rtol, atol=0):
+        rng = np.random.RandomState(1234)
+        n = 10000
+        x = rng.pareto(0.02, n) * (2*rng.randint(0, 2, n) - 1)
+        y = rng.pareto(0.02, n) * (2*rng.randint(0, 2, n) - 1)
+        z = x + 1j*y
+
+        with np.errstate(all='ignore'):
+            w = other_func(z)
+            w_real = other_func(x).real
+
+            mask = np.isfinite(w)
+            w = w[mask]
+            z = z[mask]
+
+            mask = np.isfinite(w_real)
+            w_real = w_real[mask]
+            x = x[mask]
+
+            # test both real and complex variants
+            assert_func_equal(func, w, z, rtol=rtol, atol=atol)
+            assert_func_equal(func, w_real, x, rtol=rtol, atol=atol)
+
+    def test_erfc_consistent(self):
+        self._check_variant_func(
+            cephes.erfc,
+            lambda z: 1 - cephes.erf(z),
+            rtol=1e-12,
+            atol=1e-14  # <- the test function loses precision
+            )
+
+    def test_erfcx_consistent(self):
+        self._check_variant_func(
+            cephes.erfcx,
+            lambda z: np.exp(z*z) * cephes.erfc(z),
+            rtol=1e-12
+            )
+
+    def test_erfi_consistent(self):
+        self._check_variant_func(
+            cephes.erfi,
+            lambda z: -1j * cephes.erf(1j*z),
+            rtol=1e-12
+            )
+
+    def test_dawsn_consistent(self):
+        self._check_variant_func(
+            cephes.dawsn,
+            lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z),
+            rtol=1e-12
+            )
+
+    def test_erf_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, -1, 1]
+        assert_allclose(special.erf(vals), expected, rtol=1e-15)
+
+    def test_erfc_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, 2, 0]
+        assert_allclose(special.erfc(vals), expected, rtol=1e-15)
+
+    def test_erfcx_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, np.inf, 0]
+        assert_allclose(special.erfcx(vals), expected, rtol=1e-15)
+
+    def test_erfi_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, -np.inf, np.inf]
+        assert_allclose(special.erfi(vals), expected, rtol=1e-15)
+
+    def test_dawsn_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, -0.0, 0.0]
+        assert_allclose(special.dawsn(vals), expected, rtol=1e-15)
+
+    def test_wofz_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j]
+        assert_allclose(special.wofz(vals), expected, rtol=1e-15)
+
+
+class TestEuler:
+    def test_euler(self):
+        eu0 = special.euler(0)
+        eu1 = special.euler(1)
+        eu2 = special.euler(2)   # just checking segfaults
+        assert_allclose(eu0, [1], rtol=1e-15)
+        assert_allclose(eu1, [1, 0], rtol=1e-15)
+        assert_allclose(eu2, [1, 0, -1], rtol=1e-15)
+        eu24 = special.euler(24)
+        mathworld = [1,1,5,61,1385,50521,2702765,199360981,
+                     19391512145,2404879675441,
+                     370371188237525,69348874393137901,
+                     15514534163557086905]
+        correct = zeros((25,),'d')
+        for k in range(0,13):
+            if (k % 2):
+                correct[2*k] = -float(mathworld[k])
+            else:
+                correct[2*k] = float(mathworld[k])
+        with np.errstate(all='ignore'):
+            err = nan_to_num((eu24-correct)/correct)
+            errmax = max(err)
+        assert_almost_equal(errmax, 0.0, 14)
+
+
+class TestExp:
+    def test_exp2(self):
+        ex = special.exp2(2)
+        exrl = 2**2
+        assert_equal(ex,exrl)
+
+    def test_exp2more(self):
+        exm = special.exp2(2.5)
+        exmrl = 2**(2.5)
+        assert_almost_equal(exm,exmrl,8)
+
+    def test_exp10(self):
+        ex = special.exp10(2)
+        exrl = 10**2
+        assert_approx_equal(ex,exrl)
+
+    def test_exp10more(self):
+        exm = special.exp10(2.5)
+        exmrl = 10**(2.5)
+        assert_almost_equal(exm,exmrl,8)
+
+    def test_expm1(self):
+        ex = (special.expm1(2),special.expm1(3),special.expm1(4))
+        exrl = (exp(2)-1,exp(3)-1,exp(4)-1)
+        assert_array_almost_equal(ex,exrl,8)
+
+    def test_expm1more(self):
+        ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2))
+        exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1)
+        assert_array_almost_equal(ex1,exrl1,8)
+
+
+def assert_really_equal(x, y, rtol=None):
+    """
+    Sharper assertion function that is stricter about matching types, not just values
+
+    This is useful/necessary in some cases:
+      * dtypes for arrays that have the same _values_ (e.g. element 1.0 vs 1)
+      * distinguishing complex from real NaN
+      * result types for scalars
+
+    We still want to be able to allow a relative tolerance for the values though.
+    The main logic comparison logic is handled by the xp_assert_* functions.
+    """
+    def assert_func(x, y):
+        xp_assert_equal(x, y) if rtol is None else xp_assert_close(x, y, rtol=rtol)
+
+    def assert_complex_nan(x):
+        assert np.isnan(x.real) and np.isnan(x.imag)
+
+    assert type(x) is type(y), f"types not equal: {type(x)}, {type(y)}"
+
+    # ensure we also compare the values _within_ an array appropriately,
+    # e.g. assert_equal does not distinguish different complex nans in arrays
+    if isinstance(x, np.ndarray):
+        # assert_equal does not compare (all) types, only values
+        assert x.dtype == y.dtype
+        # for empty arrays resp. to ensure shapes match
+        assert_func(x, y)
+        for elem_x, elem_y in zip(x.ravel(), y.ravel()):
+            assert_really_equal(elem_x, elem_y, rtol=rtol)
+    elif np.isnan(x) and np.isnan(y) and _is_subdtype(type(x), "c"):
+        assert_complex_nan(x) and assert_complex_nan(y)
+    # no need to consider complex infinities due to numpy/numpy#25493
+    else:
+        assert_func(x, y)
+
+
+class TestFactorialFunctions:
+    def factorialk_ref(self, n, k, exact, extend):
+        if exact:
+            return special.factorialk(n, k=k, exact=True)
+        # for details / explanation see factorialk-docstring
+        r = np.mod(n, k) if extend == "zero" else 1
+        vals = np.power(k, (n - r)/k) * special.gamma(n/k + 1) * special.rgamma(r/k + 1)
+        # np.maximum is element-wise, which is what we want
+        return vals * np.maximum(r, 1)
+
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    def test_factorialx_scalar_return_type(self, exact, extend):
+        kw = {"exact": exact, "extend": extend}
+        assert np.isscalar(special.factorial(1, **kw))
+        assert np.isscalar(special.factorial2(1, **kw))
+        assert np.isscalar(special.factorialk(1, k=3, **kw))
+
+    @pytest.mark.parametrize("n", [-1, -2, -3])
+    @pytest.mark.parametrize("exact", [True, False])
+    def test_factorialx_negative_extend_zero(self, exact, n):
+        kw = {"exact": exact}
+        assert_equal(special.factorial(n, **kw), 0)
+        assert_equal(special.factorial2(n, **kw), 0)
+        assert_equal(special.factorialk(n, k=3, **kw), 0)
+
+    @pytest.mark.parametrize("exact", [True, False])
+    def test_factorialx_negative_extend_zero_array(self, exact):
+        kw = {"exact": exact}
+        rtol = 1e-15
+        n = [-5, -4, 0, 1]
+        # Consistent output for n < 0
+        expected = np.array([0, 0, 1, 1], dtype=native_int if exact else np.float64)
+        assert_really_equal(special.factorial(n, **kw), expected, rtol=rtol)
+        assert_really_equal(special.factorial2(n, **kw), expected, rtol=rtol)
+        assert_really_equal(special.factorialk(n, k=3, **kw), expected, rtol=rtol)
+
+    @pytest.mark.parametrize("n", [-1.1, -2.2, -3.3])
+    def test_factorialx_negative_extend_complex(self, n):
+        kw = {"extend": "complex"}
+        exp_1 = {-1.1: -10.686287021193184771,
+                 -2.2:   4.8509571405220931958,
+                 -3.3:  -1.4471073942559181166}
+        exp_2 = {-1.1:  1.0725776858167496309,
+                 -2.2: -3.9777171783768419874,
+                 -3.3: -0.99588841846200555977}
+        exp_k = {-1.1:  0.73565345382163025659,
+                 -2.2:  1.1749163167190809498,
+                 -3.3: -2.4780584257450583713}
+        rtol = 3e-15
+        assert_allclose(special.factorial(n, **kw), exp_1[n], rtol=rtol)
+        assert_allclose(special.factorial2(n, **kw), exp_2[n], rtol=rtol)
+        assert_allclose(special.factorialk(n, k=3, **kw), exp_k[n], rtol=rtol)
+        assert_allclose(special.factorial([n], **kw)[0], exp_1[n], rtol=rtol)
+        assert_allclose(special.factorial2([n], **kw)[0], exp_2[n], rtol=rtol)
+        assert_allclose(special.factorialk([n], k=3, **kw)[0], exp_k[n], rtol=rtol)
+
+    @pytest.mark.parametrize("imag", [0, 0j])
+    @pytest.mark.parametrize("n_outer", [-1, -2, -3])
+    def test_factorialx_negative_extend_complex_poles(self, n_outer, imag):
+        kw = {"extend": "complex"}
+        def _check(n):
+            complexify = _is_subdtype(type(n), "c")
+            # like for gamma, we expect complex nans for complex inputs
+            complex_nan = np.complex128("nan+nanj")
+            exp = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            # poles are at negative integers that are multiples of k
+            assert_really_equal(special.factorial(n, **kw), exp)
+            assert_really_equal(special.factorial2(n * 2, **kw), exp)
+            assert_really_equal(special.factorialk(n * 3, k=3, **kw), exp)
+            # also test complex k for factorialk
+            c = 1.5 - 2j
+            assert_really_equal(special.factorialk(n * c, k=c, **kw), complex_nan)
+            # same for array case
+            assert_really_equal(special.factorial([n], **kw)[0], exp)
+            assert_really_equal(special.factorial2([n * 2], **kw)[0], exp)
+            assert_really_equal(special.factorialk([n * 3], k=3, **kw)[0], exp)
+            assert_really_equal(special.factorialk([n * c], k=c, **kw)[0], complex_nan)
+            # more specific tests in test_factorial{,2,k}_complex_reference
+
+        # imag ensures we test both real and complex representations of the poles
+        _check(n_outer + imag)
+        # check for large multiple of period
+        _check(100_000 * n_outer + imag)
+
+    @pytest.mark.parametrize("boxed", [True, False])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize(
+        "n",
+        [
+            np.nan, np.float64("nan"), np.nan + np.nan*1j, np.complex128("nan+nanj"),
+            np.inf, np.inf + 0j, -np.inf, -np.inf + 0j, None, np.datetime64("nat")
+        ],
+        ids=[
+            "NaN", "np.float64('nan')", "NaN+i*NaN", "np.complex128('nan+nanj')",
+            "inf", "inf+0i", "-inf", "-inf+0i", "None", "NaT"
+        ]
+    )
+    @pytest.mark.parametrize(
+        "factorialx",
+        [special.factorial, special.factorial2, special.factorialk]
+    )
+    def test_factorialx_inf_nan(self, factorialx, n, extend, boxed):
+        # NaNs not allowed (by dtype) for exact=True
+        kw = {"exact": False, "extend": extend}
+        if factorialx == special.factorialk:
+            kw["k"] = 3
+
+        # None is allowed for scalars, but would cause object type in array case
+        permissible_types = ["i", "f", "c"] if boxed else ["i", "f", "c", type(None)]
+        # factorial allows floats also for extend="zero"
+        types_need_complex_ext = "c" if factorialx == special.factorial else ["f", "c"]
+
+        if not _is_subdtype(type(n), permissible_types):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                factorialx([n] if boxed else n, **kw)
+        elif _is_subdtype(type(n), types_need_complex_ext) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                factorialx([n] if boxed else n, **kw)
+        else:
+            # account for type and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            # note that the type of the naïve `np.nan + np.nan * 1j` is `complex`
+            # instead of `numpy.complex128`, which trips up assert_really_equal
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            # the only exception are real infinities
+            if _is_subdtype(type(n), "f") and np.isinf(n):
+                # unchanged for positive infinity; negative one depends on extension
+                neg_inf_result = np.float64(0 if (extend == "zero") else "nan")
+                expected = np.float64("inf") if (n > 0) else neg_inf_result
+
+            result = factorialx([n], **kw)[0] if boxed else factorialx(n, **kw)
+            assert_really_equal(result, expected)
+            # also tested in test_factorial{,2,k}_{array,scalar}_corner_cases
+
+    @pytest.mark.parametrize("extend", [0, 1.1, np.nan, "string"])
+    def test_factorialx_raises_extend(self, extend):
+        with pytest.raises(ValueError, match="argument `extend` must be.*"):
+            special.factorial(1, extend=extend)
+        with pytest.raises(ValueError, match="argument `extend` must be.*"):
+            special.factorial2(1, extend=extend)
+        with pytest.raises(ValueError, match="argument `extend` must be.*"):
+            special.factorialk(1, k=3, exact=True, extend=extend)
+
+    @pytest.mark.parametrize("levels", range(1, 5))
+    @pytest.mark.parametrize("exact", [True, False])
+    def test_factorialx_array_shape(self, levels, exact):
+        def _nest_me(x, k=1):
+            """
+            Double x and nest it k times
+
+            For example:
+            >>> _nest_me([3, 4], 2)
+            [[[3, 4], [3, 4]], [[3, 4], [3, 4]]]
+            """
+            if k == 0:
+                return x
+            else:
+                return _nest_me([x, x], k-1)
+
+        def _check(res, nucleus):
+            exp = np.array(_nest_me(nucleus, k=levels), dtype=object)
+            # test that ndarray shape is maintained
+            # need to cast to float due to numpy/numpy#21220
+            assert_allclose(res.astype(np.float64), exp.astype(np.float64))
+
+        n = np.array(_nest_me([5, 25], k=levels))
+        exp_nucleus = {1: [120, math.factorial(25)],
+                       # correctness of factorial{2,k}() is tested elsewhere
+                       2: [15, special.factorial2(25, exact=True)],
+                       3: [10, special.factorialk(25, 3, exact=True)]}
+
+        _check(special.factorial(n, exact=exact), exp_nucleus[1])
+        _check(special.factorial2(n, exact=exact), exp_nucleus[2])
+        _check(special.factorialk(n, 3, exact=exact), exp_nucleus[3])
+
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dtype", [
+        None, int, np.int8, np.int16, np.int32, np.int64,
+        np.uint8, np.uint16, np.uint32, np.uint64
+    ])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    def test_factorialx_array_dimension(self, dim, dtype, exact):
+        n = np.array(5, dtype=dtype, ndmin=dim)
+        exp = {1: 120, 2: 15, 3: 10}
+        assert_allclose(special.factorial(n, exact=exact),
+                        np.array(exp[1], ndmin=dim))
+        assert_allclose(special.factorial2(n, exact=exact),
+                        np.array(exp[2], ndmin=dim))
+        assert_allclose(special.factorialk(n, 3, exact=exact),
+                        np.array(exp[3], ndmin=dim))
+
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("level", range(1, 5))
+    def test_factorialx_array_like(self, level, exact):
+        def _nest_me(x, k=1):
+            if k == 0:
+                return x
+            else:
+                return _nest_me([x], k-1)
+
+        n = _nest_me([5], k=level-1)  # nested list
+        exp_nucleus = {1: 120, 2: 15, 3: 10}
+        assert_func = assert_array_equal if exact else assert_allclose
+        assert_func(special.factorial(n, exact=exact),
+                    np.array(exp_nucleus[1], ndmin=level))
+        assert_func(special.factorial2(n, exact=exact),
+                    np.array(exp_nucleus[2], ndmin=level))
+        assert_func(special.factorialk(n, 3, exact=exact),
+                    np.array(exp_nucleus[3], ndmin=level))
+
+    @pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    def test_factorialx_uint(self, exact, extend, dtype):
+        # ensure that uint types work correctly as inputs
+        kw = {"exact": exact, "extend": extend}
+        assert_func = assert_array_equal if exact else assert_allclose
+        def _check(n):
+            n_ref = n.astype(np.int64) if isinstance(n, np.ndarray) else np.int64(n)
+            assert_func(special.factorial(n, **kw), special.factorial(n_ref, **kw))
+            assert_func(special.factorial2(n, **kw), special.factorial2(n_ref, **kw))
+            assert_func(special.factorialk(n, k=3, **kw),
+                        special.factorialk(n_ref, k=3, **kw))
+        _check(dtype(0))
+        _check(dtype(1))
+        _check(np.array(0, dtype=dtype))
+        _check(np.array([0, 1], dtype=dtype))
+
+    # note that n=170 is the last integer such that factorial(n) fits float64
+    @pytest.mark.parametrize('n', range(30, 180, 10))
+    def test_factorial_accuracy(self, n):
+        # Compare exact=True vs False, i.e. that the accuracy of the
+        # approximation is better than the specified tolerance.
+
+        rtol = 6e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        assert_allclose(float(special.factorial(n, exact=True)),
+                        special.factorial(n, exact=False), rtol=rtol)
+        assert_allclose(special.factorial([n], exact=True).astype(float),
+                        special.factorial([n], exact=False), rtol=rtol)
+
+    @pytest.mark.parametrize('n',
+                             list(range(0, 22)) + list(range(30, 180, 10)))
+    def test_factorial_int_reference(self, n):
+        # Compare all with math.factorial
+        correct = math.factorial(n)
+        assert_array_equal(correct, special.factorial(n, exact=True))
+        assert_array_equal(correct, special.factorial([n], exact=True)[0])
+
+        rtol = 8e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        correct = float(correct)
+        assert_allclose(correct, special.factorial(n, exact=False), rtol=rtol)
+        assert_allclose(correct, special.factorial([n], exact=False)[0], rtol=rtol)
+
+        # extend="complex" only works for exact=False
+        kw = {"exact": False, "extend": "complex"}
+        assert_allclose(correct, special.factorial(n, **kw), rtol=rtol)
+        assert_allclose(correct, special.factorial([n], **kw)[0], rtol=rtol)
+
+    def test_factorial_float_reference(self):
+        def _check(n, expected):
+            rtol = 8e-14 if sys.platform == 'win32' else 1e-15
+            assert_allclose(special.factorial(n), expected, rtol=rtol)
+            assert_allclose(special.factorial([n])[0], expected, rtol=rtol)
+            # using floats with `exact=True` raises an error for scalars and arrays
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial(n, exact=True)
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial([n], exact=True)
+
+        # Reference values from mpmath for gamma(n+1)
+        _check(0.01, 0.994325851191506032181932988)
+        _check(1.11, 1.051609009483625091514147465)
+        _check(5.55, 314.9503192327208241614959052)
+        _check(11.1, 50983227.84411615655137170553)
+        _check(33.3, 2.493363339642036352229215273e+37)
+        _check(55.5, 9.479934358436729043289162027e+73)
+        _check(77.7, 3.060540559059579022358692625e+114)
+        _check(99.9, 5.885840419492871504575693337e+157)
+        # close to maximum for float64
+        _check(170.6243, 1.79698185749571048960082e+308)
+
+    def test_factorial_complex_reference(self):
+        def _check(n, expected):
+            rtol = 3e-15 if sys.platform == 'win32' else 2e-15
+            kw = {"exact": False, "extend": "complex"}
+            assert_allclose(special.factorial(n, **kw), expected, rtol=rtol)
+            assert_allclose(special.factorial([n], **kw)[0], expected, rtol=rtol)
+
+        # Reference values from mpmath.gamma(n+1)
+        # negative & complex values
+        _check(-0.5, expected=1.7724538509055160276)
+        _check(-0.5 + 0j, expected=1.7724538509055160276 + 0j)
+        _check(2 + 2j, expected=-0.42263728631120216694 + 0.87181425569650686062j)
+        # close to poles
+        _check(-0.9999, expected=9999.422883232725532)
+        _check(-1 + 0.0001j, expected=-0.57721565582674219 - 9999.9999010944009697j)
+
+    @pytest.mark.parametrize("dtype", [np.int64, np.float64,
+                                       np.complex128, object])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    # test empty & non-empty arrays, with nans and mixed
+    @pytest.mark.parametrize(
+        "content",
+        [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]],
+        ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"],
+    )
+    def test_factorial_array_corner_cases(self, content, dim, exact, extend, dtype):
+        if dtype is object and SCIPY_ARRAY_API:
+            pytest.skip("object arrays unsupported in array API mode")
+        # get dtype without calling array constructor (that might fail or mutate)
+        if dtype is np.int64 and any(np.isnan(x) or (x != int(x)) for x in content):
+            pytest.skip("impossible combination")
+        if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content):
+            pytest.skip("impossible combination")
+
+        kw = {"exact": exact, "extend": extend}
+        # np.array(x, ndim=0) will not be 0-dim. unless x is too
+        content = content if (dim > 0 or len(content) != 1) else content[0]
+        n = np.array(content, ndmin=dim, dtype=dtype)
+
+        result = None
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial(n, **kw)
+        elif not _is_subdtype(n.dtype, ["i", "f", "c"]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial(n, **kw)
+        elif _is_subdtype(n.dtype, "c") and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial(n, **kw)
+        elif exact and not _is_subdtype(n.dtype, "i"):
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial(n, **kw)
+        else:
+            result = special.factorial(n, **kw)
+
+        if result is not None:
+            # use scalar case as reference; tested separately in *_scalar_corner_cases
+            ref = [special.factorial(x, **kw) for x in n.ravel()]
+            # unpack length-1 lists so that np.array(x, ndim=0) works correctly
+            ref = ref[0] if len(ref) == 1 else ref
+            # result is empty if and only if n is empty, and has the same dimension
+            # as n; dtype stays the same, except when not empty and not exact:
+            if n.size:
+                cx = (extend == "complex") and _is_subdtype(n.dtype, "c")
+                dtype = np.complex128 if cx else (native_int if exact else np.float64)
+            expected = np.array(ref, ndmin=dim, dtype=dtype)
+            assert_really_equal(result, expected, rtol=1e-15)
+
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None],
+                             ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"])
+    def test_factorial_scalar_corner_cases(self, n, exact, extend):
+        kw = {"exact": exact, "extend": extend}
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial(n, **kw)
+        elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial(n, **kw)
+        elif _is_subdtype(type(n), "c") and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial(n, **kw)
+        elif n is None or np.isnan(n):
+            # account for dtype and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            assert_really_equal(special.factorial(n, **kw), expected)
+        elif exact and _is_subdtype(type(n), "f"):
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial(n, **kw)
+        else:
+            assert_equal(special.factorial(n, **kw), special.gamma(n + 1))
+
+    # use odd increment to make sure both odd & even numbers are tested!
+    @pytest.mark.parametrize('n', range(30, 180, 11))
+    def test_factorial2_accuracy(self, n):
+        # Compare exact=True vs False, i.e. that the accuracy of the
+        # approximation is better than the specified tolerance.
+
+        rtol = 2e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        assert_allclose(float(special.factorial2(n, exact=True)),
+                        special.factorial2(n, exact=False), rtol=rtol)
+        assert_allclose(special.factorial2([n], exact=True).astype(float),
+                        special.factorial2([n], exact=False), rtol=rtol)
+
+    @pytest.mark.parametrize('n',
+                             list(range(0, 22)) + list(range(30, 180, 11)))
+    def test_factorial2_int_reference(self, n):
+        # Compare all with correct value
+
+        # Cannot use np.product due to overflow
+        correct = functools.reduce(operator.mul, list(range(n, 0, -2)), 1)
+
+        assert_array_equal(correct, special.factorial2(n, exact=True))
+        assert_array_equal(correct, special.factorial2([n], exact=True)[0])
+
+        rtol = 2e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        correct = float(correct)
+        assert_allclose(correct, special.factorial2(n, exact=False), rtol=rtol)
+        assert_allclose(correct, special.factorial2([n], exact=False)[0], rtol=rtol)
+
+        # extend="complex" only works for exact=False
+        kw = {"exact": False, "extend": "complex"}
+        # approximation only matches exactly for `n == 1 (mod k)`, see docstring
+        if n % 2 == 1:
+            assert_allclose(correct, special.factorial2(n, **kw), rtol=rtol)
+            assert_allclose(correct, special.factorial2([n], **kw)[0], rtol=rtol)
+
+    def test_factorial2_complex_reference(self):
+        # this tests for both floats and complex
+        def _check(n, expected):
+            rtol = 5e-15
+            kw = {"exact": False, "extend": "complex"}
+            assert_allclose(special.factorial2(n, **kw), expected, rtol=rtol)
+            assert_allclose(special.factorial2([n], **kw)[0], expected, rtol=rtol)
+
+        # Reference values from mpmath for:
+        # mpmath.power(2, n/2) * mpmath.gamma(n/2 + 1) * mpmath.sqrt(2 / mpmath.pi)
+        _check(3, expected=3)
+        _check(4, expected=special.factorial2(4) * math.sqrt(2 / math.pi))
+        _check(20, expected=special.factorial2(20) * math.sqrt(2 / math.pi))
+        # negative & complex values
+        _check(-0.5, expected=0.82217895866245855122)
+        _check(-0.5 + 0j, expected=0.82217895866245855122 + 0j)
+        _check(3 + 3j, expected=-1.0742236630142471526 + 1.4421398439387262897j)
+        # close to poles
+        _check(-1.9999, expected=7978.8918745523440682)
+        _check(-2 + 0.0001j, expected=0.0462499835314308444 - 7978.84559148876374493j)
+
+    @pytest.mark.parametrize("dtype", [np.int64, np.float64,
+                                       np.complex128, object])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    # test empty & non-empty arrays, with nans and mixed
+    @pytest.mark.parametrize(
+        "content",
+        [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]],
+        ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"],
+    )
+    def test_factorial2_array_corner_cases(self, content, dim, exact, extend, dtype):
+        # get dtype without calling array constructor (that might fail or mutate)
+        if dtype == np.int64 and any(np.isnan(x) or (x != int(x)) for x in content):
+            pytest.skip("impossible combination")
+        if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content):
+            pytest.skip("impossible combination")
+
+        kw = {"exact": exact, "extend": extend}
+        # np.array(x, ndim=0) will not be 0-dim. unless x is too
+        content = content if (dim > 0 or len(content) != 1) else content[0]
+        n = np.array(content, ndmin=dim, dtype=dtype)
+
+        result = None
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial2(n, **kw)
+        elif not _is_subdtype(n.dtype, ["i", "f", "c"]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial2(n, **kw)
+        elif _is_subdtype(n.dtype, ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial2(n, **kw)
+        else:
+            result = special.factorial2(n, **kw)
+
+        if result is not None:
+            # use scalar case as reference; tested separately in *_scalar_corner_cases
+            ref = [special.factorial2(x, **kw) for x in n.ravel()]
+            # unpack length-1 lists so that np.array(x, ndim=0) works correctly
+            ref = ref[0] if len(ref) == 1 else ref
+            # result is empty if and only if n is empty, and has the same dimension
+            # as n; dtype stays the same, except when not empty and not exact:
+            if n.size:
+                cx = (extend == "complex") and _is_subdtype(n.dtype, "c")
+                dtype = np.complex128 if cx else (native_int if exact else np.float64)
+            expected = np.array(ref, ndmin=dim, dtype=dtype)
+            assert_really_equal(result, expected, rtol=2e-15)
+
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None],
+                             ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"])
+    def test_factorial2_scalar_corner_cases(self, n, exact, extend):
+        kw = {"exact": exact, "extend": extend}
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial2(n, **kw)
+        elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial2(n, **kw)
+        elif _is_subdtype(type(n), ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial2(n, **kw)
+        elif n is None or np.isnan(n):
+            # account for dtype and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            assert_really_equal(special.factorial2(n, **kw), expected)
+        else:
+            expected = self.factorialk_ref(n, k=2, **kw)
+            assert_really_equal(special.factorial2(n, **kw), expected, rtol=1e-15)
+
+    @pytest.mark.parametrize("k", range(1, 5))
+    # note that n=170 is the last integer such that factorial(n) fits float64;
+    # use odd increment to make sure both odd & even numbers are tested
+    @pytest.mark.parametrize('n', range(170, 20, -29))
+    def test_factorialk_accuracy(self, n, k):
+        # Compare exact=True vs False, i.e. that the accuracy of the
+        # approximation is better than the specified tolerance.
+
+        rtol = 6e-14 if sys.platform == 'win32' else 2e-14
+        # need to cast exact result to float due to numpy/numpy#21220
+        assert_allclose(float(special.factorialk(n, k=k, exact=True)),
+                        special.factorialk(n, k=k, exact=False), rtol=rtol)
+        assert_allclose(special.factorialk([n], k=k, exact=True).astype(float),
+                        special.factorialk([n], k=k, exact=False), rtol=rtol)
+
+    @pytest.mark.parametrize('k', list(range(1, 5)) + [10, 20])
+    @pytest.mark.parametrize('n',
+                             list(range(0, 22)) + list(range(22, 100, 11)))
+    def test_factorialk_int_reference(self, n, k):
+        # Compare all with correct value
+
+        # Would be nice to use np.product here, but that's
+        # broken on windows, see numpy/numpy#21219
+        correct = functools.reduce(operator.mul, list(range(n, 0, -k)), 1)
+
+        assert_array_equal(correct, special.factorialk(n, k, exact=True))
+        assert_array_equal(correct, special.factorialk([n], k, exact=True)[0])
+
+        rtol = 3e-14 if sys.platform == 'win32' else 1e-14
+        # need to cast exact result to float due to numpy/numpy#21220
+        correct = float(correct)
+        assert_allclose(correct, special.factorialk(n, k, exact=False), rtol=rtol)
+        assert_allclose(correct, special.factorialk([n], k, exact=False)[0], rtol=rtol)
+
+        # extend="complex" only works for exact=False
+        kw = {"k": k, "exact": False, "extend": "complex"}
+        # approximation only matches exactly for `n == 1 (mod k)`, see docstring
+        if n % k == 1:
+            rtol = 2e-14
+            assert_allclose(correct, special.factorialk(n, **kw), rtol=rtol)
+            assert_allclose(correct, special.factorialk([n], **kw)[0], rtol=rtol)
+
+    def test_factorialk_complex_reference(self):
+        # this tests for both floats and complex
+        def _check(n, k, exp):
+            rtol = 1e-14
+            kw = {"k": k, "exact": False, "extend": "complex"}
+            assert_allclose(special.factorialk(n, **kw), exp, rtol=rtol)
+            assert_allclose(special.factorialk([n], **kw)[0], exp, rtol=rtol)
+
+        # Reference values from mpmath for:
+        # mpmath.power(k, (n-1)/k) * mpmath.gamma(n/k + 1) / mpmath.gamma(1/k + 1)
+        _check(n=4, k=3, exp=special.factorialk(4, k=3, exact=True))
+        _check(n=5, k=3, exp=7.29011132947227083)
+        _check(n=6.5, k=3, exp=19.6805080113566010)
+        # non-integer k
+        _check(n=3, k=2.5, exp=2.58465740293218541)
+        _check(n=11, k=2.5, exp=1963.5)  # ==11*8.5*6*3.5; c.f. n == 1 (mod k)
+        _check(n=-3 + 3j + 1, k=-3 + 3j, exp=-2 + 3j)
+        # complex values
+        _check(n=4 + 4j, k=4, exp=-0.67855904082768043854 + 2.1993925819930311497j)
+        _check(n=4, k=4 - 4j, exp=1.9775338957222718742 + 0.92607172675423901371j)
+        _check(n=4 + 4j, k=4 - 4j, exp=0.1868492880824934475 + 0.87660580316894290247j)
+        # negative values
+        _check(n=-0.5, k=3, exp=0.72981013240713739354)
+        _check(n=-0.5 + 0j, k=3, exp=0.72981013240713739354 + 0j)
+        _check(n=2.9, k=-0.7, exp=0.45396591474966867296 + 0.56925525174685228866j)
+        _check(n=-0.6, k=-0.7, exp=-0.07190820089634757334 - 0.090170031876701730081j)
+        # close to poles
+        _check(n=-2.9999, k=3, exp=7764.7170695908828364)
+        _check(n=-3 + 0.0001j, k=3, exp=0.1349475632879599864 - 7764.5821055158365027j)
+
+    @pytest.mark.parametrize("dtype", [np.int64, np.float64,
+                                       np.complex128, object])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    # test empty & non-empty arrays, with nans and mixed
+    @pytest.mark.parametrize(
+        "content",
+        [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]],
+        ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"],
+    )
+    def test_factorialk_array_corner_cases(self, content, dim, exact, extend, dtype):
+        # get dtype without calling array constructor (that might fail or mutate)
+        if dtype == np.int64 and any(np.isnan(x) or (x != int(x)) for x in content):
+            pytest.skip("impossible combination")
+        if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content):
+            pytest.skip("impossible combination")
+
+        kw = {"k": 3, "exact": exact, "extend": extend}
+        # np.array(x, ndim=0) will not be 0-dim. unless x is too
+        content = content if (dim > 0 or len(content) != 1) else content[0]
+        n = np.array(content, ndmin=dim, dtype=dtype)
+
+        result = None
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorialk(n, **kw)
+        elif not _is_subdtype(n.dtype, ["i", "f", "c"]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorialk(n, **kw)
+        elif _is_subdtype(n.dtype, ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorialk(n, **kw)
+        else:
+            result = special.factorialk(n, **kw)
+
+        if result is not None:
+            # use scalar case as reference; tested separately in *_scalar_corner_cases
+            ref = [special.factorialk(x, **kw) for x in n.ravel()]
+            # unpack length-1 lists so that np.array(x, ndim=0) works correctly
+            ref = ref[0] if len(ref) == 1 else ref
+            # result is empty if and only if n is empty, and has the same dimension
+            # as n; dtype stays the same, except when not empty and not exact:
+            if n.size:
+                cx = (extend == "complex") and _is_subdtype(n.dtype, "c")
+                dtype = np.complex128 if cx else (native_int if exact else np.float64)
+            expected = np.array(ref, ndmin=dim, dtype=dtype)
+            assert_really_equal(result, expected, rtol=2e-15)
+
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("k", range(1, 5))
+    @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None],
+                             ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"])
+    def test_factorialk_scalar_corner_cases(self, n, k, exact, extend):
+        kw = {"k": k, "exact": exact, "extend": extend}
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorialk(n, **kw)
+        elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorialk(n, **kw)
+        elif _is_subdtype(type(n), ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorialk(n, **kw)
+        elif n is None or np.isnan(n):
+            # account for dtype and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            assert_really_equal(special.factorialk(n, **kw), expected)
+        else:
+            expected = self.factorialk_ref(n, **kw)
+            assert_really_equal(special.factorialk(n, **kw), expected, rtol=1e-15)
+
+    @pytest.mark.parametrize("boxed", [True, False])
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    @pytest.mark.parametrize("k", [-1, -1.0, 0, 0.0, 0 + 1j, 1.1, np.nan])
+    def test_factorialk_raises_k_complex(self, k, exact, extend, boxed):
+        n = [1] if boxed else 1
+        kw = {"k": k, "exact": exact, "extend": extend}
+        if extend == "zero":
+            msg = "In order to use non-integer.*"
+            if _is_subdtype(type(k), "i") and (k < 1):
+                msg = "For `extend='zero'`.*"
+            with pytest.raises(ValueError, match=msg):
+                special.factorialk(n, **kw)
+        elif k == 0:
+            with pytest.raises(ValueError, match="Parameter k cannot be zero!"):
+                special.factorialk(n, **kw)
+        else:
+            # no error
+            special.factorialk(n, **kw)
+
+    @pytest.mark.parametrize("boxed", [True, False])
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    # neither integer, float nor complex
+    @pytest.mark.parametrize("k", ["string", np.datetime64("nat")],
+                             ids=["string", "NaT"])
+    def test_factorialk_raises_k_other(self, k, exact, extend, boxed):
+        n = [1] if boxed else 1
+        kw = {"k": k, "exact": exact, "extend": extend}
+        with pytest.raises(ValueError, match="Unsupported data type.*"):
+            special.factorialk(n, **kw)
+
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    @pytest.mark.parametrize("k", range(1, 12))
+    def test_factorialk_dtype(self, k, exact, extend):
+        kw = {"k": k, "exact": exact, "extend": extend}
+        if exact and k in _FACTORIALK_LIMITS_64BITS.keys():
+            n = np.array([_FACTORIALK_LIMITS_32BITS[k]])
+            assert_equal(special.factorialk(n, **kw).dtype, np_long)
+            assert_equal(special.factorialk(n + 1, **kw).dtype, np.int64)
+            # assert maximality of limits for given dtype
+            assert special.factorialk(n + 1, **kw) > np.iinfo(np.int32).max
+
+            n = np.array([_FACTORIALK_LIMITS_64BITS[k]])
+            assert_equal(special.factorialk(n, **kw).dtype, np.int64)
+            assert_equal(special.factorialk(n + 1, **kw).dtype, object)
+            assert special.factorialk(n + 1, **kw) > np.iinfo(np.int64).max
+        else:
+            n = np.array([_FACTORIALK_LIMITS_64BITS.get(k, 1)])
+            # for exact=True and k >= 10, we always return object;
+            # for exact=False it's always float (unless input is complex)
+            dtype = object if exact else np.float64
+            assert_equal(special.factorialk(n, **kw).dtype, dtype)
+
+    def test_factorial_mixed_nan_inputs(self):
+        x = np.array([np.nan, 1, 2, 3, np.nan])
+        expected = np.array([np.nan, 1, 2, 6, np.nan])
+        assert_equal(special.factorial(x, exact=False), expected)
+        with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+            special.factorial(x, exact=True)
+
+
+class TestFresnel:
+    @pytest.mark.parametrize("z, s, c", [
+        # some positive value
+        (.5, 0.064732432859999287, 0.49234422587144644),
+        (.5 + .0j, 0.064732432859999287, 0.49234422587144644),
+        # negative half annulus
+        # https://github.com/scipy/scipy/issues/12309
+        # Reference values can be reproduced with
+        # https://www.wolframalpha.com/input/?i=FresnelS%5B-2.0+%2B+0.1i%5D
+        # https://www.wolframalpha.com/input/?i=FresnelC%5B-2.0+%2B+0.1i%5D
+        (
+            -2.0 + 0.1j,
+            -0.3109538687728942-0.0005870728836383176j,
+            -0.4879956866358554+0.10670801832903172j
+        ),
+        (
+            -0.1 - 1.5j,
+            -0.03918309471866977+0.7197508454568574j,
+            0.09605692502968956-0.43625191013617465j
+        ),
+        # a different algorithm kicks in for "large" values, i.e., |z| >= 4.5,
+        # make sure to test both float and complex values; a different
+        # algorithm is used
+        (6.0, 0.44696076, 0.49953147),
+        (6.0 + 0.0j, 0.44696076, 0.49953147),
+        (6.0j, -0.44696076j, 0.49953147j),
+        (-6.0 + 0.0j, -0.44696076, -0.49953147),
+        (-6.0j, 0.44696076j, -0.49953147j),
+        # inf
+        (np.inf, 0.5, 0.5),
+        (-np.inf, -0.5, -0.5),
+    ])
+    def test_fresnel_values(self, z, s, c):
+        frs = array(special.fresnel(z))
+        assert_array_almost_equal(frs, array([s, c]), 8)
+
+    # values from pg 329  Table 7.11 of A & S
+    #  slightly corrected in 4th decimal place
+    def test_fresnel_zeros(self):
+        szo, czo = special.fresnel_zeros(5)
+        assert_array_almost_equal(szo,
+                                  array([2.0093+0.2885j,
+                                          2.8335+0.2443j,
+                                          3.4675+0.2185j,
+                                          4.0026+0.2009j,
+                                          4.4742+0.1877j]),3)
+        assert_array_almost_equal(czo,
+                                  array([1.7437+0.3057j,
+                                          2.6515+0.2529j,
+                                          3.3204+0.2240j,
+                                          3.8757+0.2047j,
+                                          4.3611+0.1907j]),3)
+        vals1 = special.fresnel(szo)[0]
+        vals2 = special.fresnel(czo)[1]
+        assert_array_almost_equal(vals1,0,14)
+        assert_array_almost_equal(vals2,0,14)
+
+    def test_fresnelc_zeros(self):
+        szo, czo = special.fresnel_zeros(6)
+        frc = special.fresnelc_zeros(6)
+        assert_array_almost_equal(frc,czo,12)
+
+    def test_fresnels_zeros(self):
+        szo, czo = special.fresnel_zeros(5)
+        frs = special.fresnels_zeros(5)
+        assert_array_almost_equal(frs,szo,12)
+
+
+class TestGamma:
+    def test_gamma(self):
+        gam = special.gamma(5)
+        assert_equal(gam,24.0)
+
+    def test_gammaln(self):
+        gamln = special.gammaln(3)
+        lngam = log(special.gamma(3))
+        assert_almost_equal(gamln,lngam,8)
+
+    def test_gammainccinv(self):
+        gccinv = special.gammainccinv(.5,.5)
+        gcinv = special.gammaincinv(.5,.5)
+        assert_almost_equal(gccinv,gcinv,8)
+
+    @with_special_errors
+    def test_gammaincinv(self):
+        y = special.gammaincinv(.4,.4)
+        x = special.gammainc(.4,y)
+        assert_almost_equal(x,0.4,1)
+        y = special.gammainc(10, 0.05)
+        x = special.gammaincinv(10, 2.5715803516000736e-20)
+        assert_almost_equal(0.05, x, decimal=10)
+        assert_almost_equal(y, 2.5715803516000736e-20, decimal=10)
+        x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18)
+        assert_almost_equal(11.0, x, decimal=10)
+
+    @with_special_errors
+    def test_975(self):
+        # Regression test for ticket #975 -- switch point in algorithm
+        # check that things work OK at the point, immediately next floats
+        # around it, and a bit further away
+        pts = [0.25,
+               np.nextafter(0.25, 0), 0.25 - 1e-12,
+               np.nextafter(0.25, 1), 0.25 + 1e-12]
+        for xp in pts:
+            y = special.gammaincinv(.4, xp)
+            x = special.gammainc(0.4, y)
+            assert_allclose(x, xp, rtol=1e-12)
+
+    def test_rgamma(self):
+        rgam = special.rgamma(8)
+        rlgam = 1/special.gamma(8)
+        assert_almost_equal(rgam,rlgam,8)
+
+    def test_infinity(self):
+        assert_equal(special.rgamma(-1), 0)
+
+    @pytest.mark.parametrize(
+        "x,expected",
+        [
+            # infinities
+            ([-np.inf, np.inf], [np.nan, np.inf]),
+            # negative and positive zero
+            ([-0.0, 0.0], [-np.inf, np.inf]),
+            # small poles
+            (range(-32, 0), np.full(32, np.nan)),
+            # medium sized poles
+            (range(-1024, -32, 99), np.full(11, np.nan)),
+            # large pole
+            ([-4.141512231792294e+16], [np.nan]),
+        ]
+    )
+    def test_poles(self, x, expected):
+        assert_array_equal(special.gamma(x), expected)
+
+
+class TestHankel:
+
+    def test_negv1(self):
+        assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14)
+
+    def test_hankel1(self):
+        hank1 = special.hankel1(1,.1)
+        hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j)
+        assert_almost_equal(hank1,hankrl,8)
+
+    def test_negv1e(self):
+        assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14)
+
+    def test_hankel1e(self):
+        hank1e = special.hankel1e(1,.1)
+        hankrle = special.hankel1(1,.1)*exp(-.1j)
+        assert_almost_equal(hank1e,hankrle,8)
+
+    def test_negv2(self):
+        assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14)
+
+    def test_hankel2(self):
+        hank2 = special.hankel2(1,.1)
+        hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j)
+        assert_almost_equal(hank2,hankrl2,8)
+
+    def test_neg2e(self):
+        assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14)
+
+    def test_hankl2e(self):
+        hank2e = special.hankel2e(1,.1)
+        hankrl2e = special.hankel2e(1,.1)
+        assert_almost_equal(hank2e,hankrl2e,8)
+
+    def test_hankel2_gh4517(self):
+        # Test edge case reported in https://github.com/scipy/scipy/issues/4517
+        res = special.hankel2(0, 0)
+        assert np.isnan(res.real)
+        assert np.isposinf(res.imag)
+
+
+class TestHyper:
+    def test_h1vp(self):
+        h1 = special.h1vp(1,.1)
+        h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j)
+        assert_almost_equal(h1,h1real,8)
+
+    def test_h2vp(self):
+        h2 = special.h2vp(1,.1)
+        h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j)
+        assert_almost_equal(h2,h2real,8)
+
+    def test_hyp0f1(self):
+        # scalar input
+        assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12)
+        assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15)
+
+        # float input, expected values match mpmath
+        x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5])
+        expected = np.array([0.58493659229143, 0.70566805723127, 1.0,
+                             1.37789689539747, 1.60373685288480])
+        assert_allclose(x, expected, rtol=1e-12)
+
+        # complex input
+        x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j)
+        assert_allclose(x, expected.astype(complex), rtol=1e-12)
+
+        # test broadcasting
+        x1 = [0.5, 1.5, 2.5]
+        x2 = [0, 1, 0.5]
+        x = special.hyp0f1(x1, x2)
+        expected = [1.0, 1.8134302039235093, 1.21482702689997]
+        assert_allclose(x, expected, rtol=1e-12)
+        x = special.hyp0f1(np.vstack([x1] * 2), x2)
+        assert_allclose(x, np.vstack([expected] * 2), rtol=1e-12)
+        assert_raises(ValueError, special.hyp0f1,
+                      np.vstack([x1] * 3), [0, 1])
+
+    def test_hyp0f1_gh5764(self):
+        # Just checks the point that failed; there's a more systematic
+        # test in test_mpmath
+        res = special.hyp0f1(0.8, 0.5 + 0.5*1J)
+        # The expected value was generated using mpmath
+        assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665)
+
+    def test_hyp1f1(self):
+        hyp1 = special.hyp1f1(.1,.1,.3)
+        assert_almost_equal(hyp1, 1.3498588075760032,7)
+
+        # test contributed by Moritz Deger (2008-05-29)
+        # https://github.com/scipy/scipy/issues/1186 (Trac #659)
+
+        # reference data obtained from mathematica [ a, b, x, m(a,b,x)]:
+        # produced with test_hyp1f1.nb
+        ref_data = array([
+            [-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04],
+            [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00],
+            [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05],
+            [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08],
+            [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24],
+            [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21],
+            [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13],
+            [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13],
+            [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02],
+            [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10],
+            [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01],
+            [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21],
+            [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20],
+            [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07],
+            [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03],
+            [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02],
+            [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11],
+            [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03],
+            [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17],
+            [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01],
+            [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00],
+            [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00],
+            [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23],
+            [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01],
+            [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04],
+            [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08],
+            [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01],
+            [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07],
+            [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03],
+            [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09],
+            [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06],
+            [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00],
+            [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01],
+            [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02],
+            [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02],
+            [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02],
+            [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00],
+            [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09],
+            [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01],
+            [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00],
+            [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02],
+            [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05],
+            [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05],
+            [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02],
+            [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02],
+            [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13],
+            [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05],
+            [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12],
+            [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01],
+            [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16],
+            [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37],
+            [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06],
+            [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02],
+            [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12],
+            [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27],
+            [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04],
+            [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06],
+            [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07],
+            [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03],
+            [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07],
+            [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27],
+            [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12],
+            [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32],
+            [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04],
+            [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01],
+            [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02],
+            [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19],
+            [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09],
+            [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31],
+            [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01],
+            [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02],
+            [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08],
+            [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09],
+            [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33],
+            [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01],
+            [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29],
+            [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01],
+            [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29],
+            [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02],
+            [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00],
+            [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08],
+            [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01],
+            [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01],
+            [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01],
+            [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13],
+            [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11],
+            [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02],
+            [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02],
+            [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01],
+            [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31],
+            [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04],
+            [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25],
+            [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01],
+            [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00],
+            [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02],
+            [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05],
+            [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02],
+            [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01],
+            [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01],
+            [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]
+        ])
+
+        for a,b,c,expected in ref_data:
+            result = special.hyp1f1(a,b,c)
+            assert_(abs(expected - result)/expected < 1e-4)
+
+    def test_hyp1f1_gh2957(self):
+        hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933)
+        hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934)
+        assert_almost_equal(hyp1, hyp2, 12)
+
+    def test_hyp1f1_gh2282(self):
+        hyp = special.hyp1f1(0.5, 1.5, -1000)
+        assert_almost_equal(hyp, 0.028024956081989643, 12)
+
+    def test_hyp2f1(self):
+        # a collection of special cases taken from AMS 55
+        values = [
+            [0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))],
+            [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)],
+            [1, 1, 2, 0.2, -1/0.2*log(1-0.2)],
+            [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))],
+            [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)],
+            [3, 4, 8, 1,
+             special.gamma(8) * special.gamma(8-4-3)
+             / special.gamma(8-3) / special.gamma(8-4)],
+            [3, 2, 3-2+1, -1,
+             1./2**3*sqrt(pi) * special.gamma(1+3-2)
+             / special.gamma(1+0.5*3-2) / special.gamma(0.5+0.5*3)],
+            [5, 2, 5-2+1, -1,
+             1./2**5*sqrt(pi) * special.gamma(1+5-2)
+             / special.gamma(1+0.5*5-2) / special.gamma(0.5+0.5*5)],
+            [4, 0.5+4, 1.5-2*4, -1./3,
+             (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)
+             / special.gamma(3./2) / special.gamma(4./3-2*4)],
+            # and some others
+            # ticket #424
+            [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484],
+            # negative integer a or b, with c-a-b integer and x > 0.9
+            [-2,3,1,0.95,0.715],
+            [2,-3,1,0.95,-0.007],
+            [-6,3,1,0.95,0.0000810625],
+            [2,-5,1,0.95,-0.000029375],
+            # huge negative integers
+            (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24),
+            (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18),
+        ]
+        for i, (a, b, c, x, v) in enumerate(values):
+            cv = special.hyp2f1(a, b, c, x)
+            assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
+
+    def test_hyperu(self):
+        val1 = special.hyperu(1,0.1,100)
+        assert_almost_equal(val1,0.0098153,7)
+        a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2]
+        a,b = asarray(a), asarray(b)
+        z = 0.5
+        hypu = special.hyperu(a,b,z)
+        hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) /
+                               (special.gamma(1+a-b)*special.gamma(b)) -
+                               z**(1-b)*special.hyp1f1(1+a-b,2-b,z)
+                               / (special.gamma(a)*special.gamma(2-b)))
+        assert_array_almost_equal(hypu,hprl,12)
+
+    def test_hyperu_gh2287(self):
+        assert_almost_equal(special.hyperu(1, 1.5, 20.2),
+                            0.048360918656699191, 12)
+
+
+class TestBessel:
+    def test_itj0y0(self):
+        it0 = array(special.itj0y0(.2))
+        assert_array_almost_equal(
+            it0,
+            array([0.19933433254006822, -0.34570883800412566]),
+            8,
+        )
+
+    def test_it2j0y0(self):
+        it2 = array(special.it2j0y0(.2))
+        assert_array_almost_equal(
+            it2,
+            array([0.0049937546274601858, -0.43423067011231614]),
+            8,
+        )
+
+    def test_negv_iv(self):
+        assert_equal(special.iv(3,2), special.iv(-3,2))
+
+    def test_j0(self):
+        oz = special.j0(.1)
+        ozr = special.jn(0,.1)
+        assert_almost_equal(oz,ozr,8)
+
+    def test_j1(self):
+        o1 = special.j1(.1)
+        o1r = special.jn(1,.1)
+        assert_almost_equal(o1,o1r,8)
+
+    def test_jn(self):
+        jnnr = special.jn(1,.2)
+        assert_almost_equal(jnnr,0.099500832639235995,8)
+
+    def test_negv_jv(self):
+        assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14)
+
+    def test_jv(self):
+        values = [[0, 0.1, 0.99750156206604002],
+                  [2./3, 1e-8, 0.3239028506761532e-5],
+                  [2./3, 1e-10, 0.1503423854873779e-6],
+                  [3.1, 1e-10, 0.1711956265409013e-32],
+                  [2./3, 4.0, -0.2325440850267039],
+                  ]
+        for i, (v, x, y) in enumerate(values):
+            yc = special.jv(v, x)
+            assert_almost_equal(yc, y, 8, err_msg='test #%d' % i)
+
+    def test_negv_jve(self):
+        assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14)
+
+    def test_jve(self):
+        jvexp = special.jve(1,.2)
+        assert_almost_equal(jvexp,0.099500832639235995,8)
+        jvexp1 = special.jve(1,.2+1j)
+        z = .2+1j
+        jvexpr = special.jv(1,z)*exp(-abs(z.imag))
+        assert_almost_equal(jvexp1,jvexpr,8)
+
+    def test_jn_zeros(self):
+        jn0 = special.jn_zeros(0,5)
+        jn1 = special.jn_zeros(1,5)
+        assert_array_almost_equal(jn0,array([2.4048255577,
+                                              5.5200781103,
+                                              8.6537279129,
+                                              11.7915344391,
+                                              14.9309177086]),4)
+        assert_array_almost_equal(jn1,array([3.83171,
+                                              7.01559,
+                                              10.17347,
+                                              13.32369,
+                                              16.47063]),4)
+
+        jn102 = special.jn_zeros(102,5)
+        assert_allclose(jn102, array([110.89174935992040343,
+                                       117.83464175788308398,
+                                       123.70194191713507279,
+                                       129.02417238949092824,
+                                       134.00114761868422559]), rtol=1e-13)
+
+        jn301 = special.jn_zeros(301,5)
+        assert_allclose(jn301, array([313.59097866698830153,
+                                       323.21549776096288280,
+                                       331.22338738656748796,
+                                       338.39676338872084500,
+                                       345.03284233056064157]), rtol=1e-13)
+
+    def test_jn_zeros_slow(self):
+        jn0 = special.jn_zeros(0, 300)
+        assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13)
+        assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13)
+        assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13)
+
+        jn10 = special.jn_zeros(10, 300)
+        assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13)
+        assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13)
+        assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13)
+
+        jn3010 = special.jn_zeros(3010,5)
+        assert_allclose(jn3010, array([3036.86590780927,
+                                        3057.06598526482,
+                                        3073.66360690272,
+                                        3088.37736494778,
+                                        3101.86438139042]), rtol=1e-8)
+
+    def test_jnjnp_zeros(self):
+        jn = special.jn
+
+        def jnp(n, x):
+            return (jn(n-1,x) - jn(n+1,x))/2
+        for nt in range(1, 30):
+            z, n, m, t = special.jnjnp_zeros(nt)
+            for zz, nn, tt in zip(z, n, t):
+                if tt == 0:
+                    assert_allclose(jn(nn, zz), 0, atol=1e-6)
+                elif tt == 1:
+                    assert_allclose(jnp(nn, zz), 0, atol=1e-6)
+                else:
+                    raise AssertionError("Invalid t return for nt=%d" % nt)
+
+    def test_jnp_zeros(self):
+        jnp = special.jnp_zeros(1,5)
+        assert_array_almost_equal(jnp, array([1.84118,
+                                                5.33144,
+                                                8.53632,
+                                                11.70600,
+                                                14.86359]),4)
+        jnp = special.jnp_zeros(443,5)
+        assert_allclose(special.jvp(443, jnp), 0, atol=1e-15)
+
+    def test_jnyn_zeros(self):
+        jnz = special.jnyn_zeros(1,5)
+        assert_array_almost_equal(jnz,(array([3.83171,
+                                                7.01559,
+                                                10.17347,
+                                                13.32369,
+                                                16.47063]),
+                                       array([1.84118,
+                                                5.33144,
+                                                8.53632,
+                                                11.70600,
+                                                14.86359]),
+                                       array([2.19714,
+                                                5.42968,
+                                                8.59601,
+                                                11.74915,
+                                                14.89744]),
+                                       array([3.68302,
+                                                6.94150,
+                                                10.12340,
+                                                13.28576,
+                                                16.44006])),5)
+
+    def test_jvp(self):
+        jvprim = special.jvp(2,2)
+        jv0 = (special.jv(1,2)-special.jv(3,2))/2
+        assert_almost_equal(jvprim,jv0,10)
+
+    def test_k0(self):
+        ozk = special.k0(.1)
+        ozkr = special.kv(0,.1)
+        assert_almost_equal(ozk,ozkr,8)
+
+    def test_k0e(self):
+        ozke = special.k0e(.1)
+        ozker = special.kve(0,.1)
+        assert_almost_equal(ozke,ozker,8)
+
+    def test_k1(self):
+        o1k = special.k1(.1)
+        o1kr = special.kv(1,.1)
+        assert_almost_equal(o1k,o1kr,8)
+
+    def test_k1e(self):
+        o1ke = special.k1e(.1)
+        o1ker = special.kve(1,.1)
+        assert_almost_equal(o1ke,o1ker,8)
+
+    def test_jacobi(self):
+        a = 5*np.random.random() - 1
+        b = 5*np.random.random() - 1
+        P0 = special.jacobi(0,a,b)
+        P1 = special.jacobi(1,a,b)
+        P2 = special.jacobi(2,a,b)
+        P3 = special.jacobi(3,a,b)
+
+        assert_array_almost_equal(P0.c,[1],13)
+        assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13)
+        cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)]
+        p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]]
+        assert_array_almost_equal(P2.c,array(p2c)/8.0,13)
+        cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3),
+              12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)]
+        p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]]
+        assert_array_almost_equal(P3.c,array(p3c)/48.0,13)
+
+    def test_kn(self):
+        kn1 = special.kn(0,.2)
+        assert_almost_equal(kn1,1.7527038555281462,8)
+
+    def test_negv_kv(self):
+        assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2))
+
+    def test_kv0(self):
+        kv0 = special.kv(0,.2)
+        assert_almost_equal(kv0, 1.7527038555281462, 10)
+
+    def test_kv1(self):
+        kv1 = special.kv(1,0.2)
+        assert_almost_equal(kv1, 4.775972543220472, 10)
+
+    def test_kv2(self):
+        kv2 = special.kv(2,0.2)
+        assert_almost_equal(kv2, 49.51242928773287, 10)
+
+    def test_kn_largeorder(self):
+        assert_allclose(special.kn(32, 1), 1.7516596664574289e+43)
+
+    def test_kv_largearg(self):
+        assert_equal(special.kv(0, 1e19), 0)
+
+    def test_negv_kve(self):
+        assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2))
+
+    def test_kve(self):
+        kve1 = special.kve(0,.2)
+        kv1 = special.kv(0,.2)*exp(.2)
+        assert_almost_equal(kve1,kv1,8)
+        z = .2+1j
+        kve2 = special.kve(0,z)
+        kv2 = special.kv(0,z)*exp(z)
+        assert_almost_equal(kve2,kv2,8)
+
+    def test_kvp_v0n1(self):
+        z = 2.2
+        assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10)
+
+    def test_kvp_n1(self):
+        v = 3.
+        z = 2.2
+        xc = -special.kv(v+1,z) + v/z*special.kv(v,z)
+        x = special.kvp(v,z, n=1)
+        assert_almost_equal(xc, x, 10)   # this function (kvp) is broken
+
+    def test_kvp_n2(self):
+        v = 3.
+        z = 2.2
+        xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z
+        x = special.kvp(v, z, n=2)
+        assert_almost_equal(xc, x, 10)
+
+    def test_y0(self):
+        oz = special.y0(.1)
+        ozr = special.yn(0,.1)
+        assert_almost_equal(oz,ozr,8)
+
+    def test_y1(self):
+        o1 = special.y1(.1)
+        o1r = special.yn(1,.1)
+        assert_almost_equal(o1,o1r,8)
+
+    def test_y0_zeros(self):
+        yo,ypo = special.y0_zeros(2)
+        zo,zpo = special.y0_zeros(2,complex=1)
+        all = r_[yo,zo]
+        allval = r_[ypo,zpo]
+        assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11)
+        assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11)
+
+    def test_y1_zeros(self):
+        y1 = special.y1_zeros(1)
+        assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5)
+
+    def test_y1p_zeros(self):
+        y1p = special.y1p_zeros(1,complex=1)
+        assert_array_almost_equal(
+            y1p,
+            (array([0.5768+0.904j]), array([-0.7635+0.5892j])),
+            3,
+        )
+
+    def test_yn_zeros(self):
+        an = special.yn_zeros(4,2)
+        assert_array_almost_equal(an,array([5.64515, 9.36162]),5)
+        an = special.yn_zeros(443,5)
+        assert_allclose(an, [450.13573091578090314,
+                             463.05692376675001542,
+                             472.80651546418663566,
+                             481.27353184725625838,
+                             488.98055964441374646],
+                        rtol=1e-15,)
+
+    def test_ynp_zeros(self):
+        ao = special.ynp_zeros(0,2)
+        assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6)
+        ao = special.ynp_zeros(43,5)
+        assert_allclose(special.yvp(43, ao), 0, atol=1e-15)
+        ao = special.ynp_zeros(443,5)
+        assert_allclose(special.yvp(443, ao), 0, atol=1e-9)
+
+    def test_ynp_zeros_large_order(self):
+        ao = special.ynp_zeros(443,5)
+        assert_allclose(special.yvp(443, ao), 0, atol=1e-14)
+
+    def test_yn(self):
+        yn2n = special.yn(1,.2)
+        assert_almost_equal(yn2n,-3.3238249881118471,8)
+
+    def test_yn_gh_20405(self):
+        # Enforce correct asymptotic behavior for large n.
+        observed = cephes.yn(500, 1)
+        assert observed == -np.inf
+
+    def test_negv_yv(self):
+        assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14)
+
+    def test_yv(self):
+        yv2 = special.yv(1,.2)
+        assert_almost_equal(yv2,-3.3238249881118471,8)
+
+    def test_negv_yve(self):
+        assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14)
+
+    def test_yve(self):
+        yve2 = special.yve(1,.2)
+        assert_almost_equal(yve2,-3.3238249881118471,8)
+        yve2r = special.yv(1,.2+1j)*exp(-1)
+        yve22 = special.yve(1,.2+1j)
+        assert_almost_equal(yve22,yve2r,8)
+
+    def test_yvp(self):
+        yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0
+        yvp1 = special.yvp(2,.2)
+        assert_array_almost_equal(yvp1,yvpr,10)
+
+    def _cephes_vs_amos_points(self):
+        """Yield points at which to compare Cephes implementation to AMOS"""
+        # check several points, including large-amplitude ones
+        v = [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]
+        z = [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300,
+             10003]
+        yield from itertools.product(v, z)
+
+        # check half-integers; these are problematic points at least
+        # for cephes/iv
+        yield from itertools.product(0.5 + arange(-60, 60), [3.5])
+
+    def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None):
+        for v, z in self._cephes_vs_amos_points():
+            if skip is not None and skip(v, z):
+                continue
+            c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z)
+            if np.isinf(c1):
+                assert_(np.abs(c2) >= 1e300, (v, z))
+            elif np.isnan(c1):
+                assert_(c2.imag != 0, (v, z))
+            else:
+                assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol)
+                if v == int(v):
+                    assert_allclose(c3, c2, err_msg=(v, z),
+                                     rtol=rtol, atol=atol)
+
+    @pytest.mark.xfail(platform.machine() == 'ppc64le',
+                       reason="fails on ppc64le")
+    def test_jv_cephes_vs_amos(self):
+        self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305)
+
+    @pytest.mark.xfail(platform.machine() == 'ppc64le',
+                       reason="fails on ppc64le")
+    def test_yv_cephes_vs_amos(self):
+        self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305)
+
+    def test_yv_cephes_vs_amos_only_small_orders(self):
+        def skipper(v, z):
+            return abs(v) > 50
+        self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305,
+                                  skip=skipper)
+
+    def test_iv_cephes_vs_amos(self):
+        with np.errstate(all='ignore'):
+            self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305)
+
+    @pytest.mark.slow
+    def test_iv_cephes_vs_amos_mass_test(self):
+        N = 1000000
+        np.random.seed(1)
+        v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N)
+        x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N)
+
+        imsk = (np.random.randint(8, size=N) == 0)
+        v[imsk] = v[imsk].astype(np.int64)
+
+        with np.errstate(all='ignore'):
+            c1 = special.iv(v, x)
+            c2 = special.iv(v, x+0j)
+
+            # deal with differences in the inf and zero cutoffs
+            c1[abs(c1) > 1e300] = np.inf
+            c2[abs(c2) > 1e300] = np.inf
+            c1[abs(c1) < 1e-300] = 0
+            c2[abs(c2) < 1e-300] = 0
+
+            dc = abs(c1/c2 - 1)
+            dc[np.isnan(dc)] = 0
+
+        k = np.argmax(dc)
+
+        # Most error apparently comes from AMOS and not our implementation;
+        # there are some problems near integer orders there
+        assert_(
+            dc[k] < 2e-7,
+            (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))
+        )
+
+    def test_kv_cephes_vs_amos(self):
+        self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305)
+        self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305)
+
+    def test_ticket_623(self):
+        assert_allclose(special.jv(3, 4), 0.43017147387562193)
+        assert_allclose(special.jv(301, 1300), 0.0183487151115275)
+        assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048)
+
+    def test_ticket_853(self):
+        """Negative-order Bessels"""
+        # cephes
+        assert_allclose(special.jv(-1, 1), -0.4400505857449335)
+        assert_allclose(special.jv(-2, 1), 0.1149034849319005)
+        assert_allclose(special.yv(-1, 1), 0.7812128213002887)
+        assert_allclose(special.yv(-2, 1), -1.650682606816255)
+        assert_allclose(special.iv(-1, 1), 0.5651591039924851)
+        assert_allclose(special.iv(-2, 1), 0.1357476697670383)
+        assert_allclose(special.kv(-1, 1), 0.6019072301972347)
+        assert_allclose(special.kv(-2, 1), 1.624838898635178)
+        assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952)
+        assert_allclose(special.yv(-0.5, 1), 0.6713967071418031)
+        assert_allclose(special.iv(-0.5, 1), 1.231200214592967)
+        assert_allclose(special.kv(-0.5, 1), 0.4610685044478945)
+        # amos
+        assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335)
+        assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005)
+        assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887)
+        assert_allclose(special.yv(-2, 1+0j), -1.650682606816255)
+
+        assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851)
+        assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383)
+        assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347)
+        assert_allclose(special.kv(-2, 1+0j), 1.624838898635178)
+
+        assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952)
+        assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j)
+        assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031)
+        assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j)
+
+        assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967)
+        assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j)
+        assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945)
+        assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j)
+
+        assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3))
+        assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3))
+        assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3))
+        assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j))
+
+        assert_allclose(
+            special.hankel1(-0.5, 1+1j),
+            special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)
+        )
+        assert_allclose(
+            special.hankel2(-0.5, 1+1j),
+            special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)
+        )
+
+    def test_ticket_854(self):
+        """Real-valued Bessel domains"""
+        assert_(isnan(special.jv(0.5, -1)))
+        assert_(isnan(special.iv(0.5, -1)))
+        assert_(isnan(special.yv(0.5, -1)))
+        assert_(isnan(special.yv(1, -1)))
+        assert_(isnan(special.kv(0.5, -1)))
+        assert_(isnan(special.kv(1, -1)))
+        assert_(isnan(special.jve(0.5, -1)))
+        assert_(isnan(special.ive(0.5, -1)))
+        assert_(isnan(special.yve(0.5, -1)))
+        assert_(isnan(special.yve(1, -1)))
+        assert_(isnan(special.kve(0.5, -1)))
+        assert_(isnan(special.kve(1, -1)))
+        assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1))
+        assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1))
+
+    def test_gh_7909(self):
+        assert_(special.kv(1.5, 0) == np.inf)
+        assert_(special.kve(1.5, 0) == np.inf)
+
+    def test_ticket_503(self):
+        """Real-valued Bessel I overflow"""
+        assert_allclose(special.iv(1, 700), 1.528500390233901e302)
+        assert_allclose(special.iv(1000, 1120), 1.301564549405821e301)
+
+    def test_iv_hyperg_poles(self):
+        assert_allclose(special.iv(-0.5, 1), 1.231200214592967)
+
+    def iv_series(self, v, z, n=200):
+        k = arange(0, n).astype(double)
+        r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1)
+        r[isnan(r)] = inf
+        r = exp(r)
+        err = abs(r).max() * finfo(double).eps * n + abs(r[-1])*10
+        return r.sum(), err
+
+    def test_i0_series(self):
+        for z in [1., 10., 200.5]:
+            value, err = self.iv_series(0, z)
+            assert_allclose(special.i0(z), value, atol=err, err_msg=z)
+
+    def test_i1_series(self):
+        for z in [1., 10., 200.5]:
+            value, err = self.iv_series(1, z)
+            assert_allclose(special.i1(z), value, atol=err, err_msg=z)
+
+    def test_iv_series(self):
+        for v in [-20., -10., -1., 0., 1., 12.49, 120.]:
+            for z in [1., 10., 200.5, -1+2j]:
+                value, err = self.iv_series(v, z)
+                assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z))
+
+    def test_i0(self):
+        values = [[0.0, 1.0],
+                  [1e-10, 1.0],
+                  [0.1, 0.9071009258],
+                  [0.5, 0.6450352706],
+                  [1.0, 0.4657596077],
+                  [2.5, 0.2700464416],
+                  [5.0, 0.1835408126],
+                  [20.0, 0.0897803119],
+                  ]
+        for i, (x, v) in enumerate(values):
+            cv = special.i0(x) * exp(-x)
+            assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
+
+    def test_i0e(self):
+        oize = special.i0e(.1)
+        oizer = special.ive(0,.1)
+        assert_almost_equal(oize,oizer,8)
+
+    def test_i1(self):
+        values = [[0.0, 0.0],
+                  [1e-10, 0.4999999999500000e-10],
+                  [0.1, 0.0452984468],
+                  [0.5, 0.1564208032],
+                  [1.0, 0.2079104154],
+                  [5.0, 0.1639722669],
+                  [20.0, 0.0875062222],
+                  ]
+        for i, (x, v) in enumerate(values):
+            cv = special.i1(x) * exp(-x)
+            assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
+
+    def test_i1e(self):
+        oi1e = special.i1e(.1)
+        oi1er = special.ive(1,.1)
+        assert_almost_equal(oi1e,oi1er,8)
+
+    def test_iti0k0(self):
+        iti0 = array(special.iti0k0(5))
+        assert_array_almost_equal(
+            iti0,
+            array([31.848667776169801, 1.5673873907283657]),
+            5,
+        )
+
+    def test_it2i0k0(self):
+        it2k = special.it2i0k0(.1)
+        assert_array_almost_equal(
+            it2k,
+            array([0.0012503906973464409, 3.3309450354686687]),
+            6,
+        )
+
+    def test_iv(self):
+        iv1 = special.iv(0,.1)*exp(-.1)
+        assert_almost_equal(iv1,0.90710092578230106,10)
+
+    def test_negv_ive(self):
+        assert_equal(special.ive(3,2), special.ive(-3,2))
+
+    def test_ive(self):
+        ive1 = special.ive(0,.1)
+        iv1 = special.iv(0,.1)*exp(-.1)
+        assert_almost_equal(ive1,iv1,10)
+
+    def test_ivp0(self):
+        assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10)
+
+    def test_ivp(self):
+        y = (special.iv(0,2) + special.iv(2,2))/2
+        x = special.ivp(1,2)
+        assert_almost_equal(x,y,10)
+
+
+class TestLaguerre:
+    def test_laguerre(self):
+        lag0 = special.laguerre(0)
+        lag1 = special.laguerre(1)
+        lag2 = special.laguerre(2)
+        lag3 = special.laguerre(3)
+        lag4 = special.laguerre(4)
+        lag5 = special.laguerre(5)
+        assert_array_almost_equal(lag0.c,[1],13)
+        assert_array_almost_equal(lag1.c,[-1,1],13)
+        assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13)
+        assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13)
+        assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13)
+        assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13)
+
+    def test_genlaguerre(self):
+        k = 5*np.random.random() - 0.9
+        lag0 = special.genlaguerre(0,k)
+        lag1 = special.genlaguerre(1,k)
+        lag2 = special.genlaguerre(2,k)
+        lag3 = special.genlaguerre(3,k)
+        assert_equal(lag0.c, [1])
+        assert_equal(lag1.c, [-1, k + 1])
+        assert_almost_equal(
+            lag2.c,
+            array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0
+        )
+        assert_almost_equal(
+            lag3.c,
+            array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0
+        )
+
+
+class TestLambda:
+    def test_lmbda(self):
+        lam = special.lmbda(1,.1)
+        lamr = (
+            array([special.jn(0,.1), 2*special.jn(1,.1)/.1]),
+            array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])
+        )
+        assert_array_almost_equal(lam,lamr,8)
+
+
+class TestLog1p:
+    def test_log1p(self):
+        l1p = (special.log1p(10), special.log1p(11), special.log1p(12))
+        l1prl = (log(11), log(12), log(13))
+        assert_array_almost_equal(l1p,l1prl,8)
+
+    def test_log1pmore(self):
+        l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2))
+        l1pmrl = (log(2),log(2.1),log(2.2))
+        assert_array_almost_equal(l1pm,l1pmrl,8)
+
+
+class TestMathieu:
+
+    def test_mathieu_a(self):
+        pass
+
+    def test_mathieu_even_coef(self):
+        special.mathieu_even_coef(2,5)
+        # Q not defined broken and cannot figure out proper reporting order
+
+    def test_mathieu_odd_coef(self):
+        # same problem as above
+        pass
+
+
+class TestFresnelIntegral:
+
+    def test_modfresnelp(self):
+        pass
+
+    def test_modfresnelm(self):
+        pass
+
+
+class TestOblCvSeq:
+    def test_obl_cv_seq(self):
+        obl = special.obl_cv_seq(0,3,1)
+        assert_array_almost_equal(obl,array([-0.348602,
+                                              1.393206,
+                                              5.486800,
+                                              11.492120]),5)
+
+
+class TestParabolicCylinder:
+    def test_pbdn_seq(self):
+        pb = special.pbdn_seq(1,.1)
+        assert_array_almost_equal(pb,(array([0.9975,
+                                              0.0998]),
+                                      array([-0.0499,
+                                             0.9925])),4)
+
+    def test_pbdv(self):
+        special.pbdv(1,.2)
+        1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0]
+
+    def test_pbdv_seq(self):
+        pbn = special.pbdn_seq(1,.1)
+        pbv = special.pbdv_seq(1,.1)
+        assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4)
+
+    def test_pbdv_points(self):
+        # simple case
+        eta = np.linspace(-10, 10, 5)
+        z = 2**(eta/2)*np.sqrt(np.pi)*special.rgamma(.5-.5*eta)
+        assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14)
+
+        # some points
+        assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12)
+        assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12)
+
+    def test_pbdv_gradient(self):
+        x = np.linspace(-4, 4, 8)[:,None]
+        eta = np.linspace(-10, 10, 5)[None,:]
+
+        p = special.pbdv(eta, x)
+        eps = 1e-7 + 1e-7*abs(x)
+        dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2.
+        assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6)
+
+    def test_pbvv_gradient(self):
+        x = np.linspace(-4, 4, 8)[:,None]
+        eta = np.linspace(-10, 10, 5)[None,:]
+
+        p = special.pbvv(eta, x)
+        eps = 1e-7 + 1e-7*abs(x)
+        dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2.
+        assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6)
+
+    def test_pbvv_seq(self):
+        res1, res2 = special.pbvv_seq(2, 3)
+        assert_allclose(res1, np.array([2.976319645712036,
+                                        1.358840996329579,
+                                        0.5501016716383508]))
+        assert_allclose(res2, np.array([3.105638472238475,
+                                        0.9380581512176672,
+                                        0.533688488872053]))
+
+
+class TestPolygamma:
+    # from Table 6.2 (pg. 271) of A&S
+    def test_polygamma(self):
+        poly2 = special.polygamma(2,1)
+        poly3 = special.polygamma(3,1)
+        assert_almost_equal(poly2,-2.4041138063,10)
+        assert_almost_equal(poly3,6.4939394023,10)
+
+        # Test polygamma(0, x) == psi(x)
+        x = [2, 3, 1.1e14]
+        assert_almost_equal(special.polygamma(0, x), special.psi(x))
+
+        # Test broadcasting
+        n = [0, 1, 2]
+        x = [0.5, 1.5, 2.5]
+        expected = [-1.9635100260214238, 0.93480220054467933,
+                    -0.23620405164172739]
+        assert_almost_equal(special.polygamma(n, x), expected)
+        expected = np.vstack([expected]*2)
+        assert_almost_equal(special.polygamma(n, np.vstack([x]*2)),
+                            expected)
+        assert_almost_equal(special.polygamma(np.vstack([n]*2), x),
+                            expected)
+
+
+class TestProCvSeq:
+    def test_pro_cv_seq(self):
+        prol = special.pro_cv_seq(0,3,1)
+        assert_array_almost_equal(prol,array([0.319000,
+                                               2.593084,
+                                               6.533471,
+                                               12.514462]),5)
+
+
+class TestPsi:
+    def test_psi(self):
+        ps = special.psi(1)
+        assert_almost_equal(ps,-0.57721566490153287,8)
+
+
+class TestRadian:
+    def test_radian(self):
+        rad = special.radian(90,0,0)
+        assert_almost_equal(rad,pi/2.0,5)
+
+    def test_radianmore(self):
+        rad1 = special.radian(90,1,60)
+        assert_almost_equal(rad1,pi/2+0.0005816135199345904,5)
+
+
+class TestRiccati:
+    def test_riccati_jn(self):
+        N, x = 2, 0.2
+        S = np.empty((N, N))
+        for n in range(N):
+            j = special.spherical_jn(n, x)
+            jp = special.spherical_jn(n, x, derivative=True)
+            S[0,n] = x*j
+            S[1,n] = x*jp + j
+        assert_array_almost_equal(S, special.riccati_jn(n, x), 8)
+
+    def test_riccati_yn(self):
+        N, x = 2, 0.2
+        C = np.empty((N, N))
+        for n in range(N):
+            y = special.spherical_yn(n, x)
+            yp = special.spherical_yn(n, x, derivative=True)
+            C[0,n] = x*y
+            C[1,n] = x*yp + y
+        assert_array_almost_equal(C, special.riccati_yn(n, x), 8)
+
+
+class TestSoftplus:
+    def test_softplus(self):
+        # Test cases for the softplus function. Selected based on Eq.(10) of:
+        # Mächler, M. (2012). log1mexp-note.pdf. Rmpfr: R MPFR - Multiple Precision
+        # Floating-Point Reliable. Retrieved from:
+        # https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf
+        # Reference values computed with `mpmath`
+        import numpy as np
+        rng = np.random.default_rng(3298432985245)
+        n = 3
+        a1 = rng.uniform(-100, -37, size=n)
+        a2 = rng.uniform(-37, 18, size=n)
+        a3 = rng.uniform(18, 33.3, size=n)
+        a4 = rng.uniform(33.33, 100, size=n)
+        a = np.stack([a1, a2, a3, a4])
+
+        # from mpmath import mp
+        # mp.dps = 100
+        # @np.vectorize
+        # def softplus(x):
+        #     return float(mp.log(mp.one + mp.exp(x)))
+        # softplus(a).tolist()
+        ref = [[1.692721323272333e-42, 7.42673911145206e-41, 8.504608846033205e-35],
+               [1.8425343736349797, 9.488245799395577e-15, 7.225195764021444e-08],
+               [31.253760266045106, 27.758244090327832, 29.995959179643634],
+               [73.26040086468937, 76.24944728617226, 37.83955519155184]]
+
+        res = softplus(a)
+        assert_allclose(res, ref, rtol=2e-15)
+
+    def test_softplus_with_kwargs(self):
+        x = np.arange(5) - 2
+        out = np.ones(5)
+        ref = out.copy()
+        where = x > 0
+
+        softplus(x, out=out, where=where)
+        ref[where] = softplus(x[where])
+        assert_allclose(out, ref)
+
+
+class TestRound:
+    def test_round(self):
+        rnd = list(map(int, (special.round(10.1),
+                             special.round(10.4),
+                             special.round(10.5),
+                             special.round(10.6))))
+
+        # Note: According to the documentation, scipy.special.round is
+        # supposed to round to the nearest even number if the fractional
+        # part is exactly 0.5. On some platforms, this does not appear
+        # to work and thus this test may fail. However, this unit test is
+        # correctly written.
+        rndrl = (10,10,10,11)
+        assert_array_equal(rnd,rndrl)
+
+# sph_harm is deprecated and is implemented as a shim around sph_harm_y.
+# The following two tests are maintained to verify the correctness of the shim.
+
+def test_sph_harm():
+    # Tests derived from tables in
+    # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics
+    sh = special.sph_harm
+    pi = np.pi
+    exp = np.exp
+    sqrt = np.sqrt
+    sin = np.sin
+    cos = np.cos
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        assert_array_almost_equal(sh(0,0,0,0),
+               0.5/sqrt(pi))
+        assert_array_almost_equal(sh(-2,2,0.,pi/4),
+               0.25*sqrt(15./(2.*pi)) *
+               (sin(pi/4))**2.)
+        assert_array_almost_equal(sh(-2,2,0.,pi/2),
+               0.25*sqrt(15./(2.*pi)))
+        assert_array_almost_equal(sh(2,2,pi,pi/2),
+               0.25*sqrt(15/(2.*pi)) *
+               exp(0+2.*pi*1j)*sin(pi/2.)**2.)
+        assert_array_almost_equal(sh(2,4,pi/4.,pi/3.),
+               (3./8.)*sqrt(5./(2.*pi)) *
+               exp(0+2.*pi/4.*1j) *
+               sin(pi/3.)**2. *
+               (7.*cos(pi/3.)**2.-1))
+        assert_array_almost_equal(sh(4,4,pi/8.,pi/6.),
+               (3./16.)*sqrt(35./(2.*pi)) *
+               exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.)
+
+
+def test_sph_harm_ufunc_loop_selection():
+    # see https://github.com/scipy/scipy/issues/4895
+    dt = np.dtype(np.complex128)
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt)
+        assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt)
+        assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt)
+        assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt)
+        assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt)
+        assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt)
+
+
+class TestStruve:
+    def _series(self, v, z, n=100):
+        """Compute Struve function & error estimate from its power series."""
+        k = arange(0, n)
+        r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5)
+        err = abs(r).max() * finfo(double).eps * n
+        return r.sum(), err
+
+    def test_vs_series(self):
+        """Check Struve function versus its power series"""
+        for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]:
+            for z in [1, 10, 19, 21, 30]:
+                value, err = self._series(v, z)
+                assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z)
+
+    def test_some_values(self):
+        assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7)
+        assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8)
+        assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12)
+        assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11)
+        assert_equal(special.struve(-12, -41), -special.struve(-12, 41))
+        assert_equal(special.struve(+12, -41), -special.struve(+12, 41))
+        assert_equal(special.struve(-11, -41), +special.struve(-11, 41))
+        assert_equal(special.struve(+11, -41), +special.struve(+11, 41))
+
+        assert_(isnan(special.struve(-7.1, -1)))
+        assert_(isnan(special.struve(-10.1, -1)))
+
+    def test_regression_679(self):
+        """Regression test for #679"""
+        assert_allclose(special.struve(-1.0, 20 - 1e-8),
+                        special.struve(-1.0, 20 + 1e-8))
+        assert_allclose(special.struve(-2.0, 20 - 1e-8),
+                        special.struve(-2.0, 20 + 1e-8))
+        assert_allclose(special.struve(-4.3, 20 - 1e-8),
+                        special.struve(-4.3, 20 + 1e-8))
+
+
+def test_chi2_smalldf():
+    assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110)
+
+
+def test_ch2_inf():
+    assert_equal(special.chdtr(0.7,np.inf), 1.0)
+
+
+def test_chi2c_smalldf():
+    assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110)
+
+
+def test_chi2_inv_smalldf():
+    assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3)
+
+
+def test_agm_simple():
+    rtol = 1e-13
+
+    # Gauss's constant
+    assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186,
+                    rtol=rtol)
+
+    # These values were computed using Wolfram Alpha, with the
+    # function ArithmeticGeometricMean[a, b].
+    agm13 = 1.863616783244897
+    agm15 = 2.604008190530940
+    agm35 = 3.936235503649555
+    assert_allclose(special.agm([[1], [3]], [1, 3, 5]),
+                    [[1, agm13, agm15],
+                     [agm13, 3, agm35]], rtol=rtol)
+
+    # Computed by the iteration formula using mpmath,
+    # with mpmath.mp.prec = 1000:
+    agm12 = 1.4567910310469068
+    assert_allclose(special.agm(1, 2), agm12, rtol=rtol)
+    assert_allclose(special.agm(2, 1), agm12, rtol=rtol)
+    assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol)
+    assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol)
+    assert_allclose(special.agm(13, 123456789.5), 11111458.498599306,
+                    rtol=rtol)
+    assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol)
+    assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol)
+    assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178,
+                    rtol=rtol)
+    assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177,
+                    rtol=rtol)
+    assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152,
+                    rtol=rtol)
+    fi = np.finfo(1.0)
+    assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305,
+                    rtol=rtol)
+    assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308,
+                    rtol=rtol)
+    assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308,
+                    rtol=rtol)
+
+    # zero, nan and inf cases.
+    assert_equal(special.agm(0, 0), 0)
+    assert_equal(special.agm(99, 0), 0)
+
+    assert_equal(special.agm(-1, 10), np.nan)
+    assert_equal(special.agm(0, np.inf), np.nan)
+    assert_equal(special.agm(np.inf, 0), np.nan)
+    assert_equal(special.agm(0, -np.inf), np.nan)
+    assert_equal(special.agm(-np.inf, 0), np.nan)
+    assert_equal(special.agm(np.inf, -np.inf), np.nan)
+    assert_equal(special.agm(-np.inf, np.inf), np.nan)
+    assert_equal(special.agm(1, np.nan), np.nan)
+    assert_equal(special.agm(np.nan, -1), np.nan)
+
+    assert_equal(special.agm(1, np.inf), np.inf)
+    assert_equal(special.agm(np.inf, 1), np.inf)
+    assert_equal(special.agm(-1, -np.inf), -np.inf)
+    assert_equal(special.agm(-np.inf, -1), -np.inf)
+
+
+def test_legacy():
+    # Legacy behavior: truncating arguments to integers
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "floating point number truncated to an integer")
+        assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3))
+        assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3))
+        assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3))
+        assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3))
+        assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3))
+        assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3))
+        assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3))
+        assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3))
+        assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3))
+
+
+# This lock can be removed once errstate is made thread-safe (see gh-21956)
+@pytest.fixture
+def errstate_lock():
+    import threading
+    return threading.Lock()
+
+
+@with_special_errors
+def test_error_raising(errstate_lock):
+    with errstate_lock:
+        with special.errstate(all='raise'):
+            assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j)
+
+
+def test_xlogy():
+    def xfunc(x, y):
+        with np.errstate(invalid='ignore'):
+            if x == 0 and not np.isnan(y):
+                return x
+            else:
+                return x*np.log(y)
+
+    z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float)
+    z2 = np.r_[z1, [(0, 1j), (1, 1j)]]
+
+    w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1])
+    assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13)
+    w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1])
+    assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13)
+
+
+def test_xlog1py():
+    def xfunc(x, y):
+        with np.errstate(invalid='ignore'):
+            if x == 0 and not np.isnan(y):
+                return x
+            else:
+                return x * np.log1p(y)
+
+    z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0),
+                     (1, 1e-30)], dtype=float)
+    w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1])
+    assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13)
+
+
+def test_entr():
+    def xfunc(x):
+        if x < 0:
+            return -np.inf
+        else:
+            return -special.xlogy(x, x)
+    values = (0, 0.5, 1.0, np.inf)
+    signs = [-1, 1]
+    arr = []
+    for sgn, v in itertools.product(signs, values):
+        arr.append(sgn * v)
+    z = np.array(arr, dtype=float)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z)
+    assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_kl_div():
+    def xfunc(x, y):
+        if x < 0 or y < 0 or (y == 0 and x != 0):
+            # extension of natural domain to preserve convexity
+            return np.inf
+        elif np.isposinf(x) or np.isposinf(y):
+            # limits within the natural domain
+            return np.inf
+        elif x == 0:
+            return y
+        else:
+            return special.xlogy(x, x/y) - x + y
+    values = (0, 0.5, 1.0)
+    signs = [-1, 1]
+    arr = []
+    for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values):
+        arr.append((sgna*va, sgnb*vb))
+    z = np.array(arr, dtype=float)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_rel_entr():
+    def xfunc(x, y):
+        if x > 0 and y > 0:
+            return special.xlogy(x, x/y)
+        elif x == 0 and y >= 0:
+            return 0
+        else:
+            return np.inf
+    values = (0, 0.5, 1.0)
+    signs = [-1, 1]
+    arr = []
+    for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values):
+        arr.append((sgna*va, sgnb*vb))
+    z = np.array(arr, dtype=float)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_rel_entr_gh_20710_near_zero():
+    # Check accuracy of inputs which are very close
+    inputs = np.array([
+        # x, y
+        (0.9456657713430001, 0.9456657713430094),
+        (0.48066098564791515, 0.48066098564794774),
+        (0.786048657854401, 0.7860486578542367),
+    ])
+    # Known values produced using `x * mpmath.log(x / y)` with dps=30
+    expected = [
+        -9.325873406851269e-15,
+        -3.258504577274724e-14,
+        1.6431300764454033e-13,
+    ]
+    x = inputs[:, 0]
+    y = inputs[:, 1]
+    assert_allclose(special.rel_entr(x, y), expected, rtol=1e-13, atol=0)
+
+
+def test_rel_entr_gh_20710_overflow():
+    special.seterr(all='ignore')
+    inputs = np.array([
+        # x, y
+        # Overflow
+        (4, 2.22e-308),
+        # Underflow
+        (1e-200, 1e+200),
+        # Subnormal
+        (2.22e-308, 1e15),
+    ])
+    # Known values produced using `x * mpmath.log(x / y)` with dps=30
+    expected = [
+        2839.139983229607,
+        -9.210340371976183e-198,
+        -1.6493212008074475e-305,
+    ]
+    x = inputs[:, 0]
+    y = inputs[:, 1]
+    assert_allclose(special.rel_entr(x, y), expected, rtol=1e-13, atol=0)
+
+
+def test_huber():
+    assert_equal(special.huber(-1, 1.5), np.inf)
+    assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5))
+    assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2))
+
+    def xfunc(delta, r):
+        if delta < 0:
+            return np.inf
+        elif np.abs(r) < delta:
+            return 0.5 * np.square(r)
+        else:
+            return delta * (np.abs(r) - 0.5 * delta)
+
+    z = np.random.randn(10, 2)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_pseudo_huber():
+    def xfunc(delta, r):
+        if delta < 0:
+            return np.inf
+        elif (not delta) or (not r):
+            return 0
+        else:
+            return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1)
+
+    z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]])
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_pseudo_huber_small_r():
+    delta = 1.0
+    r = 1e-18
+    y = special.pseudo_huber(delta, r)
+    # expected computed with mpmath:
+    #     import mpmath
+    #     mpmath.mp.dps = 200
+    #     r = mpmath.mpf(1e-18)
+    #     expected = float(mpmath.sqrt(1 + r**2) - 1)
+    expected = 5.0000000000000005e-37
+    assert_allclose(y, expected, rtol=1e-13)
+
+
+@pytest.mark.thread_unsafe
+def test_runtime_warning():
+    with pytest.warns(RuntimeWarning,
+                      match=r'Too many predicted coefficients'):
+        mathieu_odd_coef(1000, 1000)
+    with pytest.warns(RuntimeWarning,
+                      match=r'Too many predicted coefficients'):
+        mathieu_even_coef(1000, 1000)
+
+
+class TestStirling2:
+    table = [
+        [1],
+        [0, 1],
+        [0, 1, 1],
+        [0, 1, 3, 1],
+        [0, 1, 7, 6, 1],
+        [0, 1, 15, 25, 10, 1],
+        [0, 1, 31, 90, 65, 15, 1],
+        [0, 1, 63, 301, 350, 140, 21, 1],
+        [0, 1, 127, 966, 1701, 1050, 266, 28, 1],
+        [0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1],
+        [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1],
+    ]
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_table_cases(self, is_exact, comp, kwargs):
+        for n in range(1, len(self.table)):
+            k_values = list(range(n+1))
+            row = self.table[n]
+            comp(row, stirling2([n], k_values, exact=is_exact), **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_valid_single_integer(self, is_exact, comp, kwargs):
+        comp(stirling2(0, 0, exact=is_exact), self.table[0][0], **kwargs)
+        comp(stirling2(4, 2, exact=is_exact), self.table[4][2], **kwargs)
+        # a single 2-tuple of integers as arguments must return an int and not
+        # an array whereas arrays of single values should return array
+        comp(stirling2(5, 3, exact=is_exact), 25, **kwargs)
+        comp(stirling2([5], [3], exact=is_exact), [25], **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_negative_integer(self, is_exact, comp, kwargs):
+        # negative integers for n or k arguments return 0
+        comp(stirling2(-1, -1, exact=is_exact), 0, **kwargs)
+        comp(stirling2(-1, 2, exact=is_exact), 0, **kwargs)
+        comp(stirling2(2, -1, exact=is_exact), 0, **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_array_inputs(self, is_exact, comp, kwargs):
+        ans = [self.table[10][3], self.table[10][4]]
+        comp(stirling2(asarray([10, 10]),
+                               asarray([3, 4]),
+                               exact=is_exact),
+                     ans)
+        comp(stirling2([10, 10],
+                               asarray([3, 4]),
+                               exact=is_exact),
+                     ans)
+        comp(stirling2(asarray([10, 10]),
+                               [3, 4],
+                               exact=is_exact),
+                     ans)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-13})
+    ])
+    def test_mixed_values(self, is_exact, comp, kwargs):
+        # negative values-of either n or k-should return 0 for the entry
+        ans = [0, 1, 3, 25, 1050, 5880, 9330]
+        n = [-1, 0, 3, 5, 8, 10, 10]
+        k = [-2, 0, 2, 3, 5, 7, 3]
+        comp(stirling2(n, k, exact=is_exact), ans, **kwargs)
+
+    def test_correct_parity(self):
+        """Test parity follows well known identity.
+
+        en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind#Parity
+        """
+        n, K = 100, np.arange(101)
+        assert_equal(
+            stirling2(n, K, exact=True) % 2,
+            [math.comb(n - (k // 2) - 1, n - k) % 2 for k in K],
+        )
+
+    def test_big_numbers(self):
+        # via mpmath (bigger than 32bit)
+        ans = asarray([48063331393110, 48004081105038305])
+        n = [25, 30]
+        k = [17, 4]
+        assert array_equal(stirling2(n, k, exact=True), ans)
+        # bigger than 64 bit
+        ans = asarray([2801934359500572414253157841233849412,
+                       14245032222277144547280648984426251])
+        n = [42, 43]
+        k = [17, 23]
+        assert array_equal(stirling2(n, k, exact=True), ans)
+
+    @pytest.mark.parametrize("N", [4.5, 3., 4+1j, "12", np.nan])
+    @pytest.mark.parametrize("K", [3.5, 3, "2", None])
+    @pytest.mark.parametrize("is_exact", [True, False])
+    def test_unsupported_input_types(self, N, K, is_exact):
+        # object, float, string, complex are not supported and raise TypeError
+        with pytest.raises(TypeError):
+            stirling2(N, K, exact=is_exact)
+
+    @pytest.mark.parametrize("is_exact", [True, False])
+    def test_numpy_array_int_object_dtype(self, is_exact):
+        # python integers with arbitrary precision are *not* allowed as
+        # object type in numpy arrays are inconsistent from api perspective
+        ans = asarray(self.table[4][1:])
+        n = asarray([4, 4, 4, 4], dtype=object)
+        k = asarray([1, 2, 3, 4], dtype=object)
+        with pytest.raises(TypeError):
+            array_equal(stirling2(n, k, exact=is_exact), ans)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-13})
+    ])
+    def test_numpy_array_unsigned_int_dtype(self, is_exact, comp, kwargs):
+        # numpy unsigned integers are allowed as dtype in numpy arrays
+        ans = asarray(self.table[4][1:])
+        n = asarray([4, 4, 4, 4], dtype=np_ulong)
+        k = asarray([1, 2, 3, 4], dtype=np_ulong)
+        comp(stirling2(n, k, exact=False), ans, **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-13})
+    ])
+    def test_broadcasting_arrays_correctly(self, is_exact, comp, kwargs):
+        # broadcasting is handled by stirling2
+        # test leading 1s are replicated
+        ans = asarray([[1, 15, 25, 10], [1, 7, 6, 1]])  # shape (2,4)
+        n = asarray([[5, 5, 5, 5], [4, 4, 4, 4]])  # shape (2,4)
+        k = asarray([1, 2, 3, 4])  # shape (4,)
+        comp(stirling2(n, k, exact=is_exact), ans, **kwargs)
+        # test that dims both mismatch broadcast correctly (5,1) & (6,)
+        n = asarray([[4], [4], [4], [4], [4]])
+        k = asarray([0, 1, 2, 3, 4, 5])
+        ans = asarray([[0, 1, 7, 6, 1, 0] for _ in range(5)])
+        comp(stirling2(n, k, exact=False), ans, **kwargs)
+
+    def test_temme_rel_max_error(self):
+        # python integers with arbitrary precision are *not* allowed as
+        # object type in numpy arrays are inconsistent from api perspective
+        x = list(range(51, 101, 5))
+        for n in x:
+            k_entries = list(range(1, n+1))
+            denom = stirling2([n], k_entries, exact=True)
+            num = denom - stirling2([n], k_entries, exact=False)
+            assert np.max(np.abs(num / denom)) < 2e-5
+
+
+class TestLegendreDeprecation:
+
+    def test_warn_lpn(self):
+        msg = "`scipy.special.lpn` is deprecated..."
+        with pytest.deprecated_call(match=msg):
+            _ = lpn(1, 0)
+
+    @pytest.mark.parametrize("xlpmn", [lpmn, clpmn])
+    def test_warn_xlpmn(self, xlpmn):
+        message = f"`scipy.special.{xlpmn.__name__}` is deprecated..."
+        with pytest.deprecated_call(match=message):
+            _ = xlpmn(1, 1, 0)
+
+    def test_warn_sph_harm(self):
+        msg = "`scipy.special.sph_harm` is deprecated..."
+        with pytest.deprecated_call(match=msg):
+            _ = special.sph_harm(1, 1, 0, 0)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..57694becc49b2028f17eac819b80a225ac010795
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py
@@ -0,0 +1,112 @@
+import numpy as np
+import scipy.special as sc
+import pytest
+from numpy.testing import assert_allclose, assert_array_equal, suppress_warnings
+
+
+class TestBdtr:
+    def test(self):
+        val = sc.bdtr(0, 1, 0.5)
+        assert_allclose(val, 0.5)
+
+    def test_sum_is_one(self):
+        val = sc.bdtr([0, 1, 2], 2, 0.5)
+        assert_array_equal(val, [0.25, 0.75, 1.0])
+
+    def test_rounding(self):
+        double_val = sc.bdtr([0.1, 1.1, 2.1], 2, 0.5)
+        int_val = sc.bdtr([0, 1, 2], 2, 0.5)
+        assert_array_equal(double_val, int_val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (np.inf, 2, 0.5),
+        (1.0, np.inf, 0.5),
+        (1.0, 2, np.inf)
+    ])
+    def test_inf(self, k, n, p):
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning)
+            val = sc.bdtr(k, n, p)
+        assert np.isnan(val)
+
+    def test_domain(self):
+        val = sc.bdtr(-1.1, 1, 0.5)
+        assert np.isnan(val)
+
+
+class TestBdtrc:
+    def test_value(self):
+        val = sc.bdtrc(0, 1, 0.5)
+        assert_allclose(val, 0.5)
+
+    def test_sum_is_one(self):
+        val = sc.bdtrc([0, 1, 2], 2, 0.5)
+        assert_array_equal(val, [0.75, 0.25, 0.0])
+
+    def test_rounding(self):
+        double_val = sc.bdtrc([0.1, 1.1, 2.1], 2, 0.5)
+        int_val = sc.bdtrc([0, 1, 2], 2, 0.5)
+        assert_array_equal(double_val, int_val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (np.inf, 2, 0.5),
+        (1.0, np.inf, 0.5),
+        (1.0, 2, np.inf)
+    ])
+    def test_inf(self, k, n, p):
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning)
+            val = sc.bdtrc(k, n, p)
+        assert np.isnan(val)
+
+    def test_domain(self):
+        val = sc.bdtrc(-1.1, 1, 0.5)
+        val2 = sc.bdtrc(2.1, 1, 0.5)
+        assert np.isnan(val2)
+        assert_allclose(val, 1.0)
+
+    def test_bdtr_bdtrc_sum_to_one(self):
+        bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5)
+        bdtrc_vals = sc.bdtrc([0, 1, 2], 2, 0.5)
+        vals = bdtr_vals + bdtrc_vals
+        assert_allclose(vals, [1.0, 1.0, 1.0])
+
+
+class TestBdtri:
+    def test_value(self):
+        val = sc.bdtri(0, 1, 0.5)
+        assert_allclose(val, 0.5)
+
+    def test_sum_is_one(self):
+        val = sc.bdtri([0, 1], 2, 0.5)
+        actual = np.asarray([1 - 1/np.sqrt(2), 1/np.sqrt(2)])
+        assert_allclose(val, actual)
+
+    def test_rounding(self):
+        double_val = sc.bdtri([0.1, 1.1], 2, 0.5)
+        int_val = sc.bdtri([0, 1], 2, 0.5)
+        assert_allclose(double_val, int_val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (np.inf, 2, 0.5),
+        (1.0, np.inf, 0.5),
+        (1.0, 2, np.inf)
+    ])
+    def test_inf(self, k, n, p):
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning)
+            val = sc.bdtri(k, n, p)
+        assert np.isnan(val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (-1.1, 1, 0.5),
+        (2.1, 1, 0.5)
+    ])
+    def test_domain(self, k, n, p):
+        val = sc.bdtri(k, n, p)
+        assert np.isnan(val)
+
+    def test_bdtr_bdtri_roundtrip(self):
+        bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5)
+        roundtrip_vals = sc.bdtri([0, 1, 2], 2, bdtr_vals)
+        assert_allclose(roundtrip_vals, [0.5, 0.5, np.nan])
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..132fb9ab11ec19d8efa00c5bb96f851795017d31
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py
@@ -0,0 +1,61 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special._ufuncs as scu
+from scipy.integrate import tanhsinh
+
+
+type_char_to_type_tol = {'f': (np.float32, 32*np.finfo(np.float32).eps),
+                         'd': (np.float64, 32*np.finfo(np.float64).eps)}
+
+
+# Each item in this list is
+#   (func, args, expected_value)
+# All the values can be represented exactly, even with np.float32.
+#
+# This is not an exhaustive test data set of all the functions!
+# It is a spot check of several functions, primarily for
+# checking that the different data types are handled correctly.
+test_data = [
+    (scu._beta_pdf, (0.5, 2, 3), 1.5),
+    (scu._beta_pdf, (0, 1, 5), 5.0),
+    (scu._beta_pdf, (1, 5, 1), 5.0),
+    (scu._beta_ppf, (0.5, 5., 5.), 0.5),  # gh-21303
+    (scu._binom_cdf, (1, 3, 0.5), 0.5),
+    (scu._binom_pmf, (1, 4, 0.5), 0.25),
+    (scu._hypergeom_cdf, (2, 3, 5, 6), 0.5),
+    (scu._nbinom_cdf, (1, 4, 0.25), 0.015625),
+    (scu._ncf_mean, (10, 12, 2.5), 1.5),
+]
+
+
+@pytest.mark.parametrize('func, args, expected', test_data)
+def test_stats_boost_ufunc(func, args, expected):
+    type_sigs = func.types
+    type_chars = [sig.split('->')[-1] for sig in type_sigs]
+    for type_char in type_chars:
+        typ, rtol = type_char_to_type_tol[type_char]
+        args = [typ(arg) for arg in args]
+        # Harmless overflow warnings are a "feature" of some wrappers on some
+        # platforms. This test is about dtype and accuracy, so let's avoid false
+        # test failures cause by these warnings. See gh-17432.
+        with np.errstate(over='ignore'):
+            value = func(*args)
+        assert isinstance(value, typ)
+        assert_allclose(value, expected, rtol=rtol)
+
+
+def test_landau():
+    # Test that Landau distribution ufuncs are wrapped as expected;
+    # accuracy is tested by Boost.
+    x = np.linspace(-3, 10, 10)
+    args = (0, 1)
+    res = tanhsinh(lambda x: scu._landau_pdf(x, *args), -np.inf, x)
+    cdf = scu._landau_cdf(x, *args)
+    assert_allclose(res.integral, cdf)
+    sf = scu._landau_sf(x, *args)
+    assert_allclose(sf, 1-cdf)
+    ppf = scu._landau_ppf(cdf, *args)
+    assert_allclose(ppf, x)
+    isf = scu._landau_isf(sf, *args)
+    assert_allclose(isf, x, rtol=1e-6)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py
new file mode 100644
index 0000000000000000000000000000000000000000..25d76d0560a6a9fe416f750213662b5f7fb22f25
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py
@@ -0,0 +1,125 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
+from scipy.special import boxcox, boxcox1p, inv_boxcox, inv_boxcox1p
+import pytest
+
+
+# There are more tests of boxcox and boxcox1p in test_mpmath.py.
+
+def test_boxcox_basic():
+    x = np.array([0.5, 1, 2, 4])
+
+    # lambda = 0  =>  y = log(x)
+    y = boxcox(x, 0)
+    assert_almost_equal(y, np.log(x))
+
+    # lambda = 1  =>  y = x - 1
+    y = boxcox(x, 1)
+    assert_almost_equal(y, x - 1)
+
+    # lambda = 2  =>  y = 0.5*(x**2 - 1)
+    y = boxcox(x, 2)
+    assert_almost_equal(y, 0.5*(x**2 - 1))
+
+    # x = 0 and lambda > 0  =>  y = -1 / lambda
+    lam = np.array([0.5, 1, 2])
+    y = boxcox(0, lam)
+    assert_almost_equal(y, -1.0 / lam)
+
+def test_boxcox_underflow():
+    x = 1 + 1e-15
+    lmbda = 1e-306
+    y = boxcox(x, lmbda)
+    assert_allclose(y, np.log(x), rtol=1e-14)
+
+
+def test_boxcox_nonfinite():
+    # x < 0  =>  y = nan
+    x = np.array([-1, -1, -0.5])
+    y = boxcox(x, [0.5, 2.0, -1.5])
+    assert_equal(y, np.array([np.nan, np.nan, np.nan]))
+
+    # x = 0 and lambda <= 0  =>  y = -inf
+    x = 0
+    y = boxcox(x, [-2.5, 0])
+    assert_equal(y, np.array([-np.inf, -np.inf]))
+
+
+def test_boxcox1p_basic():
+    x = np.array([-0.25, -1e-20, 0, 1e-20, 0.25, 1, 3])
+
+    # lambda = 0  =>  y = log(1+x)
+    y = boxcox1p(x, 0)
+    assert_almost_equal(y, np.log1p(x))
+
+    # lambda = 1  =>  y = x
+    y = boxcox1p(x, 1)
+    assert_almost_equal(y, x)
+
+    # lambda = 2  =>  y = 0.5*((1+x)**2 - 1) = 0.5*x*(2 + x)
+    y = boxcox1p(x, 2)
+    assert_almost_equal(y, 0.5*x*(2 + x))
+
+    # x = -1 and lambda > 0  =>  y = -1 / lambda
+    lam = np.array([0.5, 1, 2])
+    y = boxcox1p(-1, lam)
+    assert_almost_equal(y, -1.0 / lam)
+
+
+def test_boxcox1p_underflow():
+    x = np.array([1e-15, 1e-306])
+    lmbda = np.array([1e-306, 1e-18])
+    y = boxcox1p(x, lmbda)
+    assert_allclose(y, np.log1p(x), rtol=1e-14)
+
+
+def test_boxcox1p_nonfinite():
+    # x < -1  =>  y = nan
+    x = np.array([-2, -2, -1.5])
+    y = boxcox1p(x, [0.5, 2.0, -1.5])
+    assert_equal(y, np.array([np.nan, np.nan, np.nan]))
+
+    # x = -1 and lambda <= 0  =>  y = -inf
+    x = -1
+    y = boxcox1p(x, [-2.5, 0])
+    assert_equal(y, np.array([-np.inf, -np.inf]))
+
+
+def test_inv_boxcox():
+    x = np.array([0., 1., 2.])
+    lam = np.array([0., 1., 2.])
+    y = boxcox(x, lam)
+    x2 = inv_boxcox(y, lam)
+    assert_almost_equal(x, x2)
+
+    x = np.array([0., 1., 2.])
+    lam = np.array([0., 1., 2.])
+    y = boxcox1p(x, lam)
+    x2 = inv_boxcox1p(y, lam)
+    assert_almost_equal(x, x2)
+
+
+def test_inv_boxcox1p_underflow():
+    x = 1e-15
+    lam = 1e-306
+    y = inv_boxcox1p(x, lam)
+    assert_allclose(y, x, rtol=1e-14)
+
+
+@pytest.mark.parametrize(
+    "x, lmb",
+    [[100, 155],
+     [0.01, -155]]
+)
+def test_boxcox_premature_overflow(x, lmb):
+    # test boxcox & inv_boxcox
+    y = boxcox(x, lmb)
+    assert np.isfinite(y)
+    x_inv = inv_boxcox(y, lmb)
+    assert_allclose(x, x_inv)
+
+    # test boxcox1p & inv_boxcox1p
+    y1p = boxcox1p(x-1, lmb)
+    assert np.isfinite(y1p)
+    x1p_inv = inv_boxcox1p(y1p, lmb)
+    assert_allclose(x-1, x1p_inv)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8352182bdf657029ab9857411e1b41141fdc0a5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py
@@ -0,0 +1,688 @@
+"""
+Test cdflib functions versus mpmath, if available.
+
+The following functions still need tests:
+
+- ncfdtri
+- ncfdtridfn
+- ncfdtridfd
+- ncfdtrinc
+- nbdtrik
+- nbdtrin
+- pdtrik
+- nctdtrit
+- nctdtridf
+- nctdtrinc
+
+"""
+import itertools
+
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+import pytest
+
+import scipy.special as sp
+from scipy.special._testutils import (
+    MissingModule, check_version, FuncData)
+from scipy.special._mptestutils import (
+    Arg, IntArg, get_args, mpf2float, assert_mpmath_equal)
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule('mpmath')
+
+
+class ProbArg:
+    """Generate a set of probabilities on [0, 1]."""
+
+    def __init__(self):
+        # Include the endpoints for compatibility with Arg et. al.
+        self.a = 0
+        self.b = 1
+
+    def values(self, n):
+        """Return an array containing approximately n numbers."""
+        m = max(1, n//3)
+        v1 = np.logspace(-30, np.log10(0.3), m)
+        v2 = np.linspace(0.3, 0.7, m + 1, endpoint=False)[1:]
+        v3 = 1 - np.logspace(np.log10(0.3), -15, m)
+        v = np.r_[v1, v2, v3]
+        return np.unique(v)
+
+
+class EndpointFilter:
+    def __init__(self, a, b, rtol, atol):
+        self.a = a
+        self.b = b
+        self.rtol = rtol
+        self.atol = atol
+
+    def __call__(self, x):
+        mask1 = np.abs(x - self.a) < self.rtol*np.abs(self.a) + self.atol
+        mask2 = np.abs(x - self.b) < self.rtol*np.abs(self.b) + self.atol
+        return np.where(mask1 | mask2, False, True)
+
+
+class _CDFData:
+    def __init__(self, spfunc, mpfunc, index, argspec, spfunc_first=True,
+                 dps=20, n=5000, rtol=None, atol=None,
+                 endpt_rtol=None, endpt_atol=None):
+        self.spfunc = spfunc
+        self.mpfunc = mpfunc
+        self.index = index
+        self.argspec = argspec
+        self.spfunc_first = spfunc_first
+        self.dps = dps
+        self.n = n
+        self.rtol = rtol
+        self.atol = atol
+
+        if not isinstance(argspec, list):
+            self.endpt_rtol = None
+            self.endpt_atol = None
+        elif endpt_rtol is not None or endpt_atol is not None:
+            if isinstance(endpt_rtol, list):
+                self.endpt_rtol = endpt_rtol
+            else:
+                self.endpt_rtol = [endpt_rtol]*len(self.argspec)
+            if isinstance(endpt_atol, list):
+                self.endpt_atol = endpt_atol
+            else:
+                self.endpt_atol = [endpt_atol]*len(self.argspec)
+        else:
+            self.endpt_rtol = None
+            self.endpt_atol = None
+
+    def idmap(self, *args):
+        if self.spfunc_first:
+            res = self.spfunc(*args)
+            if np.isnan(res):
+                return np.nan
+            args = list(args)
+            args[self.index] = res
+            with mpmath.workdps(self.dps):
+                res = self.mpfunc(*tuple(args))
+                # Imaginary parts are spurious
+                res = mpf2float(res.real)
+        else:
+            with mpmath.workdps(self.dps):
+                res = self.mpfunc(*args)
+                res = mpf2float(res.real)
+            args = list(args)
+            args[self.index] = res
+            res = self.spfunc(*tuple(args))
+        return res
+
+    def get_param_filter(self):
+        if self.endpt_rtol is None and self.endpt_atol is None:
+            return None
+
+        filters = []
+        for rtol, atol, spec in zip(self.endpt_rtol, self.endpt_atol, self.argspec):
+            if rtol is None and atol is None:
+                filters.append(None)
+                continue
+            elif rtol is None:
+                rtol = 0.0
+            elif atol is None:
+                atol = 0.0
+
+            filters.append(EndpointFilter(spec.a, spec.b, rtol, atol))
+        return filters
+
+    def check(self):
+        # Generate values for the arguments
+        args = get_args(self.argspec, self.n)
+        param_filter = self.get_param_filter()
+        param_columns = tuple(range(args.shape[1]))
+        result_columns = args.shape[1]
+        args = np.hstack((args, args[:, self.index].reshape(args.shape[0], 1)))
+        FuncData(self.idmap, args,
+                 param_columns=param_columns, result_columns=result_columns,
+                 rtol=self.rtol, atol=self.atol, vectorized=False,
+                 param_filter=param_filter).check()
+
+
+def _assert_inverts(*a, **kw):
+    d = _CDFData(*a, **kw)
+    d.check()
+
+
+def _binomial_cdf(k, n, p):
+    k, n, p = mpmath.mpf(k), mpmath.mpf(n), mpmath.mpf(p)
+    if k <= 0:
+        return mpmath.mpf(0)
+    elif k >= n:
+        return mpmath.mpf(1)
+
+    onemp = mpmath.fsub(1, p, exact=True)
+    return mpmath.betainc(n - k, k + 1, x2=onemp, regularized=True)
+
+
+def _f_cdf(dfn, dfd, x):
+    if x < 0:
+        return mpmath.mpf(0)
+    dfn, dfd, x = mpmath.mpf(dfn), mpmath.mpf(dfd), mpmath.mpf(x)
+    ub = dfn*x/(dfn*x + dfd)
+    res = mpmath.betainc(dfn/2, dfd/2, x2=ub, regularized=True)
+    return res
+
+
+def _student_t_cdf(df, t, dps=None):
+    if dps is None:
+        dps = mpmath.mp.dps
+    with mpmath.workdps(dps):
+        df, t = mpmath.mpf(df), mpmath.mpf(t)
+        fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df)
+        fac *= t*mpmath.gamma(0.5*(df + 1))
+        fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df)
+        return 0.5 + fac
+
+
+def _noncentral_chi_pdf(t, df, nc):
+    res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t))
+    res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2
+    return res
+
+
+def _noncentral_chi_cdf(x, df, nc, dps=None):
+    if dps is None:
+        dps = mpmath.mp.dps
+    x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc)
+    with mpmath.workdps(dps):
+        res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x])
+        return res
+
+
+def _tukey_lmbda_quantile(p, lmbda):
+    # For lmbda != 0
+    return (p**lmbda - (1 - p)**lmbda)/lmbda
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+class TestCDFlib:
+
+    @pytest.mark.xfail(run=False)
+    def test_bdtrik(self):
+        _assert_inverts(
+            sp.bdtrik,
+            _binomial_cdf,
+            0, [ProbArg(), IntArg(1, 1000), ProbArg()],
+            rtol=1e-4)
+
+    def test_bdtrin(self):
+        _assert_inverts(
+            sp.bdtrin,
+            _binomial_cdf,
+            1, [IntArg(1, 1000), ProbArg(), ProbArg()],
+            rtol=1e-4, endpt_atol=[None, None, 1e-6])
+
+    def test_btdtria(self):
+        _assert_inverts(
+            sp.btdtria,
+            lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True),
+            0, [ProbArg(), Arg(0, 1e2, inclusive_a=False),
+                Arg(0, 1, inclusive_a=False, inclusive_b=False)],
+            rtol=1e-6)
+
+    def test_btdtrib(self):
+        # Use small values of a or mpmath doesn't converge
+        _assert_inverts(
+            sp.btdtrib,
+            lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True),
+            1,
+            [Arg(0, 1e2, inclusive_a=False), ProbArg(),
+             Arg(0, 1, inclusive_a=False, inclusive_b=False)],
+            rtol=1e-7,
+            endpt_atol=[None, 1e-18, 1e-15])
+
+    @pytest.mark.xfail(run=False)
+    def test_fdtridfd(self):
+        _assert_inverts(
+            sp.fdtridfd,
+            _f_cdf,
+            1,
+            [IntArg(1, 100), ProbArg(), Arg(0, 100, inclusive_a=False)],
+            rtol=1e-7)
+
+    def test_gdtria(self):
+        _assert_inverts(
+            sp.gdtria,
+            lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
+            0,
+            [ProbArg(), Arg(0, 1e3, inclusive_a=False),
+             Arg(0, 1e4, inclusive_a=False)],
+            rtol=1e-7,
+            endpt_atol=[None, 1e-7, 1e-10])
+
+    def test_gdtrib(self):
+        # Use small values of a and x or mpmath doesn't converge
+        _assert_inverts(
+            sp.gdtrib,
+            lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
+            1,
+            [Arg(0, 1e2, inclusive_a=False), ProbArg(),
+             Arg(0, 1e3, inclusive_a=False)],
+            rtol=1e-5)
+
+    def test_gdtrix(self):
+        _assert_inverts(
+            sp.gdtrix,
+            lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
+            2,
+            [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False),
+             ProbArg()],
+            rtol=1e-7,
+            endpt_atol=[None, 1e-7, 1e-10])
+
+    # Overall nrdtrimn and nrdtrisd are not performing well with infeasible/edge
+    # combinations of sigma and x, hence restricted the domains to still use the
+    # testing machinery, also see gh-20069
+
+    # nrdtrimn signature: p, sd, x
+    # nrdtrisd signature: mn, p, x
+    def test_nrdtrimn(self):
+        _assert_inverts(
+            sp.nrdtrimn,
+            lambda x, y, z: mpmath.ncdf(z, x, y),
+            0,
+            [ProbArg(),  # CDF value p
+             Arg(0.1, np.inf, inclusive_a=False, inclusive_b=False),  # sigma
+             Arg(-1e10, 1e10)],  # x
+            rtol=1e-5)
+
+    def test_nrdtrisd(self):
+        _assert_inverts(
+            sp.nrdtrisd,
+            lambda x, y, z: mpmath.ncdf(z, x, y),
+            1,
+            [Arg(-np.inf, 10, inclusive_a=False, inclusive_b=False),  # mn
+             ProbArg(),  # CDF value p
+             Arg(10, 1e100)],  # x
+            rtol=1e-5)
+
+    def test_stdtr(self):
+        # Ideally the left endpoint for Arg() should be 0.
+        assert_mpmath_equal(
+            sp.stdtr,
+            _student_t_cdf,
+            [IntArg(1, 100), Arg(1e-10, np.inf)], rtol=1e-7)
+
+    @pytest.mark.xfail(run=False)
+    def test_stdtridf(self):
+        _assert_inverts(
+            sp.stdtridf,
+            _student_t_cdf,
+            0, [ProbArg(), Arg()], rtol=1e-7)
+
+    def test_stdtrit(self):
+        _assert_inverts(
+            sp.stdtrit,
+            _student_t_cdf,
+            1, [IntArg(1, 100), ProbArg()], rtol=1e-7,
+            endpt_atol=[None, 1e-10])
+
+    def test_chdtriv(self):
+        _assert_inverts(
+            sp.chdtriv,
+            lambda v, x: mpmath.gammainc(v/2, b=x/2, regularized=True),
+            0, [ProbArg(), IntArg(1, 100)], rtol=1e-4)
+
+    @pytest.mark.xfail(run=False)
+    def test_chndtridf(self):
+        # Use a larger atol since mpmath is doing numerical integration
+        _assert_inverts(
+            sp.chndtridf,
+            _noncentral_chi_cdf,
+            1, [Arg(0, 100, inclusive_a=False), ProbArg(),
+                Arg(0, 100, inclusive_a=False)],
+            n=1000, rtol=1e-4, atol=1e-15)
+
+    @pytest.mark.xfail(run=False)
+    def test_chndtrinc(self):
+        # Use a larger atol since mpmath is doing numerical integration
+        _assert_inverts(
+            sp.chndtrinc,
+            _noncentral_chi_cdf,
+            2, [Arg(0, 100, inclusive_a=False), IntArg(1, 100), ProbArg()],
+            n=1000, rtol=1e-4, atol=1e-15)
+
+    def test_chndtrix(self):
+        # Use a larger atol since mpmath is doing numerical integration
+        _assert_inverts(
+            sp.chndtrix,
+            _noncentral_chi_cdf,
+            0, [ProbArg(), IntArg(1, 100), Arg(0, 100, inclusive_a=False)],
+            n=1000, rtol=1e-4, atol=1e-15,
+            endpt_atol=[1e-6, None, None])
+
+    def test_tklmbda_zero_shape(self):
+        # When lmbda = 0 the CDF has a simple closed form
+        one = mpmath.mpf(1)
+        assert_mpmath_equal(
+            lambda x: sp.tklmbda(x, 0),
+            lambda x: one/(mpmath.exp(-x) + one),
+            [Arg()], rtol=1e-7)
+
+    def test_tklmbda_neg_shape(self):
+        _assert_inverts(
+            sp.tklmbda,
+            _tukey_lmbda_quantile,
+            0, [ProbArg(), Arg(-25, 0, inclusive_b=False)],
+            spfunc_first=False, rtol=1e-5,
+            endpt_atol=[1e-9, 1e-5])
+
+    @pytest.mark.xfail(run=False)
+    def test_tklmbda_pos_shape(self):
+        _assert_inverts(
+            sp.tklmbda,
+            _tukey_lmbda_quantile,
+            0, [ProbArg(), Arg(0, 100, inclusive_a=False)],
+            spfunc_first=False, rtol=1e-5)
+
+    # The values of lmdba are chosen so that 1/lmbda is exact.
+    @pytest.mark.parametrize('lmbda', [0.5, 1.0, 8.0])
+    def test_tklmbda_lmbda1(self, lmbda):
+        bound = 1/lmbda
+        assert_equal(sp.tklmbda([-bound, bound], lmbda), [0.0, 1.0])
+
+
+funcs = [
+    ("btdtria", 3),
+    ("btdtrib", 3),
+    ("bdtrik", 3),
+    ("bdtrin", 3),
+    ("chdtriv", 2),
+    ("chndtr", 3),
+    ("chndtrix", 3),
+    ("chndtridf", 3),
+    ("chndtrinc", 3),
+    ("fdtridfd", 3),
+    ("ncfdtr", 4),
+    ("ncfdtri", 4),
+    ("ncfdtridfn", 4),
+    ("ncfdtridfd", 4),
+    ("ncfdtrinc", 4),
+    ("gdtrix", 3),
+    ("gdtrib", 3),
+    ("gdtria", 3),
+    ("nbdtrik", 3),
+    ("nbdtrin", 3),
+    ("nrdtrimn", 3),
+    ("nrdtrisd", 3),
+    ("pdtrik", 2),
+    ("stdtr", 2),
+    ("stdtrit", 2),
+    ("stdtridf", 2),
+    ("nctdtr", 3),
+    ("nctdtrit", 3),
+    ("nctdtridf", 3),
+    ("nctdtrinc", 3),
+    ("tklmbda", 2),
+]
+
+
+@pytest.mark.parametrize('func,numargs', funcs, ids=[x[0] for x in funcs])
+def test_nonfinite(func, numargs):
+
+    rng = np.random.default_rng(1701299355559735)
+    func = getattr(sp, func)
+    args_choices = [(float(x), np.nan, np.inf, -np.inf) for x in rng.random(numargs)]
+
+    for args in itertools.product(*args_choices):
+        res = func(*args)
+
+        if any(np.isnan(x) for x in args):
+            # Nan inputs should result to nan output
+            assert_equal(res, np.nan)
+        else:
+            # All other inputs should return something (but not
+            # raise exceptions or cause hangs)
+            pass
+
+
+def test_chndtrix_gh2158():
+    # test that gh-2158 is resolved; previously this blew up
+    res = sp.chndtrix(0.999999, 2, np.arange(20.)+1e-6)
+
+    # Generated in R
+    # options(digits=16)
+    # ncp <- seq(0, 19) + 1e-6
+    # print(qchisq(0.999999, df = 2, ncp = ncp))
+    res_exp = [27.63103493142305, 35.25728589950540, 39.97396073236288,
+               43.88033702110538, 47.35206403482798, 50.54112500166103,
+               53.52720257322766, 56.35830042867810, 59.06600769498512,
+               61.67243118946381, 64.19376191277179, 66.64228141346548,
+               69.02756927200180, 71.35726934749408, 73.63759723904816,
+               75.87368842650227, 78.06984431185720, 80.22971052389806,
+               82.35640899964173, 84.45263768373256]
+    assert_allclose(res, res_exp)
+
+
+def test_nctdtrinc_gh19896():
+    # test that gh-19896 is resolved.
+    # Compared to SciPy 1.11 results from Fortran code.
+    dfarr = [0.001, 0.98, 9.8, 98, 980, 10000, 98, 9.8, 0.98, 0.001]
+    parr = [0.001, 0.1, 0.3, 0.8, 0.999, 0.001, 0.1, 0.3, 0.8, 0.999]
+    tarr = [0.0015, 0.15, 1.5, 15, 300, 0.0015, 0.15, 1.5, 15, 300]
+    desired = [3.090232306168629, 1.406141304556198, 2.014225177124157,
+               13.727067118283456, 278.9765683871208, 3.090232306168629,
+               1.4312427877936222, 2.014225177124157, 3.712743137978295,
+               -3.086951096691082]
+    actual = sp.nctdtrinc(dfarr, parr, tarr)
+    assert_allclose(actual, desired, rtol=5e-12, atol=0.0)
+
+
+def test_stdtr_stdtrit_neg_inf():
+    # -inf was treated as +inf and values from the normal were returned
+    assert np.all(np.isnan(sp.stdtr(-np.inf, [-np.inf, -1.0, 0.0, 1.0, np.inf])))
+    assert np.all(np.isnan(sp.stdtrit(-np.inf, [0.0, 0.25, 0.5, 0.75, 1.0])))
+
+
+def test_bdtrik_nbdtrik_inf():
+    y = np.array(
+        [np.nan,-np.inf,-10.0, -1.0, 0.0, .00001, .5, 0.9999, 1.0, 10.0, np.inf])
+    y = y[:,None]
+    p = np.atleast_2d(
+        [np.nan, -np.inf, -10.0, -1.0, 0.0, .00001, .5, 1.0, np.inf])
+    assert np.all(np.isnan(sp.bdtrik(y, np.inf, p)))
+    assert np.all(np.isnan(sp.nbdtrik(y, np.inf, p)))
+
+
+@pytest.mark.parametrize(
+    "dfn,dfd,nc,f,expected",
+    [[100.0, 0.1, 0.1, 100.0, 0.29787396410092676],
+     [100.0, 100.0, 0.01, 0.1, 4.4344737598690424e-26],
+     [100.0, 0.01, 0.1, 0.01, 0.002848616633080384],
+     [10.0, 0.01, 1.0, 0.1, 0.012339557729057956],
+     [100.0, 100.0, 0.01, 0.01, 1.8926477420964936e-72],
+     [1.0, 100.0, 100.0, 0.1, 1.7925940526821304e-22],
+     [1.0, 0.01, 100.0, 10.0, 0.012334711965024968],
+     [1.0, 0.01, 10.0, 0.01, 0.00021944525290299],
+     [10.0, 1.0, 0.1, 100.0, 0.9219345555070705],
+     [0.1, 0.1, 1.0, 1.0, 0.3136335813423239],
+     [100.0, 100.0, 0.1, 10.0, 1.0],
+     [1.0, 0.1, 100.0, 10.0, 0.02926064279680897]]
+)
+def test_ncfdtr(dfn, dfd, nc, f, expected):
+    # Reference values computed with mpmath with the following script
+    #
+    # import numpy as np
+    #
+    # from mpmath import mp
+    # from scipy.special import ncfdtr
+    #
+    # mp.dps = 100
+    #
+    # def mp_ncfdtr(dfn, dfd, nc, f):
+    #     # Uses formula 26.2.20 from Abramowitz and Stegun.
+    #     dfn, dfd, nc, f = map(mp.mpf, (dfn, dfd, nc, f))
+    #     def term(j):
+    #         result = mp.exp(-nc/2)*(nc/2)**j / mp.factorial(j)
+    #         result *= mp.betainc(
+    #             dfn/2 + j, dfd/2, 0, f*dfn/(f*dfn + dfd), regularized=True
+    #         )
+    #         return result
+    #     result = mp.nsum(term, [0, mp.inf])
+    #     return float(result)
+    #
+    # dfn = np.logspace(-2, 2, 5)
+    # dfd = np.logspace(-2, 2, 5)
+    # nc = np.logspace(-2, 2, 5)
+    # f = np.logspace(-2, 2, 5)
+    #
+    # dfn, dfd, nc, f = np.meshgrid(dfn, dfd, nc, f)
+    # dfn, dfd, nc, f = map(np.ravel, (dfn, dfd, nc, f))
+    #
+    # cases = []
+    # re = []
+    # for x0, x1, x2, x3 in zip(*(dfn, dfd, nc, f)):
+    #     observed = ncfdtr(x0, x1, x2, x3)
+    #     expected = mp_ncfdtr(x0, x1, x2, x3)
+    #     cases.append((x0, x1, x2, x3, expected))
+    #     re.append((abs(expected - observed)/abs(expected)))
+    #
+    # assert np.max(re) < 1e-13
+    #
+    # rng = np.random.default_rng(1234)
+    # sample_idx = rng.choice(len(re), replace=False, size=12)
+    # cases = np.array(cases)[sample_idx].tolist()
+    assert_allclose(sp.ncfdtr(dfn, dfd, nc, f), expected, rtol=1e-13, atol=0)
+
+
+class TestNctdtr:
+
+    # Reference values computed with mpmath with the following script
+    # Formula from:
+    # Lenth, Russell V (1989). "Algorithm AS 243: Cumulative Distribution Function
+    # of the Non-central t Distribution". Journal of the Royal Statistical Society,
+    # Series C. 38 (1): 185-189
+    #
+    # Warning: may take a long time to run
+    #
+    # from mpmath import mp
+    # mp.dps = 400
+
+    # def nct_cdf(df, nc, x):
+    #     df, nc, x = map(mp.mpf, (df, nc, x))
+        
+    #     def f(df, nc, x):
+    #         phi = mp.ncdf(-nc)
+    #         y = x * x / (x * x + df)
+    #         constant = mp.exp(-nc * nc / 2.)
+    #         def term(j):
+    #             intermediate = constant * (nc *nc / 2.)**j
+    #             p = intermediate/mp.factorial(j)
+    #             q = nc / (mp.sqrt(2.) * mp.gamma(j + 1.5)) * intermediate
+    #             first_beta_term = mp.betainc(j + 0.5, df/2., x2=y,
+    #                                          regularized=True)
+    #             second_beta_term = mp.betainc(j + mp.one, df/2., x2=y,
+    #                                           regularized=True)
+    #             return p * first_beta_term + q * second_beta_term
+
+    #         sum_term = mp.nsum(term, [0, mp.inf])
+    #         f = phi + 0.5 * sum_term
+    #         return f
+
+    #     if x >= 0:
+    #         result = f(df, nc, x)
+    #     else:
+    #         result = mp.one - f(df, -nc, x)
+    #     return float(result)
+
+    @pytest.mark.parametrize("df, nc, x, expected", [
+        (0.98, -3.8, 0.0015, 0.9999279987514815),
+        (0.98, -3.8, 0.15, 0.9999528361700505),
+        (0.98, -3.8, 1.5, 0.9999908823016942),
+        (0.98, -3.8, 15, 0.9999990264591945),
+        (0.98, 0.38, 0.0015, 0.35241533122693),
+        (0.98, 0.38, 0.15, 0.39749697267146983),
+        (0.98, 0.38, 1.5, 0.716862963488558),
+        (0.98, 0.38, 15, 0.9656246449257494),
+        (0.98, 3.8, 0.0015, 7.26973354942293e-05),
+        (0.98, 3.8, 0.15, 0.00012416481147589105),
+        (0.98, 3.8, 1.5, 0.035388035775454095),
+        (0.98, 3.8, 15, 0.7954826975430583),
+        (0.98, 38, 0.0015, 3.02106943e-316),
+        (0.98, 38, 0.15, 6.069970616996603e-309),
+        (0.98, 38, 1.5, 2.591995360483094e-97),
+        (0.98, 38, 15, 0.011927265886910935),
+        (9.8, -3.8, 0.0015, 0.9999280776192786),
+        (9.8, -3.8, 0.15, 0.9999599410685442),
+        (9.8, -3.8, 1.5, 0.9999997432394788),
+        (9.8, -3.8, 15, 0.9999999999999984),
+        (9.8, 0.38, 0.0015, 0.3525155979107491),
+        (9.8, 0.38, 0.15, 0.40763120140379194),
+        (9.8, 0.38, 1.5, 0.8476794017024651),
+        (9.8, 0.38, 15, 0.9999999297116268),
+        (9.8, 3.8, 0.0015, 7.277620328149153e-05),
+        (9.8, 3.8, 0.15, 0.00013024802220900652),
+        (9.8, 3.8, 1.5, 0.013477432800072933),
+        (9.8, 3.8, 15, 0.999850151230648),
+        (9.8, 38, 0.0015, 3.05066095e-316),
+        (9.8, 38, 0.15, 1.79065514676e-313),
+        (9.8, 38, 1.5, 2.0935940165900746e-249),
+        (9.8, 38, 15, 2.252076291604796e-09),
+        (98, -3.8, 0.0015, 0.9999280875149109),
+        (98, -3.8, 0.15, 0.9999608250170452),
+        (98, -3.8, 1.5, 0.9999999304757682),
+        (98, -3.8, 15, 1.0),
+        (98, 0.38, 0.0015, 0.35252817848596313),
+        (98, 0.38, 0.15, 0.40890253001794846),
+        (98, 0.38, 1.5, 0.8664672830006552),
+        (98, 0.38, 15, 1.0),
+        (98, 3.8, 0.0015, 7.278609891281275e-05),
+        (98, 3.8, 0.15, 0.0001310318674827004),
+        (98, 3.8, 1.5, 0.010990879189991727),
+        (98, 3.8, 15, 0.9999999999999989),
+        (98, 38, 0.0015, 3.05437385e-316),
+        (98, 38, 0.15, 9.1668336166e-314),
+        (98, 38, 1.5, 1.8085884236563926e-288),
+        (98, 38, 15, 2.7740532792035907e-50),
+        (980, -3.8, 0.0015, 0.9999280885188965),
+        (980, -3.8, 0.15, 0.9999609144559273),
+        (980, -3.8, 1.5, 0.9999999410050979),
+        (980, -3.8, 15, 1.0),
+        (980, 0.38, 0.0015, 0.3525294548792812),
+        (980, 0.38, 0.15, 0.4090315324657382),
+        (980, 0.38, 1.5, 0.8684247068517293),
+        (980, 0.38, 15, 1.0),
+        (980, 3.8, 0.0015, 7.278710289828983e-05),
+        (980, 3.8, 0.15, 0.00013111131667906573),
+        (980, 3.8, 1.5, 0.010750678886113882),
+        (980, 3.8, 15, 1.0),
+        (980, 38, 0.0015, 3.0547506e-316),
+        (980, 38, 0.15, 8.6191646313e-314),
+        pytest.param(980, 38, 1.5, 1.1824454111413493e-291,
+                     marks=pytest.mark.xfail(
+                        reason="Bug in underlying Boost math implementation")),
+        (980, 38, 15, 5.407535300713606e-105)
+    ])
+    def test_gh19896(self, df, nc, x, expected):
+        # test that gh-19896 is resolved.
+        # Originally this was a regression test that used the old Fortran results
+        # as a reference. The Fortran results were not accurate, so the reference
+        # values were recomputed with mpmath.
+        result = sp.nctdtr(df, nc, x)
+        assert_allclose(result, expected, rtol=1e-13, atol=1e-303)
+
+    def test_nctdtr_gh8344(self):
+        # test that gh-8344 is resolved.
+        df, nc, x = 3000, 3, 0.1
+        expected = 0.0018657780826323328
+        assert_allclose(sp.nctdtr(df, nc, x), expected, rtol=1e-14)
+
+    @pytest.mark.parametrize(
+        "df, nc, x, expected, rtol",
+        [[3., 5., -2., 1.5645373999149622e-09, 5e-9],
+         [1000., 10., 1., 1.1493552133826623e-19, 1e-13],
+         [1e-5, -6., 2., 0.9999999990135003, 1e-13],
+         [10., 20., 0.15, 6.426530505957303e-88, 1e-13],
+         [1., 1., np.inf, 1.0, 0.0],
+         [1., 1., -np.inf, 0.0, 0.0]
+        ]
+    )
+    def test_accuracy(self, df, nc, x, expected, rtol):
+        assert_allclose(sp.nctdtr(df, nc, x), expected, rtol=rtol)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b1ad41243f0865c205963d938ab61a346ee8e88
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py
@@ -0,0 +1,49 @@
+# gh-14777 regression tests
+# Test stdtr and stdtrit with infinite df and large values of df
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+from scipy.special import stdtr, stdtrit, ndtr, ndtri
+
+
+def test_stdtr_vs_R_large_df():
+    df = [1e10, 1e12, 1e120, np.inf]
+    t = 1.
+    res = stdtr(df, t)
+    # R Code:
+    #   options(digits=20)
+    #   pt(1., c(1e10, 1e12, 1e120, Inf))
+    res_R = [0.84134474605644460343,
+             0.84134474606842180044,
+             0.84134474606854281475,
+             0.84134474606854292578]
+    assert_allclose(res, res_R, rtol=2e-15)
+    # last value should also agree with ndtr
+    assert_equal(res[3], ndtr(1.))
+
+
+def test_stdtrit_vs_R_large_df():
+    df = [1e10, 1e12, 1e120, np.inf]
+    p = 0.1
+    res = stdtrit(df, p)
+    # R Code:
+    #   options(digits=20)
+    #   qt(0.1, c(1e10, 1e12, 1e120, Inf))
+    res_R = [-1.2815515656292593150,
+             -1.2815515655454472466,
+             -1.2815515655446008125,
+             -1.2815515655446008125]
+    assert_allclose(res, res_R, rtol=1e-14, atol=1e-15)
+    # last value should also agree with ndtri
+    assert_equal(res[3], ndtri(0.1))
+
+
+def test_stdtr_stdtri_invalid():
+    # a mix of large and inf df with t/p equal to nan
+    df = [1e10, 1e12, 1e120, np.inf]
+    x = np.nan
+    res1 = stdtr(df, x)
+    res2 = stdtrit(df, x)
+    res_ex = 4*[np.nan]
+    assert_equal(res1, res_ex)
+    assert_equal(res2, res_ex)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py
new file mode 100644
index 0000000000000000000000000000000000000000..05f3d1ae5c101ff50c75d1065e5e234063d192e4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py
@@ -0,0 +1,29 @@
+import pytest
+import numpy as np
+from scipy.special._ufuncs import (
+    _smirnovc, _smirnovci, _smirnovp,
+    _struve_asymp_large_z, _struve_bessel_series, _struve_power_series,
+    bdtr, bdtrc, bdtri, expn, kn, nbdtr, nbdtrc, nbdtri, pdtri,
+    smirnov, smirnovi, yn
+)
+
+
+#
+# For each ufunc here, verify that the default integer type, np.intp,
+# can be safely cast to the integer type found in the input type signatures.
+# For this particular set of functions, the code expects to find just one
+# integer type among the input signatures.
+#
+@pytest.mark.parametrize(
+    'ufunc',
+    [_smirnovc, _smirnovci, _smirnovp,
+     _struve_asymp_large_z, _struve_bessel_series, _struve_power_series,
+     bdtr, bdtrc, bdtri, expn, kn, nbdtr, nbdtrc, nbdtri, pdtri,
+     smirnov, smirnovi, yn],
+)
+def test_intp_safe_cast(ufunc):
+    int_chars = {'i', 'l', 'q'}
+    int_input = [set(sig.split('->')[0]) & int_chars for sig in ufunc.types]
+    int_char = ''.join(s.pop() if s else '' for s in int_input)
+    assert len(int_char) == 1, "More integer types in the signatures than expected"
+    assert np.can_cast(np.intp, np.dtype(int_char))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py
new file mode 100644
index 0000000000000000000000000000000000000000..27e3ca2699d0d1d0b58665f125d99c166095696d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py
@@ -0,0 +1,83 @@
+import numpy as np
+from numpy.testing import assert_allclose
+import pytest
+from scipy.special._ufuncs import _cosine_cdf, _cosine_invcdf
+
+
+# These values are (x, p) where p is the expected exact value of
+# _cosine_cdf(x).  These values will be tested for exact agreement.
+_coscdf_exact = [
+    (-4.0, 0.0),
+    (0, 0.5),
+    (np.pi, 1.0),
+    (4.0, 1.0),
+]
+
+@pytest.mark.parametrize("x, expected", _coscdf_exact)
+def test_cosine_cdf_exact(x, expected):
+    assert _cosine_cdf(x) == expected
+
+
+# These values are (x, p), where p is the expected value of
+# _cosine_cdf(x). The expected values were computed with mpmath using
+# 50 digits of precision.  These values will be tested for agreement
+# with the computed values using a very small relative tolerance.
+# The value at -np.pi is not 0, because -np.pi does not equal -π.
+_coscdf_close = [
+    (3.1409, 0.999999999991185),
+    (2.25, 0.9819328173287907),
+    # -1.6 is the threshold below which the Pade approximant is used.
+    (-1.599, 0.08641959838382553),
+    (-1.601, 0.086110582992713),
+    (-2.0, 0.0369709335961611),
+    (-3.0, 7.522387241801384e-05),
+    (-3.1415, 2.109869685443648e-14),
+    (-3.14159, 4.956444476505336e-19),
+    (-np.pi, 4.871934450264861e-50),
+]
+
+@pytest.mark.parametrize("x, expected", _coscdf_close)
+def test_cosine_cdf(x, expected):
+    assert_allclose(_cosine_cdf(x), expected, rtol=5e-15)
+
+
+# These values are (p, x) where x is the expected exact value of
+# _cosine_invcdf(p).  These values will be tested for exact agreement.
+_cosinvcdf_exact = [
+    (0.0, -np.pi),
+    (0.5, 0.0),
+    (1.0, np.pi),
+]
+
+@pytest.mark.parametrize("p, expected", _cosinvcdf_exact)
+def test_cosine_invcdf_exact(p, expected):
+    assert _cosine_invcdf(p) == expected
+
+
+def test_cosine_invcdf_invalid_p():
+    # Check that p values outside of [0, 1] return nan.
+    assert np.isnan(_cosine_invcdf([-0.1, 1.1])).all()
+
+
+# These values are (p, x), where x is the expected value of _cosine_invcdf(p).
+# The expected values were computed with mpmath using 50 digits of precision.
+_cosinvcdf_close = [
+    (1e-50, -np.pi),
+    (1e-14, -3.1415204137058454),
+    (1e-08, -3.1343686589124524),
+    (0.0018001, -2.732563923138336),
+    (0.010, -2.41276589008678),
+    (0.060, -1.7881244975330157),
+    (0.125, -1.3752523669869274),
+    (0.250, -0.831711193579736),
+    (0.400, -0.3167954512395289),
+    (0.419, -0.25586025626919906),
+    (0.421, -0.24947570750445663),
+    (0.750, 0.831711193579736),
+    (0.940, 1.7881244975330153),
+    (0.9999999996, 3.1391220839917167),
+]
+
+@pytest.mark.parametrize("p, expected", _cosinvcdf_close)
+def test_cosine_invcdf(p, expected):
+    assert_allclose(_cosine_invcdf(p), expected, rtol=1e-14)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dc9ed50cec9503edb77064cfa209c9d81573214
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py
@@ -0,0 +1,363 @@
+from collections.abc import Callable
+
+import pytest
+from itertools import product
+from numpy.testing import assert_allclose, suppress_warnings
+from scipy import special
+from scipy.special import cython_special
+
+
+bint_points = [True, False]
+int_points = [-10, -1, 1, 10]
+real_points = [-10.0, -1.0, 1.0, 10.0]
+complex_points = [complex(*tup) for tup in product(real_points, repeat=2)]
+
+
+CYTHON_SIGNATURE_MAP = {
+    'b': 'bint',
+    'f': 'float',
+    'd': 'double',
+    'g': 'long double',
+    'F': 'float complex',
+    'D': 'double complex',
+    'G': 'long double complex',
+    'i': 'int',
+    'l': 'long'
+}
+
+
+TEST_POINTS = {
+    'b': bint_points,
+    'f': real_points,
+    'd': real_points,
+    'g': real_points,
+    'F': complex_points,
+    'D': complex_points,
+    'G': complex_points,
+    'i': int_points,
+    'l': int_points,
+}
+
+
+PARAMS: list[tuple[Callable, Callable, tuple[str, ...], str | None]] = [
+    (special.agm, cython_special.agm, ('dd',), None),
+    (special.airy, cython_special._airy_pywrap, ('d', 'D'), None),
+    (special.airye, cython_special._airye_pywrap, ('d', 'D'), None),
+    (special.bdtr, cython_special.bdtr, ('dld', 'ddd'), None),
+    (special.bdtrc, cython_special.bdtrc, ('dld', 'ddd'), None),
+    (special.bdtri, cython_special.bdtri, ('dld', 'ddd'), None),
+    (special.bdtrik, cython_special.bdtrik, ('ddd',), None),
+    (special.bdtrin, cython_special.bdtrin, ('ddd',), None),
+    (special.bei, cython_special.bei, ('d',), None),
+    (special.beip, cython_special.beip, ('d',), None),
+    (special.ber, cython_special.ber, ('d',), None),
+    (special.berp, cython_special.berp, ('d',), None),
+    (special.besselpoly, cython_special.besselpoly, ('ddd',), None),
+    (special.beta, cython_special.beta, ('dd',), None),
+    (special.betainc, cython_special.betainc, ('ddd',), None),
+    (special.betaincc, cython_special.betaincc, ('ddd',), None),
+    (special.betaincinv, cython_special.betaincinv, ('ddd',), None),
+    (special.betainccinv, cython_special.betainccinv, ('ddd',), None),
+    (special.betaln, cython_special.betaln, ('dd',), None),
+    (special.binom, cython_special.binom, ('dd',), None),
+    (special.boxcox, cython_special.boxcox, ('dd',), None),
+    (special.boxcox1p, cython_special.boxcox1p, ('dd',), None),
+    (special.btdtria, cython_special.btdtria, ('ddd',), None),
+    (special.btdtrib, cython_special.btdtrib, ('ddd',), None),
+    (special.cbrt, cython_special.cbrt, ('d',), None),
+    (special.chdtr, cython_special.chdtr, ('dd',), None),
+    (special.chdtrc, cython_special.chdtrc, ('dd',), None),
+    (special.chdtri, cython_special.chdtri, ('dd',), None),
+    (special.chdtriv, cython_special.chdtriv, ('dd',), None),
+    (special.chndtr, cython_special.chndtr, ('ddd',), None),
+    (special.chndtridf, cython_special.chndtridf, ('ddd',), None),
+    (special.chndtrinc, cython_special.chndtrinc, ('ddd',), None),
+    (special.chndtrix, cython_special.chndtrix, ('ddd',), None),
+    (special.cosdg, cython_special.cosdg, ('d',), None),
+    (special.cosm1, cython_special.cosm1, ('d',), None),
+    (special.cotdg, cython_special.cotdg, ('d',), None),
+    (special.dawsn, cython_special.dawsn, ('d', 'D'), None),
+    (special.ellipe, cython_special.ellipe, ('d',), None),
+    (special.ellipeinc, cython_special.ellipeinc, ('dd',), None),
+    (special.ellipj, cython_special._ellipj_pywrap, ('dd',), None),
+    (special.ellipkinc, cython_special.ellipkinc, ('dd',), None),
+    (special.ellipkm1, cython_special.ellipkm1, ('d',), None),
+    (special.ellipk, cython_special.ellipk, ('d',), None),
+    (special.elliprc, cython_special.elliprc, ('dd', 'DD'), None),
+    (special.elliprd, cython_special.elliprd, ('ddd', 'DDD'), None),
+    (special.elliprf, cython_special.elliprf, ('ddd', 'DDD'), None),
+    (special.elliprg, cython_special.elliprg, ('ddd', 'DDD'), None),
+    (special.elliprj, cython_special.elliprj, ('dddd', 'DDDD'), None),
+    (special.entr, cython_special.entr, ('d',), None),
+    (special.erf, cython_special.erf, ('d', 'D'), None),
+    (special.erfc, cython_special.erfc, ('d', 'D'), None),
+    (special.erfcx, cython_special.erfcx, ('d', 'D'), None),
+    (special.erfi, cython_special.erfi, ('d', 'D'), None),
+    (special.erfinv, cython_special.erfinv, ('d',), None),
+    (special.erfcinv, cython_special.erfcinv, ('d',), None),
+    (special.eval_chebyc, cython_special.eval_chebyc, ('dd', 'dD', 'ld'), None),
+    (special.eval_chebys, cython_special.eval_chebys, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_chebyt, cython_special.eval_chebyt, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_chebyu, cython_special.eval_chebyu, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_gegenbauer, cython_special.eval_gegenbauer, ('ddd', 'ddD', 'ldd'),
+     'd and l differ for negative int'),
+    (special.eval_genlaguerre, cython_special.eval_genlaguerre, ('ddd', 'ddD', 'ldd'),
+     'd and l differ for negative int'),
+    (special.eval_hermite, cython_special.eval_hermite, ('ld',), None),
+    (special.eval_hermitenorm, cython_special.eval_hermitenorm, ('ld',), None),
+    (special.eval_jacobi, cython_special.eval_jacobi, ('dddd', 'dddD', 'lddd'),
+     'd and l differ for negative int'),
+    (special.eval_laguerre, cython_special.eval_laguerre, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_legendre, cython_special.eval_legendre, ('dd', 'dD', 'ld'), None),
+    (special.eval_sh_chebyt, cython_special.eval_sh_chebyt, ('dd', 'dD', 'ld'), None),
+    (special.eval_sh_chebyu, cython_special.eval_sh_chebyu, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_sh_jacobi, cython_special.eval_sh_jacobi, ('dddd', 'dddD', 'lddd'),
+     'd and l differ for negative int'),
+    (special.eval_sh_legendre, cython_special.eval_sh_legendre, ('dd', 'dD', 'ld'),
+     None),
+    (special.exp1, cython_special.exp1, ('d', 'D'), None),
+    (special.exp10, cython_special.exp10, ('d',), None),
+    (special.exp2, cython_special.exp2, ('d',), None),
+    (special.expi, cython_special.expi, ('d', 'D'), None),
+    (special.expit, cython_special.expit, ('f', 'd', 'g'), None),
+    (special.expm1, cython_special.expm1, ('d', 'D'), None),
+    (special.expn, cython_special.expn, ('ld', 'dd'), None),
+    (special.exprel, cython_special.exprel, ('d',), None),
+    (special.fdtr, cython_special.fdtr, ('ddd',), None),
+    (special.fdtrc, cython_special.fdtrc, ('ddd',), None),
+    (special.fdtri, cython_special.fdtri, ('ddd',), None),
+    (special.fdtridfd, cython_special.fdtridfd, ('ddd',), None),
+    (special.fresnel, cython_special._fresnel_pywrap, ('d', 'D'), None),
+    (special.gamma, cython_special.gamma, ('d', 'D'), None),
+    (special.gammainc, cython_special.gammainc, ('dd',), None),
+    (special.gammaincc, cython_special.gammaincc, ('dd',), None),
+    (special.gammainccinv, cython_special.gammainccinv, ('dd',), None),
+    (special.gammaincinv, cython_special.gammaincinv, ('dd',), None),
+    (special.gammaln, cython_special.gammaln, ('d',), None),
+    (special.gammasgn, cython_special.gammasgn, ('d',), None),
+    (special.gdtr, cython_special.gdtr, ('ddd',), None),
+    (special.gdtrc, cython_special.gdtrc, ('ddd',), None),
+    (special.gdtria, cython_special.gdtria, ('ddd',), None),
+    (special.gdtrib, cython_special.gdtrib, ('ddd',), None),
+    (special.gdtrix, cython_special.gdtrix, ('ddd',), None),
+    (special.hankel1, cython_special.hankel1, ('dD',), None),
+    (special.hankel1e, cython_special.hankel1e, ('dD',), None),
+    (special.hankel2, cython_special.hankel2, ('dD',), None),
+    (special.hankel2e, cython_special.hankel2e, ('dD',), None),
+    (special.huber, cython_special.huber, ('dd',), None),
+    (special.hyp0f1, cython_special.hyp0f1, ('dd', 'dD'), None),
+    (special.hyp1f1, cython_special.hyp1f1, ('ddd', 'ddD'), None),
+    (special.hyp2f1, cython_special.hyp2f1, ('dddd', 'dddD'), None),
+    (special.hyperu, cython_special.hyperu, ('ddd',), None),
+    (special.i0, cython_special.i0, ('d',), None),
+    (special.i0e, cython_special.i0e, ('d',), None),
+    (special.i1, cython_special.i1, ('d',), None),
+    (special.i1e, cython_special.i1e, ('d',), None),
+    (special.inv_boxcox, cython_special.inv_boxcox, ('dd',), None),
+    (special.inv_boxcox1p, cython_special.inv_boxcox1p, ('dd',), None),
+    (special.it2i0k0, cython_special._it2i0k0_pywrap, ('d',), None),
+    (special.it2j0y0, cython_special._it2j0y0_pywrap, ('d',), None),
+    (special.it2struve0, cython_special.it2struve0, ('d',), None),
+    (special.itairy, cython_special._itairy_pywrap, ('d',), None),
+    (special.iti0k0, cython_special._iti0k0_pywrap, ('d',), None),
+    (special.itj0y0, cython_special._itj0y0_pywrap, ('d',), None),
+    (special.itmodstruve0, cython_special.itmodstruve0, ('d',), None),
+    (special.itstruve0, cython_special.itstruve0, ('d',), None),
+    (special.iv, cython_special.iv, ('dd', 'dD'), None),
+    (special.ive, cython_special.ive, ('dd', 'dD'), None),
+    (special.j0, cython_special.j0, ('d',), None),
+    (special.j1, cython_special.j1, ('d',), None),
+    (special.jv, cython_special.jv, ('dd', 'dD'), None),
+    (special.jve, cython_special.jve, ('dd', 'dD'), None),
+    (special.k0, cython_special.k0, ('d',), None),
+    (special.k0e, cython_special.k0e, ('d',), None),
+    (special.k1, cython_special.k1, ('d',), None),
+    (special.k1e, cython_special.k1e, ('d',), None),
+    (special.kei, cython_special.kei, ('d',), None),
+    (special.keip, cython_special.keip, ('d',), None),
+    (special.kelvin, cython_special._kelvin_pywrap, ('d',), None),
+    (special.ker, cython_special.ker, ('d',), None),
+    (special.kerp, cython_special.kerp, ('d',), None),
+    (special.kl_div, cython_special.kl_div, ('dd',), None),
+    (special.kn, cython_special.kn, ('ld', 'dd'), None),
+    (special.kolmogi, cython_special.kolmogi, ('d',), None),
+    (special.kolmogorov, cython_special.kolmogorov, ('d',), None),
+    (special.kv, cython_special.kv, ('dd', 'dD'), None),
+    (special.kve, cython_special.kve, ('dd', 'dD'), None),
+    (special.log1p, cython_special.log1p, ('d', 'D'), None),
+    (special.log_expit, cython_special.log_expit, ('f', 'd', 'g'), None),
+    (special.log_ndtr, cython_special.log_ndtr, ('d', 'D'), None),
+    (special.log_wright_bessel, cython_special.log_wright_bessel, ('ddd',), None),
+    (special.ndtri_exp, cython_special.ndtri_exp, ('d',), None),
+    (special.loggamma, cython_special.loggamma, ('D',), None),
+    (special.logit, cython_special.logit, ('f', 'd', 'g'), None),
+    (special.lpmv, cython_special.lpmv, ('ddd',), None),
+    (special.mathieu_a, cython_special.mathieu_a, ('dd',), None),
+    (special.mathieu_b, cython_special.mathieu_b, ('dd',), None),
+    (special.mathieu_cem, cython_special._mathieu_cem_pywrap, ('ddd',), None),
+    (special.mathieu_modcem1, cython_special._mathieu_modcem1_pywrap, ('ddd',), None),
+    (special.mathieu_modcem2, cython_special._mathieu_modcem2_pywrap, ('ddd',), None),
+    (special.mathieu_modsem1, cython_special._mathieu_modsem1_pywrap, ('ddd',), None),
+    (special.mathieu_modsem2, cython_special._mathieu_modsem2_pywrap, ('ddd',), None),
+    (special.mathieu_sem, cython_special._mathieu_sem_pywrap, ('ddd',), None),
+    (special.modfresnelm, cython_special._modfresnelm_pywrap, ('d',), None),
+    (special.modfresnelp, cython_special._modfresnelp_pywrap, ('d',), None),
+    (special.modstruve, cython_special.modstruve, ('dd',), None),
+    (special.nbdtr, cython_special.nbdtr, ('lld', 'ddd'), None),
+    (special.nbdtrc, cython_special.nbdtrc, ('lld', 'ddd'), None),
+    (special.nbdtri, cython_special.nbdtri, ('lld', 'ddd'), None),
+    (special.nbdtrik, cython_special.nbdtrik, ('ddd',), None),
+    (special.nbdtrin, cython_special.nbdtrin, ('ddd',), None),
+    (special.ncfdtr, cython_special.ncfdtr, ('dddd',), None),
+    (special.ncfdtri, cython_special.ncfdtri, ('dddd',), None),
+    (special.ncfdtridfd, cython_special.ncfdtridfd, ('dddd',), None),
+    (special.ncfdtridfn, cython_special.ncfdtridfn, ('dddd',), None),
+    (special.ncfdtrinc, cython_special.ncfdtrinc, ('dddd',), None),
+    (special.nctdtr, cython_special.nctdtr, ('ddd',), None),
+    (special.nctdtridf, cython_special.nctdtridf, ('ddd',), None),
+    (special.nctdtrinc, cython_special.nctdtrinc, ('ddd',), None),
+    (special.nctdtrit, cython_special.nctdtrit, ('ddd',), None),
+    (special.ndtr, cython_special.ndtr, ('d', 'D'), None),
+    (special.ndtri, cython_special.ndtri, ('d',), None),
+    (special.nrdtrimn, cython_special.nrdtrimn, ('ddd',), None),
+    (special.nrdtrisd, cython_special.nrdtrisd, ('ddd',), None),
+    (special.obl_ang1, cython_special._obl_ang1_pywrap, ('dddd',), None),
+    (special.obl_ang1_cv, cython_special._obl_ang1_cv_pywrap, ('ddddd',), None),
+    (special.obl_cv, cython_special.obl_cv, ('ddd',), None),
+    (special.obl_rad1, cython_special._obl_rad1_pywrap, ('dddd',), "see gh-6211"),
+    (special.obl_rad1_cv, cython_special._obl_rad1_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.obl_rad2, cython_special._obl_rad2_pywrap, ('dddd',), "see gh-6211"),
+    (special.obl_rad2_cv, cython_special._obl_rad2_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.pbdv, cython_special._pbdv_pywrap, ('dd',), None),
+    (special.pbvv, cython_special._pbvv_pywrap, ('dd',), None),
+    (special.pbwa, cython_special._pbwa_pywrap, ('dd',), None),
+    (special.pdtr, cython_special.pdtr, ('dd', 'dd'), None),
+    (special.pdtrc, cython_special.pdtrc, ('dd', 'dd'), None),
+    (special.pdtri, cython_special.pdtri, ('ld', 'dd'), None),
+    (special.pdtrik, cython_special.pdtrik, ('dd',), None),
+    (special.poch, cython_special.poch, ('dd',), None),
+    (special.powm1, cython_special.powm1, ('dd',), None),
+    (special.pro_ang1, cython_special._pro_ang1_pywrap, ('dddd',), None),
+    (special.pro_ang1_cv, cython_special._pro_ang1_cv_pywrap, ('ddddd',), None),
+    (special.pro_cv, cython_special.pro_cv, ('ddd',), None),
+    (special.pro_rad1, cython_special._pro_rad1_pywrap, ('dddd',), "see gh-6211"),
+    (special.pro_rad1_cv, cython_special._pro_rad1_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.pro_rad2, cython_special._pro_rad2_pywrap, ('dddd',), "see gh-6211"),
+    (special.pro_rad2_cv, cython_special._pro_rad2_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.pseudo_huber, cython_special.pseudo_huber, ('dd',), None),
+    (special.psi, cython_special.psi, ('d', 'D'), None),
+    (special.radian, cython_special.radian, ('ddd',), None),
+    (special.rel_entr, cython_special.rel_entr, ('dd',), None),
+    (special.rgamma, cython_special.rgamma, ('d', 'D'), None),
+    (special.round, cython_special.round, ('d',), None),
+    (special.spherical_jn, cython_special.spherical_jn, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.spherical_yn, cython_special.spherical_yn, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.spherical_in, cython_special.spherical_in, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.spherical_kn, cython_special.spherical_kn, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.shichi, cython_special._shichi_pywrap, ('d', 'D'), None),
+    (special.sici, cython_special._sici_pywrap, ('d', 'D'), None),
+    (special.sindg, cython_special.sindg, ('d',), None),
+    (special.smirnov, cython_special.smirnov, ('ld', 'dd'), None),
+    (special.smirnovi, cython_special.smirnovi, ('ld', 'dd'), None),
+    (special.spence, cython_special.spence, ('d', 'D'), None),
+    (special.sph_harm, cython_special.sph_harm, ('lldd', 'dddd'), None),
+    (special.stdtr, cython_special.stdtr, ('dd',), None),
+    (special.stdtridf, cython_special.stdtridf, ('dd',), None),
+    (special.stdtrit, cython_special.stdtrit, ('dd',), None),
+    (special.struve, cython_special.struve, ('dd',), None),
+    (special.tandg, cython_special.tandg, ('d',), None),
+    (special.tklmbda, cython_special.tklmbda, ('dd',), None),
+    (special.voigt_profile, cython_special.voigt_profile, ('ddd',), None),
+    (special.wofz, cython_special.wofz, ('D',), None),
+    (special.wright_bessel, cython_special.wright_bessel, ('ddd',), None),
+    (special.wrightomega, cython_special.wrightomega, ('D',), None),
+    (special.xlog1py, cython_special.xlog1py, ('dd', 'DD'), None),
+    (special.xlogy, cython_special.xlogy, ('dd', 'DD'), None),
+    (special.y0, cython_special.y0, ('d',), None),
+    (special.y1, cython_special.y1, ('d',), None),
+    (special.yn, cython_special.yn, ('ld', 'dd'), None),
+    (special.yv, cython_special.yv, ('dd', 'dD'), None),
+    (special.yve, cython_special.yve, ('dd', 'dD'), None),
+    (special.zetac, cython_special.zetac, ('d',), None),
+    (special.owens_t, cython_special.owens_t, ('dd',), None)
+]
+
+
+IDS = [x[0].__name__ for x in PARAMS]
+
+
+def _generate_test_points(typecodes):
+    axes = tuple(TEST_POINTS[x] for x in typecodes)
+    pts = list(product(*axes))
+    return pts
+
+
+def test_cython_api_completeness():
+    # Check that everything is tested
+    for name in dir(cython_special):
+        func = getattr(cython_special, name)
+        if callable(func) and not name.startswith('_'):
+            for _, cyfun, _, _ in PARAMS:
+                if cyfun is func:
+                    break
+            else:
+                raise RuntimeError(f"{name} missing from tests!")
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.fail_slow(20)
+@pytest.mark.parametrize("param", PARAMS, ids=IDS)
+def test_cython_api(param):
+    pyfunc, cyfunc, specializations, knownfailure = param
+    if knownfailure:
+        pytest.xfail(reason=knownfailure)
+
+    # Check which parameters are expected to be fused types
+    max_params = max(len(spec) for spec in specializations)
+    values = [set() for _ in range(max_params)]
+    for typecodes in specializations:
+        for j, v in enumerate(typecodes):
+            values[j].add(v)
+    seen = set()
+    is_fused_code = [False] * len(values)
+    for j, v in enumerate(values):
+        vv = tuple(sorted(v))
+        if vv in seen:
+            continue
+        is_fused_code[j] = (len(v) > 1)
+        seen.add(vv)
+
+    # Check results
+    for typecodes in specializations:
+        # Pick the correct specialized function
+        signature = [CYTHON_SIGNATURE_MAP[code]
+                     for j, code in enumerate(typecodes)
+                     if is_fused_code[j]]
+
+        if signature:
+            cy_spec_func = cyfunc[tuple(signature)]
+        else:
+            signature = None
+            cy_spec_func = cyfunc
+
+        # Test it
+        pts = _generate_test_points(typecodes)
+        for pt in pts:
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning)
+                pyval = pyfunc(*pt)
+                cyval = cy_spec_func(*pt)
+            assert_allclose(cyval, pyval, err_msg=f"{pt} {typecodes} {signature}")
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fc89a328cf20da0fd243ab7603cf316ecf2acb4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py
@@ -0,0 +1,719 @@
+import importlib.resources
+
+import numpy as np
+from numpy.testing import suppress_warnings
+import pytest
+
+from scipy.special import (
+    lpn, lpmn, lpmv, lqn, lqmn, sph_harm, eval_legendre, eval_hermite,
+    eval_laguerre, eval_genlaguerre, binom, cbrt, expm1, log1p, zeta,
+    jn, jv, jvp, yn, yv, yvp, iv, ivp, kn, kv, kvp,
+    gamma, gammaln, gammainc, gammaincc, gammaincinv, gammainccinv, digamma,
+    beta, betainc, betaincinv, poch,
+    ellipe, ellipeinc, ellipk, ellipkm1, ellipkinc,
+    elliprc, elliprd, elliprf, elliprg, elliprj,
+    erf, erfc, erfinv, erfcinv, exp1, expi, expn,
+    bdtrik, btdtria, btdtrib, chndtr, gdtr, gdtrc, gdtrix, gdtrib,
+    nbdtrik, pdtrik, owens_t,
+    mathieu_a, mathieu_b, mathieu_cem, mathieu_sem, mathieu_modcem1,
+    mathieu_modsem1, mathieu_modcem2, mathieu_modsem2,
+    ellip_harm, ellip_harm_2, spherical_jn, spherical_yn, wright_bessel
+)
+from scipy.integrate import IntegrationWarning
+
+from scipy.special._testutils import FuncData
+
+
+# The npz files are generated, and hence may live in the build dir. We can only
+# access them through `importlib.resources`, not an explicit path from `__file__`
+_datadir = importlib.resources.files('scipy.special.tests.data')
+
+_boost_npz = _datadir.joinpath('boost.npz')
+with importlib.resources.as_file(_boost_npz) as f:
+    DATASETS_BOOST = np.load(f)
+
+_gsl_npz = _datadir.joinpath('gsl.npz')
+with importlib.resources.as_file(_gsl_npz) as f:
+    DATASETS_GSL = np.load(f)
+
+_local_npz = _datadir.joinpath('local.npz')
+with importlib.resources.as_file(_local_npz) as f:
+    DATASETS_LOCAL = np.load(f)
+
+
+def data(func, dataname, *a, **kw):
+    kw.setdefault('dataname', dataname)
+    return FuncData(func, DATASETS_BOOST[dataname], *a, **kw)
+
+
+def data_gsl(func, dataname, *a, **kw):
+    kw.setdefault('dataname', dataname)
+    return FuncData(func, DATASETS_GSL[dataname], *a, **kw)
+
+
+def data_local(func, dataname, *a, **kw):
+    kw.setdefault('dataname', dataname)
+    return FuncData(func, DATASETS_LOCAL[dataname], *a, **kw)
+
+
+# The functions lpn, lpmn, clpmn, and sph_harm appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all,
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn),
+# and sph_harm_y respectively. The deprecated functions listed above are
+# implemented as shims around their respective replacements. The replacements
+# are tested separately, but tests for the deprecated functions remain to
+# verify the correctness of the shims.
+
+
+def ellipk_(k):
+    return ellipk(k*k)
+
+
+def ellipkinc_(f, k):
+    return ellipkinc(f, k*k)
+
+
+def ellipe_(k):
+    return ellipe(k*k)
+
+
+def ellipeinc_(f, k):
+    return ellipeinc(f, k*k)
+
+
+def zeta_(x):
+    return zeta(x, 1.)
+
+
+def assoc_legendre_p_boost_(nu, mu, x):
+    # the boost test data is for integer orders only
+    return lpmv(mu, nu.astype(int), x)
+
+def legendre_p_via_assoc_(nu, x):
+    return lpmv(0, nu, x)
+
+def lpn_(n, x):
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        return lpn(n.astype('l'), x)[0][-1]
+
+def lqn_(n, x):
+    return lqn(n.astype('l'), x)[0][-1]
+
+def legendre_p_via_lpmn(n, x):
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        return lpmn(0, n, x)[0][0,-1]
+
+def legendre_q_via_lqmn(n, x):
+    return lqmn(0, n, x)[0][0,-1]
+
+def mathieu_ce_rad(m, q, x):
+    return mathieu_cem(m, q, x*180/np.pi)[0]
+
+
+def mathieu_se_rad(m, q, x):
+    return mathieu_sem(m, q, x*180/np.pi)[0]
+
+
+def mathieu_mc1_scaled(m, q, x):
+    # GSL follows a different normalization.
+    # We follow Abramowitz & Stegun, they apparently something else.
+    return mathieu_modcem1(m, q, x)[0] * np.sqrt(np.pi/2)
+
+
+def mathieu_ms1_scaled(m, q, x):
+    return mathieu_modsem1(m, q, x)[0] * np.sqrt(np.pi/2)
+
+
+def mathieu_mc2_scaled(m, q, x):
+    return mathieu_modcem2(m, q, x)[0] * np.sqrt(np.pi/2)
+
+
+def mathieu_ms2_scaled(m, q, x):
+    return mathieu_modsem2(m, q, x)[0] * np.sqrt(np.pi/2)
+
+def eval_legendre_ld(n, x):
+    return eval_legendre(n.astype('l'), x)
+
+def eval_legendre_dd(n, x):
+    return eval_legendre(n.astype('d'), x)
+
+def eval_hermite_ld(n, x):
+    return eval_hermite(n.astype('l'), x)
+
+def eval_laguerre_ld(n, x):
+    return eval_laguerre(n.astype('l'), x)
+
+def eval_laguerre_dd(n, x):
+    return eval_laguerre(n.astype('d'), x)
+
+def eval_genlaguerre_ldd(n, a, x):
+    return eval_genlaguerre(n.astype('l'), a, x)
+
+def eval_genlaguerre_ddd(n, a, x):
+    return eval_genlaguerre(n.astype('d'), a, x)
+
+def bdtrik_comp(y, n, p):
+    return bdtrik(1-y, n, p)
+
+def btdtria_comp(p, b, x):
+    return btdtria(1-p, b, x)
+
+def btdtrib_comp(a, p, x):
+    return btdtrib(a, 1-p, x)
+
+def gdtr_(p, x):
+    return gdtr(1.0, p, x)
+
+def gdtrc_(p, x):
+    return gdtrc(1.0, p, x)
+
+def gdtrix_(b, p):
+    return gdtrix(1.0, b, p)
+
+def gdtrix_comp(b, p):
+    return gdtrix(1.0, b, 1-p)
+
+def gdtrib_(p, x):
+    return gdtrib(1.0, p, x)
+
+def gdtrib_comp(p, x):
+    return gdtrib(1.0, 1-p, x)
+
+def nbdtrik_comp(y, n, p):
+    return nbdtrik(1-y, n, p)
+
+def pdtrik_comp(p, m):
+    return pdtrik(1-p, m)
+
+def poch_(z, m):
+    return 1.0 / poch(z, m)
+
+def poch_minus(z, m):
+    return 1.0 / poch(z, -m)
+
+def spherical_jn_(n, x):
+    return spherical_jn(n.astype('l'), x)
+
+def spherical_yn_(n, x):
+    return spherical_yn(n.astype('l'), x)
+
+def sph_harm_(m, n, theta, phi):
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        y = sph_harm(m, n, theta, phi)
+    return (y.real, y.imag)
+
+def cexpm1(x, y):
+    z = expm1(x + 1j*y)
+    return z.real, z.imag
+
+def clog1p(x, y):
+    z = log1p(x + 1j*y)
+    return z.real, z.imag
+
+
+BOOST_TESTS = [
+        data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p',
+             (0,1,2), 3, rtol=1e-11),
+
+        data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=1e-11),
+        data(legendre_p_via_assoc_, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=9.6e-14),
+        data(legendre_p_via_lpmn, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=5e-14, vectorized=False),
+        data(legendre_p_via_lpmn, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=3e-13, vectorized=False),
+        data(lpn_, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=5e-14, vectorized=False),
+        data(lpn_, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=3e-13, vectorized=False),
+        data(eval_legendre_ld, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=6e-14),
+        data(eval_legendre_ld, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=2e-13),
+        data(eval_legendre_dd, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=2e-14),
+        data(eval_legendre_dd, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=2e-13),
+
+        data(lqn_, 'legendre_p_ipp-legendre_p',
+             (0,1), 3, rtol=2e-14, vectorized=False),
+        data(lqn_, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 3, rtol=2e-12, vectorized=False),
+        data(legendre_q_via_lqmn, 'legendre_p_ipp-legendre_p',
+             (0,1), 3, rtol=2e-14, vectorized=False),
+        data(legendre_q_via_lqmn, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 3, rtol=2e-12, vectorized=False),
+
+        data(beta, 'beta_exp_data_ipp-beta_exp_data',
+             (0,1), 2, rtol=1e-13),
+        data(beta, 'beta_exp_data_ipp-beta_exp_data',
+             (0,1), 2, rtol=1e-13),
+        data(beta, 'beta_med_data_ipp-beta_med_data',
+             (0,1), 2, rtol=5e-13),
+
+        data(betainc, 'ibeta_small_data_ipp-ibeta_small_data',
+             (0,1,2), 5, rtol=6e-15),
+        data(betainc, 'ibeta_data_ipp-ibeta_data',
+             (0,1,2), 5, rtol=5e-13),
+        data(betainc, 'ibeta_int_data_ipp-ibeta_int_data',
+             (0,1,2), 5, rtol=2e-14),
+        data(betainc, 'ibeta_large_data_ipp-ibeta_large_data',
+             (0,1,2), 5, rtol=4e-10),
+
+        data(betaincinv, 'ibeta_inv_data_ipp-ibeta_inv_data',
+             (0,1,2), 3, rtol=1e-5),
+
+        data(btdtria, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (2,0,1), 3, rtol=5e-9),
+        data(btdtria_comp, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (2,0,1), 4, rtol=5e-9),
+
+        data(btdtrib, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (0,2,1), 5, rtol=5e-9),
+        data(btdtrib_comp, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (0,2,1), 6, rtol=5e-9),
+
+        data(binom, 'binomial_data_ipp-binomial_data',
+             (0,1), 2, rtol=1e-13),
+        data(binom, 'binomial_large_data_ipp-binomial_large_data',
+             (0,1), 2, rtol=5e-13),
+
+        data(bdtrik, 'binomial_quantile_ipp-binomial_quantile_data',
+             (2,0,1), 3, rtol=5e-9),
+        data(bdtrik_comp, 'binomial_quantile_ipp-binomial_quantile_data',
+             (2,0,1), 4, rtol=5e-9),
+
+        data(nbdtrik, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data',
+             (2,0,1), 3, rtol=4e-9),
+        data(nbdtrik_comp,
+             'negative_binomial_quantile_ipp-negative_binomial_quantile_data',
+             (2,0,1), 4, rtol=4e-9),
+
+        data(pdtrik, 'poisson_quantile_ipp-poisson_quantile_data',
+             (1,0), 2, rtol=3e-9),
+        data(pdtrik_comp, 'poisson_quantile_ipp-poisson_quantile_data',
+             (1,0), 3, rtol=4e-9),
+
+        data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0),
+
+        data(digamma, 'digamma_data_ipp-digamma_data', 0, 1),
+        data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1),
+        data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=2e-13),
+        data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13),
+        data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-15),
+        data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-15),
+        data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1, rtol=1e-15),
+        data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1, rtol=1e-14),
+
+        data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1),
+        data(ellipkinc_, 'ellint_f_data_ipp-ellint_f_data', (0,1), 2, rtol=1e-14),
+        data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1),
+        data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14),
+
+        data(erf, 'erf_data_ipp-erf_data', 0, 1),
+        data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-13),
+        data(erfc, 'erf_data_ipp-erf_data', 0, 2, rtol=6e-15),
+        data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1),
+        data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1),
+        data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2, rtol=4e-14),
+        data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1),
+        data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1, rtol=1e-13),
+        data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2),
+
+        data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1),
+        data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1),
+        data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1,
+             param_filter=(lambda s: s > 0)),
+
+        data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2, rtol=1e-13),
+        data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9),
+        data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13),
+        data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1, rtol=1e-13),
+        data(expi, 'expinti_data_long_ipp-expinti_data_long', 0, 1),
+
+        data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2),
+        data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14),
+
+        data(gamma, 'test_gamma_data_ipp-near_0', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_1', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_2', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1, rtol=7e-12),
+        data(gamma, 'test_gamma_data_ipp-factorials', 0, 1, rtol=4e-14),
+        data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-factorials', 0j, 1, rtol=2e-13),
+        data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10),
+        data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-factorials', 0, 2),
+
+        data(gammainc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=5e-15),
+        data(gammainc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
+        data(gammainc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
+        data(gammainc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=1e-12),
+
+        data(gdtr_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=1e-13),
+        data(gdtr_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
+        data(gdtr_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
+        data(gdtr_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=2e-9),
+
+        data(gammaincc, 'igamma_small_data_ipp-igamma_small_data',
+             (0,1), 3, rtol=1e-13),
+        data(gammaincc, 'igamma_med_data_ipp-igamma_med_data',
+             (0,1), 3, rtol=2e-13),
+        data(gammaincc, 'igamma_int_data_ipp-igamma_int_data',
+             (0,1), 3, rtol=4e-14),
+        data(gammaincc, 'igamma_big_data_ipp-igamma_big_data',
+             (0,1), 3, rtol=1e-11),
+
+        data(gdtrc_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13),
+        data(gdtrc_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13),
+        data(gdtrc_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14),
+        data(gdtrc_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11),
+
+        data(gdtrib_, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 2, rtol=5e-9),
+        data(gdtrib_comp, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 3, rtol=5e-9),
+
+        data(poch_, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data',
+             (0,1), 2, rtol=2e-13),
+        data(poch_, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int',
+             (0,1), 2,),
+        data(poch_, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2',
+             (0,1), 2,),
+        data(poch_minus, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data',
+             (0,1), 3, rtol=2e-13),
+        data(poch_minus, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int',
+             (0,1), 3),
+        data(poch_minus, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2',
+             (0,1), 3),
+
+        data(eval_hermite_ld, 'hermite_ipp-hermite',
+             (0,1), 2, rtol=2e-14),
+
+        data(eval_laguerre_ld, 'laguerre2_ipp-laguerre2',
+             (0,1), 2, rtol=7e-12),
+        data(eval_laguerre_dd, 'laguerre2_ipp-laguerre2',
+             (0,1), 2, knownfailure='hyp2f1 insufficiently accurate.'),
+        data(eval_genlaguerre_ldd, 'laguerre3_ipp-laguerre3',
+             (0,1,2), 3, rtol=2e-13),
+        data(eval_genlaguerre_ddd, 'laguerre3_ipp-laguerre3',
+             (0,1,2), 3, knownfailure='hyp2f1 insufficiently accurate.'),
+
+        data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1),
+        data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2),
+
+        data(iv, 'bessel_i_data_ipp-bessel_i_data',
+             (0,1), 2, rtol=1e-12),
+        data(iv, 'bessel_i_data_ipp-bessel_i_data',
+             (0,1j), 2, rtol=2e-10, atol=1e-306),
+        data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data',
+             (0,1), 2, rtol=1e-9),
+        data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data',
+             (0,1j), 2, rtol=2e-10),
+
+        data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data',
+             (0,1), 2, rtol=1.2e-13),
+        data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data',
+             (0,1j), 2, rtol=1.2e-13, atol=1e-300),
+
+        data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
+        data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
+        data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11),
+        data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11),
+
+        data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
+        data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
+        data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12),
+        data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12),
+
+        data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data',
+             (0,1), 2, rtol=1e-13),
+        data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data',
+             (0,1j), 2, rtol=1e-13),
+        data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data',
+             (0,1), 2, rtol=1e-11),
+        data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data',
+             (0,1j), 2, rtol=2e-11),
+
+        data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
+
+        data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
+        data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12),
+        data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12),
+        data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12),
+
+        data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data',
+             (0,1), 2, rtol=3e-14),
+        data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data',
+             (0,1j), 2, rtol=3e-14),
+        data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1), 2, rtol=7e-14),
+        data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1j), 2, rtol=7e-14),
+
+        data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12),
+        data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
+
+        data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
+        data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12),
+        data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-10),
+        data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10),
+
+        data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data',
+             (0, 1), 2, rtol=4e-9),
+        data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data',
+             (0, 1j), 2, rtol=4e-9),
+
+        data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+        data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+        data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+        data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+
+        data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 2, rtol=1e-11),
+        data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 2, rtol=1e-14),
+        data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 2, rtol=1e-11),
+
+        data(gammainccinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 3, rtol=1e-12),
+        data(gammainccinv, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 3, rtol=1e-14),
+        data(gammainccinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 3, rtol=1e-14),
+
+        data(gdtrix_, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 2, rtol=3e-13, knownfailure='gdtrix unflow some points'),
+        data(gdtrix_, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 2, rtol=3e-15),
+        data(gdtrix_, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 2),
+        data(gdtrix_comp, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 2, knownfailure='gdtrix bad some points'),
+        data(gdtrix_comp, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 3, rtol=6e-15),
+        data(gdtrix_comp, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 3),
+
+        data(chndtr, 'nccs_ipp-nccs',
+             (2,0,1), 3, rtol=3e-5),
+        data(chndtr, 'nccs_big_ipp-nccs_big',
+             (2,0,1), 3, rtol=5e-4, knownfailure='chndtr inaccurate some points'),
+
+        data(sph_harm_, 'spherical_harmonic_ipp-spherical_harmonic',
+             (1,0,3,2), (4,5), rtol=5e-11,
+             param_filter=(lambda p: np.ones(p.shape, '?'),
+                           lambda p: np.ones(p.shape, '?'),
+                           lambda p: np.logical_and(p < 2*np.pi, p >= 0),
+                           lambda p: np.logical_and(p < np.pi, p >= 0))),
+
+        data(spherical_jn_, 'sph_bessel_data_ipp-sph_bessel_data',
+             (0,1), 2, rtol=1e-13),
+        data(spherical_yn_, 'sph_neumann_data_ipp-sph_neumann_data',
+             (0,1), 2, rtol=8e-15),
+
+        data(owens_t, 'owens_t_ipp-owens_t',
+             (0, 1), 2, rtol=5e-14),
+        data(owens_t, 'owens_t_large_data_ipp-owens_t_large_data',
+             (0, 1), 2, rtol=8e-12),
+
+        # -- test data exists in boost but is not used in scipy --
+
+        # ibeta_derivative_data_ipp/ibeta_derivative_data.txt
+        # ibeta_derivative_int_data_ipp/ibeta_derivative_int_data.txt
+        # ibeta_derivative_large_data_ipp/ibeta_derivative_large_data.txt
+        # ibeta_derivative_small_data_ipp/ibeta_derivative_small_data.txt
+
+        # bessel_y01_prime_data_ipp/bessel_y01_prime_data.txt
+        # bessel_yn_prime_data_ipp/bessel_yn_prime_data.txt
+        # sph_bessel_prime_data_ipp/sph_bessel_prime_data.txt
+        # sph_neumann_prime_data_ipp/sph_neumann_prime_data.txt
+
+        # ellint_d2_data_ipp/ellint_d2_data.txt
+        # ellint_d_data_ipp/ellint_d_data.txt
+        # ellint_pi2_data_ipp/ellint_pi2_data.txt
+        # ellint_pi3_data_ipp/ellint_pi3_data.txt
+        # ellint_pi3_large_data_ipp/ellint_pi3_large_data.txt
+        data(elliprc, 'ellint_rc_data_ipp-ellint_rc_data', (0, 1), 2,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_data_ipp-ellint_rd_data', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_0xy_ipp-ellint_rd_0xy', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_0yy_ipp-ellint_rd_0yy', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_xxx_ipp-ellint_rd_xxx', (0, 1, 2), 3,
+             rtol=5e-16),
+        # Some of the following rtol for elliprd may be larger than 5e-16 to
+        # work around some hard cases in the Boost test where we get slightly
+        # larger error than the ideal bound when the x (==y) input is close to
+        # zero.
+        # Also the accuracy on 32-bit builds with g++ may suffer from excess
+        # loss of precision; see GCC bugzilla 323
+        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323
+        data(elliprd, 'ellint_rd_xxz_ipp-ellint_rd_xxz', (0, 1, 2), 3,
+             rtol=6.5e-16),
+        data(elliprd, 'ellint_rd_xyy_ipp-ellint_rd_xyy', (0, 1, 2), 3,
+             rtol=6e-16),
+        data(elliprf, 'ellint_rf_data_ipp-ellint_rf_data', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_xxx_ipp-ellint_rf_xxx', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_xyy_ipp-ellint_rf_xyy', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_xy0_ipp-ellint_rf_xy0', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_0yy_ipp-ellint_rf_0yy', (0, 1, 2), 3,
+             rtol=5e-16),
+        # The accuracy of R_G is primarily limited by R_D that is used
+        # internally. It is generally worse than R_D. Notice that we increased
+        # the rtol for R_G here. The cases with duplicate arguments are
+        # slightly less likely to be unbalanced (at least two arguments are
+        # already balanced) so the error bound is slightly better. Again,
+        # precision with g++ 32-bit is even worse.
+        data(elliprg, 'ellint_rg_ipp-ellint_rg', (0, 1, 2), 3,
+             rtol=8.0e-16),
+        data(elliprg, 'ellint_rg_xxx_ipp-ellint_rg_xxx', (0, 1, 2), 3,
+             rtol=6e-16),
+        data(elliprg, 'ellint_rg_xyy_ipp-ellint_rg_xyy', (0, 1, 2), 3,
+             rtol=7.5e-16),
+        data(elliprg, 'ellint_rg_xy0_ipp-ellint_rg_xy0', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprg, 'ellint_rg_00x_ipp-ellint_rg_00x', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprj, 'ellint_rj_data_ipp-ellint_rj_data', (0, 1, 2, 3), 4,
+             rtol=5e-16, atol=1e-25,
+             param_filter=(lambda s: s <= 5e-26,)),
+        # ellint_rc_data_ipp/ellint_rc_data.txt
+        # ellint_rd_0xy_ipp/ellint_rd_0xy.txt
+        # ellint_rd_0yy_ipp/ellint_rd_0yy.txt
+        # ellint_rd_data_ipp/ellint_rd_data.txt
+        # ellint_rd_xxx_ipp/ellint_rd_xxx.txt
+        # ellint_rd_xxz_ipp/ellint_rd_xxz.txt
+        # ellint_rd_xyy_ipp/ellint_rd_xyy.txt
+        # ellint_rf_0yy_ipp/ellint_rf_0yy.txt
+        # ellint_rf_data_ipp/ellint_rf_data.txt
+        # ellint_rf_xxx_ipp/ellint_rf_xxx.txt
+        # ellint_rf_xy0_ipp/ellint_rf_xy0.txt
+        # ellint_rf_xyy_ipp/ellint_rf_xyy.txt
+        # ellint_rg_00x_ipp/ellint_rg_00x.txt
+        # ellint_rg_ipp/ellint_rg.txt
+        # ellint_rg_xxx_ipp/ellint_rg_xxx.txt
+        # ellint_rg_xy0_ipp/ellint_rg_xy0.txt
+        # ellint_rg_xyy_ipp/ellint_rg_xyy.txt
+        # ellint_rj_data_ipp/ellint_rj_data.txt
+        # ellint_rj_e2_ipp/ellint_rj_e2.txt
+        # ellint_rj_e3_ipp/ellint_rj_e3.txt
+        # ellint_rj_e4_ipp/ellint_rj_e4.txt
+        # ellint_rj_zp_ipp/ellint_rj_zp.txt
+
+        # jacobi_elliptic_ipp/jacobi_elliptic.txt
+        # jacobi_elliptic_small_ipp/jacobi_elliptic_small.txt
+        # jacobi_large_phi_ipp/jacobi_large_phi.txt
+        # jacobi_near_1_ipp/jacobi_near_1.txt
+        # jacobi_zeta_big_phi_ipp/jacobi_zeta_big_phi.txt
+        # jacobi_zeta_data_ipp/jacobi_zeta_data.txt
+
+        # heuman_lambda_data_ipp/heuman_lambda_data.txt
+
+        # hypergeometric_0F2_ipp/hypergeometric_0F2.txt
+        # hypergeometric_1F1_big_ipp/hypergeometric_1F1_big.txt
+        # hypergeometric_1F1_ipp/hypergeometric_1F1.txt
+        # hypergeometric_1F1_small_random_ipp/hypergeometric_1F1_small_random.txt
+        # hypergeometric_1F2_ipp/hypergeometric_1F2.txt
+        # hypergeometric_1f1_large_regularized_ipp/hypergeometric_1f1_large_regularized.txt  # noqa: E501
+        # hypergeometric_1f1_log_large_unsolved_ipp/hypergeometric_1f1_log_large_unsolved.txt  # noqa: E501
+        # hypergeometric_2F0_half_ipp/hypergeometric_2F0_half.txt
+        # hypergeometric_2F0_integer_a2_ipp/hypergeometric_2F0_integer_a2.txt
+        # hypergeometric_2F0_ipp/hypergeometric_2F0.txt
+        # hypergeometric_2F0_large_z_ipp/hypergeometric_2F0_large_z.txt
+        # hypergeometric_2F1_ipp/hypergeometric_2F1.txt
+        # hypergeometric_2F2_ipp/hypergeometric_2F2.txt
+
+        # ncbeta_big_ipp/ncbeta_big.txt
+        # nct_small_delta_ipp/nct_small_delta.txt
+        # nct_asym_ipp/nct_asym.txt
+        # ncbeta_ipp/ncbeta.txt
+
+        # powm1_data_ipp/powm1_big_data.txt
+        # powm1_sqrtp1m1_test_hpp/sqrtp1m1_data.txt
+
+        # sinc_data_ipp/sinc_data.txt
+
+        # test_gamma_data_ipp/gammap1m1_data.txt
+        # tgamma_ratio_data_ipp/tgamma_ratio_data.txt
+
+        # trig_data_ipp/trig_data.txt
+        # trig_data2_ipp/trig_data2.txt
+]
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize('test', BOOST_TESTS, ids=repr)
+def test_boost(test):
+     _test_factory(test)
+
+
+GSL_TESTS = [
+        data_gsl(mathieu_a, 'mathieu_ab', (0, 1), 2, rtol=1e-13, atol=1e-13),
+        data_gsl(mathieu_b, 'mathieu_ab', (0, 1), 3, rtol=1e-13, atol=1e-13),
+
+        # Also the GSL output has limited accuracy...
+        data_gsl(mathieu_ce_rad, 'mathieu_ce_se', (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
+        data_gsl(mathieu_se_rad, 'mathieu_ce_se', (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
+
+        data_gsl(mathieu_mc1_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
+        data_gsl(mathieu_ms1_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
+
+        data_gsl(mathieu_mc2_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 5, rtol=1e-7, atol=1e-13),
+        data_gsl(mathieu_ms2_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 6, rtol=1e-7, atol=1e-13),
+]
+
+
+@pytest.mark.parametrize('test', GSL_TESTS, ids=repr)
+def test_gsl(test):
+    _test_factory(test)
+
+
+LOCAL_TESTS = [
+    data_local(ellipkinc, 'ellipkinc_neg_m', (0, 1), 2),
+    data_local(ellipkm1, 'ellipkm1', 0, 1),
+    data_local(ellipeinc, 'ellipeinc_neg_m', (0, 1), 2),
+    data_local(clog1p, 'log1p_expm1_complex', (0,1), (2,3), rtol=1e-14),
+    data_local(cexpm1, 'log1p_expm1_complex', (0,1), (4,5), rtol=1e-14),
+    data_local(gammainc, 'gammainc', (0, 1), 2, rtol=1e-12),
+    data_local(gammaincc, 'gammaincc', (0, 1), 2, rtol=1e-11),
+    data_local(ellip_harm_2, 'ellip',(0, 1, 2, 3, 4), 6, rtol=1e-10, atol=1e-13),
+    data_local(ellip_harm, 'ellip',(0, 1, 2, 3, 4), 5, rtol=1e-10, atol=1e-13),
+    data_local(wright_bessel, 'wright_bessel', (0, 1, 2), 3, rtol=1e-11),
+]
+
+
+@pytest.mark.parametrize('test', LOCAL_TESTS, ids=repr)
+def test_local(test):
+    _test_factory(test)
+
+
+def _test_factory(test, dtype=np.float64):
+    """Boost test"""
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error is detected")
+        with np.errstate(all='ignore'):
+            test.check(dtype=dtype)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py
new file mode 100644
index 0000000000000000000000000000000000000000..6da2c8ddddd7341cbb777216e9f2f3cce536a51e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py
@@ -0,0 +1,42 @@
+# Tests for a few of the "double-double" C++ functions defined in
+# special/cephes/dd_real.h. Prior to gh-20390 which translated these
+# functions from C to C++, there were test cases for _dd_expm1. It
+# was determined that this function is not used anywhere internally
+# in SciPy, so this function was not translated.
+
+
+import pytest
+from numpy.testing import assert_allclose
+from scipy.special._test_internal import _dd_exp, _dd_log
+
+
+# Each tuple in test_data contains:
+#   (dd_func, xhi, xlo, expected_yhi, expected_ylo)
+# The expected values were computed with mpmath, e.g.
+#
+#   import mpmath
+#   mpmath.mp.dps = 100
+#   xhi = 10.0
+#   xlo = 0.0
+#   x = mpmath.mpf(xhi) + mpmath.mpf(xlo)
+#   y = mpmath.log(x)
+#   expected_yhi = float(y)
+#   expected_ylo = float(y - expected_yhi)
+#
+test_data = [
+    (_dd_exp, -0.3333333333333333, -1.850371707708594e-17,
+     0.7165313105737893, -2.0286948382455594e-17),
+    (_dd_exp, 0.0, 0.0, 1.0, 0.0),
+    (_dd_exp, 10.0, 0.0, 22026.465794806718, -1.3780134700517372e-12),
+    (_dd_log, 0.03125, 0.0, -3.4657359027997265, -4.930038229799327e-18),
+    (_dd_log, 10.0, 0.0, 2.302585092994046, -2.1707562233822494e-16),
+]
+
+
+@pytest.mark.parametrize('dd_func, xhi, xlo, expected_yhi, expected_ylo',
+                         test_data)
+def test_dd(dd_func, xhi, xlo, expected_yhi, expected_ylo):
+    yhi, ylo = dd_func(xhi, xlo)
+    assert yhi == expected_yhi, (f"high double ({yhi}) does not equal the "
+                                 f"expected value {expected_yhi}")
+    assert_allclose(ylo, expected_ylo, rtol=5e-15)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7f27dc7b71c1ae928b4bdd8bd987df9ca420bab
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py
@@ -0,0 +1,45 @@
+import numpy as np
+from numpy import pi, log, sqrt
+from numpy.testing import assert_, assert_equal
+
+from scipy.special._testutils import FuncData
+import scipy.special as sc
+
+# Euler-Mascheroni constant
+euler = 0.57721566490153286
+
+
+def test_consistency():
+    # Make sure the implementation of digamma for real arguments
+    # agrees with the implementation of digamma for complex arguments.
+
+    # It's all poles after -1e16
+    x = np.r_[-np.logspace(15, -30, 200), np.logspace(-30, 300, 200)]
+    dataset = np.vstack((x + 0j, sc.digamma(x))).T
+    FuncData(sc.digamma, dataset, 0, 1, rtol=5e-14, nan_ok=True).check()
+
+
+def test_special_values():
+    # Test special values from Gauss's digamma theorem. See
+    #
+    # https://en.wikipedia.org/wiki/Digamma_function
+
+    dataset = [
+        (1, -euler),
+        (0.5, -2*log(2) - euler),
+        (1/3, -pi/(2*sqrt(3)) - 3*log(3)/2 - euler),
+        (1/4, -pi/2 - 3*log(2) - euler),
+        (1/6, -pi*sqrt(3)/2 - 2*log(2) - 3*log(3)/2 - euler),
+        (1/8,
+         -pi/2 - 4*log(2) - (pi + log(2 + sqrt(2)) - log(2 - sqrt(2)))/sqrt(2) - euler)
+    ]
+
+    dataset = np.asarray(dataset)
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
+
+
+def test_nonfinite():
+    pts = [0.0, -0.0, np.inf]
+    std = [-np.inf, np.inf, np.inf]
+    assert_equal(sc.digamma(pts), std)
+    assert_(all(np.isnan(sc.digamma([-np.inf, -1]))))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cfb6530e2fd80d2c261af960f42c974e1e1b26e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py
@@ -0,0 +1,278 @@
+#
+# Tests for the Ellipsoidal Harmonic Function,
+# Distributed under the same license as SciPy itself.
+#
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal, assert_allclose,
+                           assert_, suppress_warnings)
+from scipy.special._testutils import assert_func_equal
+from scipy.special import ellip_harm, ellip_harm_2, ellip_normal
+from scipy.integrate import IntegrationWarning
+from numpy import sqrt, pi
+
+
+def test_ellip_potential():
+    def change_coefficient(lambda1, mu, nu, h2, k2):
+        x = sqrt(lambda1**2*mu**2*nu**2/(h2*k2))
+        y = sqrt((lambda1**2 - h2)*(mu**2 - h2)*(h2 - nu**2)/(h2*(k2 - h2)))
+        z = sqrt((lambda1**2 - k2)*(k2 - mu**2)*(k2 - nu**2)/(k2*(k2 - h2)))
+        return x, y, z
+
+    def solid_int_ellip(lambda1, mu, nu, n, p, h2, k2):
+        return (ellip_harm(h2, k2, n, p, lambda1)*ellip_harm(h2, k2, n, p, mu)
+               * ellip_harm(h2, k2, n, p, nu))
+
+    def solid_int_ellip2(lambda1, mu, nu, n, p, h2, k2):
+        return (ellip_harm_2(h2, k2, n, p, lambda1)
+                * ellip_harm(h2, k2, n, p, mu)*ellip_harm(h2, k2, n, p, nu))
+
+    def summation(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2):
+        tol = 1e-8
+        sum1 = 0
+        for n in range(20):
+            xsum = 0
+            for p in range(1, 2*n+2):
+                xsum += (4*pi*(solid_int_ellip(lambda2, mu2, nu2, n, p, h2, k2)
+                    * solid_int_ellip2(lambda1, mu1, nu1, n, p, h2, k2)) /
+                    (ellip_normal(h2, k2, n, p)*(2*n + 1)))
+            if abs(xsum) < 0.1*tol*abs(sum1):
+                break
+            sum1 += xsum
+        return sum1, xsum
+
+    def potential(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2):
+        x1, y1, z1 = change_coefficient(lambda1, mu1, nu1, h2, k2)
+        x2, y2, z2 = change_coefficient(lambda2, mu2, nu2, h2, k2)
+        res = sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
+        return 1/res
+
+    pts = [
+        (120, sqrt(19), 2, 41, sqrt(17), 2, 15, 25),
+        (120, sqrt(16), 3.2, 21, sqrt(11), 2.9, 11, 20),
+       ]
+
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        sup.filter(IntegrationWarning, "The maximum number of subdivisions")
+
+        for p in pts:
+            err_msg = repr(p)
+            exact = potential(*p)
+            result, last_term = summation(*p)
+            assert_allclose(exact, result, atol=0, rtol=1e-8, err_msg=err_msg)
+            assert_(abs(result - exact) < 10*abs(last_term), err_msg)
+
+
+def test_ellip_norm():
+
+    def G01(h2, k2):
+        return 4*pi
+
+    def G11(h2, k2):
+        return 4*pi*h2*k2/3
+
+    def G12(h2, k2):
+        return 4*pi*h2*(k2 - h2)/3
+
+    def G13(h2, k2):
+        return 4*pi*k2*(k2 - h2)/3
+
+    def G22(h2, k2):
+        res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2 +
+        sqrt(h2**2 + k2**2 - h2*k2)*(-2*(h2**3 + k2**3) + 3*h2*k2*(h2 + k2)))
+        return 16*pi/405*res
+
+    def G21(h2, k2):
+        res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2
+        + sqrt(h2**2 + k2**2 - h2*k2)*(2*(h2**3 + k2**3) - 3*h2*k2*(h2 + k2)))
+        return 16*pi/405*res
+
+    def G23(h2, k2):
+        return 4*pi*h2**2*k2*(k2 - h2)/15
+
+    def G24(h2, k2):
+        return 4*pi*h2*k2**2*(k2 - h2)/15
+
+    def G25(h2, k2):
+        return 4*pi*h2*k2*(k2 - h2)**2/15
+
+    def G32(h2, k2):
+        res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2
+        + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(-8*(h2**3 + k2**3) +
+        11*h2*k2*(h2 + k2)))
+        return 16*pi/13125*k2*h2*res
+
+    def G31(h2, k2):
+        res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2
+        + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(8*(h2**3 + k2**3) -
+        11*h2*k2*(h2 + k2)))
+        return 16*pi/13125*h2*k2*res
+
+    def G34(h2, k2):
+        res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(h2**2 + 4*k2**2 - h2*k2)*(-6*h2**3 - 8*k2**3 + 9*h2**2*k2 +
+                                            13*h2*k2**2))
+        return 16*pi/13125*h2*(k2 - h2)*res
+
+    def G33(h2, k2):
+        res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(h2**2 + 4*k2**2 - h2*k2)*(6*h2**3 + 8*k2**3 - 9*h2**2*k2 -
+        13*h2*k2**2))
+        return 16*pi/13125*h2*(k2 - h2)*res
+
+    def G36(h2, k2):
+        res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(4*h2**2 + k2**2 - h2*k2)*(-8*h2**3 - 6*k2**3 + 13*h2**2*k2 +
+        9*h2*k2**2))
+        return 16*pi/13125*k2*(k2 - h2)*res
+
+    def G35(h2, k2):
+        res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(4*h2**2 + k2**2 - h2*k2)*(8*h2**3 + 6*k2**3 - 13*h2**2*k2 -
+        9*h2*k2**2))
+        return 16*pi/13125*k2*(k2 - h2)*res
+
+    def G37(h2, k2):
+        return 4*pi*h2**2*k2**2*(k2 - h2)**2/105
+
+    known_funcs = {(0, 1): G01, (1, 1): G11, (1, 2): G12, (1, 3): G13,
+                   (2, 1): G21, (2, 2): G22, (2, 3): G23, (2, 4): G24,
+                   (2, 5): G25, (3, 1): G31, (3, 2): G32, (3, 3): G33,
+                   (3, 4): G34, (3, 5): G35, (3, 6): G36, (3, 7): G37}
+
+    def _ellip_norm(n, p, h2, k2):
+        func = known_funcs[n, p]
+        return func(h2, k2)
+    _ellip_norm = np.vectorize(_ellip_norm)
+
+    def ellip_normal_known(h2, k2, n, p):
+        return _ellip_norm(n, p, h2, k2)
+
+    # generate both large and small h2 < k2 pairs
+    np.random.seed(1234)
+    h2 = np.random.pareto(0.5, size=1)
+    k2 = h2 * (1 + np.random.pareto(0.5, size=h2.size))
+
+    points = []
+    for n in range(4):
+        for p in range(1, 2*n+2):
+            points.append((h2, k2, np.full(h2.size, n), np.full(h2.size, p)))
+    points = np.array(points)
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        assert_func_equal(ellip_normal, ellip_normal_known, points, rtol=1e-12)
+
+
+def test_ellip_harm_2():
+
+    def I1(h2, k2, s):
+        res = (ellip_harm_2(h2, k2, 1, 1, s)/(3 * ellip_harm(h2, k2, 1, 1, s))
+        + ellip_harm_2(h2, k2, 1, 2, s)/(3 * ellip_harm(h2, k2, 1, 2, s)) +
+        ellip_harm_2(h2, k2, 1, 3, s)/(3 * ellip_harm(h2, k2, 1, 3, s)))
+        return res
+
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        assert_almost_equal(I1(5, 8, 10), 1/(10*sqrt((100-5)*(100-8))))
+
+        # Values produced by code from arXiv:1204.0267
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 1, 10), 0.00108056853382)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 2, 10), 0.00105820513809)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 3, 10), 0.00106058384743)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 4, 10), 0.00106774492306)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 5, 10), 0.00107976356454)
+
+
+def test_ellip_harm():
+
+    def E01(h2, k2, s):
+        return 1
+
+    def E11(h2, k2, s):
+        return s
+
+    def E12(h2, k2, s):
+        return sqrt(abs(s*s - h2))
+
+    def E13(h2, k2, s):
+        return sqrt(abs(s*s - k2))
+
+    def E21(h2, k2, s):
+        return s*s - 1/3*((h2 + k2) + sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2)))
+
+    def E22(h2, k2, s):
+        return s*s - 1/3*((h2 + k2) - sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2)))
+
+    def E23(h2, k2, s):
+        return s * sqrt(abs(s*s - h2))
+
+    def E24(h2, k2, s):
+        return s * sqrt(abs(s*s - k2))
+
+    def E25(h2, k2, s):
+        return sqrt(abs((s*s - h2)*(s*s - k2)))
+
+    def E31(h2, k2, s):
+        return s*s*s - (s/5)*(2*(h2 + k2) + sqrt(4*(h2 + k2)*(h2 + k2) -
+        15*h2*k2))
+
+    def E32(h2, k2, s):
+        return s*s*s - (s/5)*(2*(h2 + k2) - sqrt(4*(h2 + k2)*(h2 + k2) -
+        15*h2*k2))
+
+    def E33(h2, k2, s):
+        return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) + sqrt(abs((h2 +
+        2*k2)*(h2 + 2*k2) - 5*h2*k2))))
+
+    def E34(h2, k2, s):
+        return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) - sqrt(abs((h2 +
+        2*k2)*(h2 + 2*k2) - 5*h2*k2))))
+
+    def E35(h2, k2, s):
+        return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) + sqrt(abs((2*h2
+        + k2)*(2*h2 + k2) - 5*h2*k2))))
+
+    def E36(h2, k2, s):
+        return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) - sqrt(abs((2*h2
+        + k2)*(2*h2 + k2) - 5*h2*k2))))
+
+    def E37(h2, k2, s):
+        return s * sqrt(abs((s*s - h2)*(s*s - k2)))
+
+    assert_equal(ellip_harm(5, 8, 1, 2, 2.5, 1, 1),
+    ellip_harm(5, 8, 1, 2, 2.5))
+
+    known_funcs = {(0, 1): E01, (1, 1): E11, (1, 2): E12, (1, 3): E13,
+                   (2, 1): E21, (2, 2): E22, (2, 3): E23, (2, 4): E24,
+                   (2, 5): E25, (3, 1): E31, (3, 2): E32, (3, 3): E33,
+                   (3, 4): E34, (3, 5): E35, (3, 6): E36, (3, 7): E37}
+
+    point_ref = []
+
+    def ellip_harm_known(h2, k2, n, p, s):
+        for i in range(h2.size):
+            func = known_funcs[(int(n[i]), int(p[i]))]
+            point_ref.append(func(h2[i], k2[i], s[i]))
+        return point_ref
+
+    rng = np.random.RandomState(1234)
+    h2 = rng.pareto(0.5, size=30)
+    k2 = h2*(1 + rng.pareto(0.5, size=h2.size))
+    s = rng.pareto(0.5, size=h2.size)
+    points = []
+    for i in range(h2.size):
+        for n in range(4):
+            for p in range(1, 2*n+2):
+                points.append((h2[i], k2[i], n, p, s[i]))
+    points = np.array(points)
+    assert_func_equal(ellip_harm, ellip_harm_known, points, rtol=1e-12)
+
+
+def test_ellip_harm_invalid_p():
+    # Regression test. This should return nan.
+    n = 4
+    # Make p > 2*n + 1.
+    p = 2*n + 2
+    result = ellip_harm(0.5, 2.0, n, p, 0.2)
+    assert np.isnan(result)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py
new file mode 100644
index 0000000000000000000000000000000000000000..98739b93fc6ad75a41a7b80107ee696453b12a09
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py
@@ -0,0 +1,89 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+import scipy.special as sc
+
+
+class TestInverseErrorFunction:
+    def test_compliment(self):
+        # Test erfcinv(1 - x) == erfinv(x)
+        x = np.linspace(-1, 1, 101)
+        assert_allclose(sc.erfcinv(1 - x), sc.erfinv(x), rtol=0, atol=1e-15)
+
+    def test_literal_values(self):
+        # The expected values were calculated with mpmath:
+        #
+        #   import mpmath
+        #   mpmath.mp.dps = 200
+        #   for y in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:
+        #       x = mpmath.erfinv(y)
+        #       print(x)
+        #
+        y = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
+        actual = sc.erfinv(y)
+        expected = [
+            0.0,
+            0.08885599049425769,
+            0.1791434546212917,
+            0.2724627147267543,
+            0.37080715859355795,
+            0.4769362762044699,
+            0.5951160814499948,
+            0.7328690779592167,
+            0.9061938024368233,
+            1.1630871536766743,
+        ]
+        assert_allclose(actual, expected, rtol=0, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        'f, x, y',
+        [
+            (sc.erfinv, -1, -np.inf),
+            (sc.erfinv, 0, 0),
+            (sc.erfinv, 1, np.inf),
+            (sc.erfinv, -100, np.nan),
+            (sc.erfinv, 100, np.nan),
+            (sc.erfcinv, 0, np.inf),
+            (sc.erfcinv, 1, -0.0),
+            (sc.erfcinv, 2, -np.inf),
+            (sc.erfcinv, -100, np.nan),
+            (sc.erfcinv, 100, np.nan),
+        ],
+        ids=[
+            'erfinv at lower bound',
+            'erfinv at midpoint',
+            'erfinv at upper bound',
+            'erfinv below lower bound',
+            'erfinv above upper bound',
+            'erfcinv at lower bound',
+            'erfcinv at midpoint',
+            'erfcinv at upper bound',
+            'erfcinv below lower bound',
+            'erfcinv above upper bound',
+        ]
+    )
+    def test_domain_bounds(self, f, x, y):
+        assert_equal(f(x), y)
+
+    def test_erfinv_asympt(self):
+        # regression test for gh-12758: erfinv(x) loses precision at small x
+        # expected values precomputed with mpmath:
+        # >>> mpmath.mp.dps = 100
+        # >>> expected = [float(mpmath.erfinv(t)) for t in x]
+        x = np.array([1e-20, 1e-15, 1e-14, 1e-10, 1e-8, 0.9e-7, 1.1e-7, 1e-6])
+        expected = np.array([8.86226925452758e-21,
+                             8.862269254527581e-16,
+                             8.86226925452758e-15,
+                             8.862269254527581e-11,
+                             8.86226925452758e-09,
+                             7.97604232907484e-08,
+                             9.74849617998037e-08,
+                             8.8622692545299e-07])
+        assert_allclose(sc.erfinv(x), expected,
+                        rtol=1e-15)
+
+        # also test the roundtrip consistency
+        assert_allclose(sc.erf(sc.erfinv(x)),
+                        x,
+                        rtol=5e-15)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py
new file mode 100644
index 0000000000000000000000000000000000000000..8332a83267e2f75dded04e80443c150c832676c8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py
@@ -0,0 +1,118 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special as sc
+
+
+class TestExp1:
+
+    def test_branch_cut(self):
+        assert np.isnan(sc.exp1(-1))
+        assert sc.exp1(complex(-1, 0)).imag == (
+            -sc.exp1(complex(-1, -0.0)).imag
+        )
+
+        assert_allclose(
+            sc.exp1(complex(-1, 0)),
+            sc.exp1(-1 + 1e-20j),
+            atol=0,
+            rtol=1e-15
+        )
+        assert_allclose(
+            sc.exp1(complex(-1, -0.0)),
+            sc.exp1(-1 - 1e-20j),
+            atol=0,
+            rtol=1e-15
+        )
+
+    def test_834(self):
+        # Regression test for #834
+        a = sc.exp1(-complex(19.9999990))
+        b = sc.exp1(-complex(19.9999991))
+        assert_allclose(a.imag, b.imag, atol=0, rtol=1e-15)
+
+
+class TestScaledExp1:
+
+    @pytest.mark.parametrize('x, expected', [(0, 0), (np.inf, 1)])
+    def test_limits(self, x, expected):
+        y = sc._ufuncs._scaled_exp1(x)
+        assert y == expected
+
+    # The expected values were computed with mpmath, e.g.:
+    #
+    #   from mpmath import mp
+    #   mp.dps = 80
+    #   x = 1e-25
+    #   print(float(x*mp.exp(x)*np.expint(1, x)))
+    #
+    # prints 5.698741165994961e-24
+    #
+    # The method used to compute _scaled_exp1 changes at x=1
+    # and x=1250, so values at those inputs, and values just
+    # above and below them, are included in the test data.
+    @pytest.mark.parametrize('x, expected',
+                             [(1e-25, 5.698741165994961e-24),
+                              (0.1, 0.20146425447084518),
+                              (0.9995, 0.5962509885831002),
+                              (1.0, 0.5963473623231941),
+                              (1.0005, 0.5964436833238044),
+                              (2.5, 0.7588145912149602),
+                              (10.0, 0.9156333393978808),
+                              (100.0, 0.9901942286733019),
+                              (500.0, 0.9980079523802055),
+                              (1000.0, 0.9990019940238807),
+                              (1249.5, 0.9992009578306811),
+                              (1250.0, 0.9992012769377913),
+                              (1250.25, 0.9992014363957858),
+                              (2000.0, 0.9995004992514963),
+                              (1e4, 0.9999000199940024),
+                              (1e10, 0.9999999999),
+                              (1e15, 0.999999999999999),
+                              ])
+    def test_scaled_exp1(self, x, expected):
+        y = sc._ufuncs._scaled_exp1(x)
+        assert_allclose(y, expected, rtol=2e-15)
+
+
+class TestExpi:
+
+    @pytest.mark.parametrize('result', [
+        sc.expi(complex(-1, 0)),
+        sc.expi(complex(-1, -0.0)),
+        sc.expi(-1)
+    ])
+    def test_branch_cut(self, result):
+        desired = -0.21938393439552027368  # Computed using Mpmath
+        assert_allclose(result, desired, atol=0, rtol=1e-14)
+
+    def test_near_branch_cut(self):
+        lim_from_above = sc.expi(-1 + 1e-20j)
+        lim_from_below = sc.expi(-1 - 1e-20j)
+        assert_allclose(
+            lim_from_above.real,
+            lim_from_below.real,
+            atol=0,
+            rtol=1e-15
+        )
+        assert_allclose(
+            lim_from_above.imag,
+            -lim_from_below.imag,
+            atol=0,
+            rtol=1e-15
+        )
+
+    def test_continuity_on_positive_real_axis(self):
+        assert_allclose(
+            sc.expi(complex(1, 0)),
+            sc.expi(complex(1, -0.0)),
+            atol=0,
+            rtol=1e-15
+        )
+
+
+class TestExpn:
+
+    def test_out_of_domain(self):
+        assert all(np.isnan([sc.expn(-1, 1.0), sc.expn(1, -1.0)]))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ecaf51545e006e37a451a08f356ce0392a3159c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/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
+from scipy.special import beta, gamma
+
+
+@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
+    assert extensions.cy_beta(0.5, 0.1) == beta(0.5, 0.1)
+    assert extensions.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j)
+    assert extensions_cpp.cy_beta(0.5, 0.1) == beta(0.5, 0.1)
+    assert extensions_cpp.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py
new file mode 100644
index 0000000000000000000000000000000000000000..8868f66c47ce0d4bbb21c78435a6c89d44065252
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py
@@ -0,0 +1,85 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+class TestVoigtProfile:
+
+    @pytest.mark.parametrize('x, sigma, gamma', [
+        (np.nan, 1, 1),
+        (0, np.nan, 1),
+        (0, 1, np.nan),
+        (1, np.nan, 0),
+        (np.nan, 1, 0),
+        (1, 0, np.nan),
+        (np.nan, 0, 1),
+        (np.nan, 0, 0)
+    ])
+    def test_nan(self, x, sigma, gamma):
+        assert np.isnan(sc.voigt_profile(x, sigma, gamma))
+
+    @pytest.mark.parametrize('x, desired', [
+        (-np.inf, 0),
+        (np.inf, 0)
+    ])
+    def test_inf(self, x, desired):
+        assert sc.voigt_profile(x, 1, 1) == desired
+
+    def test_against_mathematica(self):
+        # Results obtained from Mathematica by computing
+        #
+        # PDF[VoigtDistribution[gamma, sigma], x]
+        #
+        points = np.array([
+            [-7.89, 45.06, 6.66, 0.0077921073660388806401],
+            [-0.05, 7.98, 24.13, 0.012068223646769913478],
+            [-13.98, 16.83, 42.37, 0.0062442236362132357833],
+            [-12.66, 0.21, 6.32, 0.010052516161087379402],
+            [11.34, 4.25, 21.96, 0.0113698923627278917805],
+            [-11.56, 20.40, 30.53, 0.0076332760432097464987],
+            [-9.17, 25.61, 8.32, 0.011646345779083005429],
+            [16.59, 18.05, 2.50, 0.013637768837526809181],
+            [9.11, 2.12, 39.33, 0.0076644040807277677585],
+            [-43.33, 0.30, 45.68, 0.0036680463875330150996]
+        ])
+        FuncData(
+            sc.voigt_profile,
+            points,
+            (0, 1, 2),
+            3,
+            atol=0,
+            rtol=1e-15
+        ).check()
+
+    def test_symmetry(self):
+        x = np.linspace(0, 10, 20)
+        assert_allclose(
+            sc.voigt_profile(x, 1, 1),
+            sc.voigt_profile(-x, 1, 1),
+            rtol=1e-15,
+            atol=0
+        )
+
+    @pytest.mark.parametrize('x, sigma, gamma, desired', [
+        (0, 0, 0, np.inf),
+        (1, 0, 0, 0)
+    ])
+    def test_corner_cases(self, x, sigma, gamma, desired):
+        assert sc.voigt_profile(x, sigma, gamma) == desired
+
+    @pytest.mark.parametrize('sigma1, gamma1, sigma2, gamma2', [
+        (0, 1, 1e-16, 1),
+        (1, 0, 1, 1e-16),
+        (0, 0, 1e-16, 1e-16)
+    ])
+    def test_continuity(self, sigma1, gamma1, sigma2, gamma2):
+        x = np.linspace(1, 10, 20)
+        assert_allclose(
+            sc.voigt_profile(x, sigma1, gamma1),
+            sc.voigt_profile(x, sigma2, gamma2),
+            rtol=1e-16,
+            atol=1e-16
+        )
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e3fbd17dddeed73d311566a930f52899e3b9db6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py
@@ -0,0 +1,12 @@
+import numpy as np
+import scipy.special as sc
+
+
+class TestRgamma:
+
+    def test_gh_11315(self):
+        assert sc.rgamma(-35) == 0
+
+    def test_rgamma_zeros(self):
+        x = np.array([0, -10, -100, -1000, -10000])
+        assert np.all(sc.rgamma(x) == 0)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py
new file mode 100644
index 0000000000000000000000000000000000000000..aae34e5c23f2d293f362abd825f1dad454371ae0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py
@@ -0,0 +1,136 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+INVALID_POINTS = [
+    (1, -1),
+    (0, 0),
+    (-1, 1),
+    (np.nan, 1),
+    (1, np.nan)
+]
+
+
+class TestGammainc:
+
+    @pytest.mark.parametrize('a, x', INVALID_POINTS)
+    def test_domain(self, a, x):
+        assert np.isnan(sc.gammainc(a, x))
+
+    def test_a_eq_0_x_gt_0(self):
+        assert sc.gammainc(0, 1) == 1
+
+    @pytest.mark.parametrize('a, x, desired', [
+        (np.inf, 1, 0),
+        (np.inf, 0, 0),
+        (np.inf, np.inf, np.nan),
+        (1, np.inf, 1)
+    ])
+    def test_infinite_arguments(self, a, x, desired):
+        result = sc.gammainc(a, x)
+        if np.isnan(desired):
+            assert np.isnan(result)
+        else:
+            assert result == desired
+
+    def test_infinite_limits(self):
+        # Test that large arguments converge to the hard-coded limits
+        # at infinity.
+        assert_allclose(
+            sc.gammainc(1000, 100),
+            sc.gammainc(np.inf, 100),
+            atol=1e-200,  # Use `atol` since the function converges to 0.
+            rtol=0
+        )
+        assert sc.gammainc(100, 1000) == sc.gammainc(100, np.inf)
+
+    def test_x_zero(self):
+        a = np.arange(1, 10)
+        assert_array_equal(sc.gammainc(a, 0), 0)
+
+    def test_limit_check(self):
+        result = sc.gammainc(1e-10, 1)
+        limit = sc.gammainc(0, 1)
+        assert np.isclose(result, limit)
+
+    def gammainc_line(self, x):
+        # The line a = x where a simpler asymptotic expansion (analog
+        # of DLMF 8.12.15) is available.
+        c = np.array([-1/3, -1/540, 25/6048, 101/155520,
+                      -3184811/3695155200, -2745493/8151736420])
+        res = 0
+        xfac = 1
+        for ck in c:
+            res -= ck*xfac
+            xfac /= x
+        res /= np.sqrt(2*np.pi*x)
+        res += 0.5
+        return res
+
+    def test_line(self):
+        x = np.logspace(np.log10(25), 300, 500)
+        a = x
+        dataset = np.vstack((a, x, self.gammainc_line(x))).T
+        FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-11).check()
+
+    def test_roundtrip(self):
+        a = np.logspace(-5, 10, 100)
+        x = np.logspace(-5, 10, 100)
+
+        y = sc.gammaincinv(a, sc.gammainc(a, x))
+        assert_allclose(x, y, rtol=1e-10)
+
+
+class TestGammaincc:
+
+    @pytest.mark.parametrize('a, x', INVALID_POINTS)
+    def test_domain(self, a, x):
+        assert np.isnan(sc.gammaincc(a, x))
+
+    def test_a_eq_0_x_gt_0(self):
+        assert sc.gammaincc(0, 1) == 0
+
+    @pytest.mark.parametrize('a, x, desired', [
+        (np.inf, 1, 1),
+        (np.inf, 0, 1),
+        (np.inf, np.inf, np.nan),
+        (1, np.inf, 0)
+    ])
+    def test_infinite_arguments(self, a, x, desired):
+        result = sc.gammaincc(a, x)
+        if np.isnan(desired):
+            assert np.isnan(result)
+        else:
+            assert result == desired
+
+    def test_infinite_limits(self):
+        # Test that large arguments converge to the hard-coded limits
+        # at infinity.
+        assert sc.gammaincc(1000, 100) == sc.gammaincc(np.inf, 100)
+        assert_allclose(
+            sc.gammaincc(100, 1000),
+            sc.gammaincc(100, np.inf),
+            atol=1e-200,  # Use `atol` since the function converges to 0.
+            rtol=0
+        )
+
+    def test_limit_check(self):
+        result = sc.gammaincc(1e-10,1)
+        limit = sc.gammaincc(0,1)
+        assert np.isclose(result, limit)
+
+    def test_x_zero(self):
+        a = np.arange(1, 10)
+        assert_array_equal(sc.gammaincc(a, 0), 1)
+
+    def test_roundtrip(self):
+        a = np.logspace(-5, 10, 100)
+        x = np.logspace(-5, 10, 100)
+
+        y = sc.gammainccinv(a, sc.gammaincc(a, x))
+        assert_allclose(x, y, rtol=1e-14)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py
new file mode 100644
index 0000000000000000000000000000000000000000..2102152213997886d0127080a2767e8fcc9af63a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py
@@ -0,0 +1,2566 @@
+"""Tests for hyp2f1 for complex values.
+
+Author: Albert Steppi, with credit to Adam Kullberg (FormerPhycisist) for
+the implementation of mp_hyp2f1 below, which modifies mpmath's hyp2f1 to
+return the same branch as scipy's on the standard branch cut.
+"""
+
+import sys
+import pytest
+import numpy as np
+from typing import NamedTuple
+from numpy.testing import assert_allclose
+
+from scipy.special import hyp2f1
+from scipy.special._testutils import check_version, MissingModule
+
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule("mpmath")
+
+
+def mp_hyp2f1(a, b, c, z):
+    """Return mpmath hyp2f1 calculated on same branch as scipy hyp2f1.
+
+    For most values of a,b,c mpmath returns the x - 0j branch of hyp2f1 on the
+    branch cut x=(1,inf) whereas scipy's hyp2f1 calculates the x + 0j branch.
+    Thus, to generate the right comparison values on the branch cut, we
+    evaluate mpmath.hyp2f1 at x + 1e-15*j.
+
+    The exception to this occurs when c-a=-m in which case both mpmath and
+    scipy calculate the x + 0j branch on the branch cut. When this happens
+    mpmath.hyp2f1 will be evaluated at the original z point.
+    """
+    on_branch_cut = z.real > 1.0 and abs(z.imag) < 1.0e-15
+    cond1 = abs(c - a - round(c - a)) < 1.0e-15 and round(c - a) <= 0
+    cond2 = abs(c - b - round(c - b)) < 1.0e-15 and round(c - b) <= 0
+    # Make sure imaginary part is *exactly* zero
+    if on_branch_cut:
+        z = z.real + 0.0j
+    if on_branch_cut and not (cond1 or cond2):
+        z_mpmath = z.real + 1.0e-15j
+    else:
+        z_mpmath = z
+    return complex(mpmath.hyp2f1(a, b, c, z_mpmath))
+
+
+class Hyp2f1TestCase(NamedTuple):
+    a: float
+    b: float
+    c: float
+    z: complex
+    expected: complex
+    rtol: float
+
+
+class TestHyp2f1:
+    """Tests for hyp2f1 for complex values.
+
+    Expected values for test cases were computed using mpmath. See
+    `scipy.special._precompute.hyp2f1_data`. The verbose style of specifying
+    test cases is used for readability and to make it easier to mark individual
+    cases as expected to fail. Expected failures are used to highlight cases
+    where improvements are needed. See
+    `scipy.special._precompute.hyp2f1_data.make_hyp2f1_test_cases` for a
+    function to generate the boilerplate for the test cases.
+
+    Assertions have been added to each test to ensure that the test cases match
+    the situations that are intended. A final test `test_test_hyp2f1` checks
+    that the expected values in the test cases actually match what is computed
+    by mpmath. This test is marked slow even though it isn't particularly slow
+    so that it won't run by default on continuous integration builds.
+    """
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=np.inf + 0j,
+                    rtol=0
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=-10,
+                    z=0 + 0j,
+                    expected=1 + 0j,
+                    rtol=0
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=1 + 0j,
+                    rtol=0
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0,
+                    c=0,
+                    z=0.2 + 0.2j,
+                    expected=1 + 0j,
+                    rtol=0,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=0,
+                    z=0.2 + 0.2j,
+                    expected=np.inf + 0j,
+                    rtol=0,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=0,
+                    z=0 + 0j,
+                    expected=np.nan + 0j,
+                    rtol=0,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=-5,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=(1.0495404166666666+0.05708208333333334j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=-10,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=(1.092966013125+0.13455014673750001j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-10,
+                    b=-20,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=(-0.07712512000000005+0.12752814080000005j),
+                    rtol=1e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1,
+                    b=3.2,
+                    c=-1,
+                    z=0.2 + 0.2j,
+                    expected=(1.6400000000000001+0.6400000000000001j),
+                    rtol=1e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-2,
+                    b=1.2,
+                    c=-4,
+                    z=1 + 0j,
+                    expected=1.8200000000000001 + 0j,
+                    rtol=1e-15,
+                ),
+            ),
+        ]
+    )
+    def test_c_non_positive_int(self, hyp2f1_test_case):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=1.5,
+                    z=1 + 0j,
+                    expected=1.1496439092239847 + 0j,
+                    rtol=1e-15
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=12.3,
+                    b=8.0,
+                    c=20.31,
+                    z=1 + 0j,
+                    expected=69280986.75273195 + 0j,
+                    rtol=1e-15
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=290.2,
+                    b=321.5,
+                    c=700.1,
+                    z=1 + 0j,
+                    expected=1.3396562400934e117 + 0j,
+                    rtol=1e-12,
+                ),
+            ),
+            # Note that here even mpmath produces different results for
+            # results that should be equivalent.
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=9.2,
+                    b=621.5,
+                    c=700.1,
+                    z=(1+0j),
+                    expected=(952726652.4158565+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=621.5,
+                    b=9.2,
+                    c=700.1,
+                    z=(1+0j),
+                    expected=(952726652.4160284+0j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-101.2,
+                    b=-400.4,
+                    c=-172.1,
+                    z=(1+0j),
+                    expected=(2.2253618341394838e+37+0j),
+                    rtol=1e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-400.4,
+                    b=-101.2,
+                    c=-172.1,
+                    z=(1+0j),
+                    expected=(2.2253618341394838e+37+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=172.5,
+                    b=-201.3,
+                    c=151.2,
+                    z=(1+0j),
+                    expected=(7.072266653650905e-135+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-201.3,
+                    b=172.5,
+                    c=151.2,
+                    z=(1+0j),
+                    expected=(7.072266653650905e-135+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-102.1,
+                    b=-20.3,
+                    c=1.3,
+                    z=1 + 0j,
+                    expected=2.7899070752746906e22 + 0j,
+                    rtol=3e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-202.6,
+                    b=60.3,
+                    c=1.5,
+                    z=1 + 0j,
+                    expected=-1.3113641413099326e-56 + 0j,
+                    rtol=1e-12,
+                ),
+            ),
+        ],
+    )
+    def test_unital_argument(self, hyp2f1_test_case):
+        """Tests for case z = 1, c - a - b > 0.
+
+        Expected answers computed using mpmath.
+        """
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert z == 1 and c - a - b > 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=1.3,
+                    z=-1 + 0j,
+                    expected=0.9428846409614143 + 0j,
+                    rtol=1e-15),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=12.3,
+                    b=8.0,
+                    c=5.300000000000001,
+                    z=-1 + 0j,
+                    expected=-4.845809986595704e-06 + 0j,
+                    rtol=1e-15
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=221.5,
+                    b=90.2,
+                    c=132.3,
+                    z=-1 + 0j,
+                    expected=2.0490488728377282e-42 + 0j,
+                    rtol=1e-7,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-102.1,
+                    b=-20.3,
+                    c=-80.8,
+                    z=-1 + 0j,
+                    expected=45143784.46783885 + 0j,
+                    rtol=1e-7,
+                ),
+                marks=pytest.mark.xfail(
+                    condition=sys.maxsize < 2**32,
+                    reason="Fails on 32 bit.",
+                )
+            ),
+        ],
+    )
+    def test_special_case_z_near_minus_1(self, hyp2f1_test_case):
+        """Tests for case z ~ -1, c ~ 1 + a - b
+
+        Expected answers computed using mpmath.
+        """
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert abs(1 + a - b - c) < 1e-15 and abs(z + 1) < 1e-15
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-4,
+                    b=2.02764642551431,
+                    c=1.0561196186065624,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.0031961077109535375-0.0011313924606557173j),
+                    rtol=1e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-8,
+                    b=-7.937789122896016,
+                    c=-15.964218273004214,
+                    z=(2-0.10526315789473695j),
+                    expected=(0.005543763196412503-0.0025948879065698306j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-8,
+                    b=8.095813935368371,
+                    c=4.0013768449590685,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(-0.0003054674127221263-9.261359291755414e-05j),
+                    rtol=1e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-4,
+                    b=-3.956227226099288,
+                    c=-3.9316537064827854,
+                    z=(1.1578947368421053-0.3157894736842106j),
+                    expected=(-0.0020809502580892937-0.0041877333232365095j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=-4,
+                    c=2.050308316530781,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.0011282435590058734+0.0002027062303465851j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-8,
+                    c=-15.964218273004214,
+                    z=(1.3684210526315788+0.10526315789473673j),
+                    expected=(-9.134907719238265e-05-0.00040219233987390723j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-4,
+                    c=4.0013768449590685,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(-0.000519013062087489-0.0005855883076830948j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-10000,
+                    b=2.2,
+                    c=93459345.3,
+                    z=(2+2j),
+                    expected=(0.9995292071559088-0.00047047067522659253j),
+                    rtol=1e-12,
+                ),
+            ),
+        ]
+    )
+    def test_a_b_negative_int(self, hyp2f1_test_case):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert a == int(a) and a < 0 or b == int(b) and b < 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-0.9629749245209605,
+                    c=-15.5,
+                    z=(1.1578947368421053-1.1578947368421053j),
+                    expected=(0.9778506962676361+0.044083801141231616j),
+                    rtol=3e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-3.9316537064827854,
+                    c=1.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(4.0793167523167675-10.11694246310966j),
+                    rtol=6e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-0.9629749245209605,
+                    c=2.5,
+                    z=(1.1578947368421053-0.10526315789473695j),
+                    expected=(-2.9692999501916915+0.6394599899845594j),
+                    rtol=1e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-0.9629749245209605,
+                    c=-15.5,
+                    z=(1.5789473684210522-1.1578947368421053j),
+                    expected=(0.9493076367106102-0.04316852977183447j),
+                    rtol=1e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.5,
+                    c=-15.5,
+                    z=(0.5263157894736841+0.10526315789473673j),
+                    expected=(0.9844377175631795-0.003120587561483841j),
+                    rtol=1e-10,
+                ),
+            ),
+        ],
+    )
+    def test_a_b_neg_int_after_euler_hypergeometric_transformation(
+        self, hyp2f1_test_case
+    ):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert (  # Tests the test
+            (abs(c - a - int(c - a)) < 1e-15 and c - a < 0) or
+            (abs(c - b - int(c - b)) < 1e-15 and c - b < 0)
+        )
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.9629749245209605,
+                    c=-15.963511401609862,
+                    z=(0.10526315789473673-0.3157894736842106j),
+                    expected=(0.9941449585778349+0.01756335047931358j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-0.9629749245209605,
+                    c=-15.963511401609862,
+                    z=(0.5263157894736841+0.5263157894736841j),
+                    expected=(1.0388722293372104-0.09549450380041416j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=1.0561196186065624,
+                    c=-7.93846038215665,
+                    z=(0.10526315789473673+0.7368421052631575j),
+                    expected=(2.1948378809826434+24.934157235172222j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=16.088264119063613,
+                    c=8.031683612216888,
+                    z=(0.3157894736842106-0.736842105263158j),
+                    expected=(-0.4075277891264672-0.06819344579666956j),
+                    rtol=2e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=2.050308316530781,
+                    c=8.031683612216888,
+                    z=(0.7368421052631575-0.10526315789473695j),
+                    expected=(2.833535530740603-0.6925373701408158j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=2.050308316530781,
+                    c=4.078873014294075,
+                    z=(0.10526315789473673-0.3157894736842106j),
+                    expected=(1.005347176329683-0.3580736009337313j),
+                    rtol=5e-16,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.9629749245209605,
+                    c=-15.963511401609862,
+                    z=(0.3157894736842106-0.5263157894736843j),
+                    expected=(0.9824353641135369+0.029271018868990268j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.9629749245209605,
+                    c=-159.63511401609862,
+                    z=(0.3157894736842106-0.5263157894736843j),
+                    expected=(0.9982436200365834+0.002927268199671111j),
+                    rtol=1e-7,
+                ),
+                marks=pytest.mark.xfail(reason="Poor convergence.")
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=16.088264119063613,
+                    c=8.031683612216888,
+                    z=(0.5263157894736841-0.5263157894736843j),
+                    expected=(-0.6906825165778091+0.8176575137504892j),
+                    rtol=5e-13,
+                ),
+            ),
+        ]
+    )
+    def test_region1(self, hyp2f1_test_case):
+        """|z| < 0.9 and real(z) >= 0."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert abs(z) < 0.9 and z.real >= 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=1.0561196186065624,
+                    c=4.078873014294075,
+                    z=(-0.3157894736842106+0.7368421052631575j),
+                    expected=(0.7751915029081136+0.24068493258607315j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=16.088264119063613,
+                    c=2.0397202577726152,
+                    z=(-0.9473684210526316-0.3157894736842106j),
+                    expected=(6.564549348474962e-07+1.6761570598334562e-06j),
+                    rtol=5e-09,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=2.050308316530781,
+                    c=16.056809865262608,
+                    z=(-0.10526315789473695-0.10526315789473695j),
+                    expected=(0.9862043298997204-0.013293151372712681j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=8.077282662161238,
+                    c=16.056809865262608,
+                    z=(-0.3157894736842106-0.736842105263158j),
+                    expected=(0.16163826638754716-0.41378530376373734j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=2.050308316530781,
+                    c=-0.906685989801748,
+                    z=(-0.5263157894736843+0.3157894736842106j),
+                    expected=(-6.256871535165936+0.13824973858225484j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=8.077282662161238,
+                    c=-3.9924618758357022,
+                    z=(-0.9473684210526316-0.3157894736842106j),
+                    expected=(75.54672526086316+50.56157041797548j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=8.077282662161238,
+                    c=-1.9631175993998025,
+                    z=(-0.5263157894736843+0.5263157894736841j),
+                    expected=(282.0602536306534-82.31597306936214j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-3.9316537064827854,
+                    c=8.031683612216888,
+                    z=(-0.5263157894736843-0.10526315789473695j),
+                    expected=(5.179603735575851+1.4445374002099813j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-7.949900487447654,
+                    c=1.0651378143226575,
+                    z=(-0.3157894736842106-0.9473684210526316j),
+                    expected=(2317.623517606141-269.51476321010324j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-1.92872979730171,
+                    c=2.0397202577726152,
+                    z=(-0.736842105263158-0.3157894736842106j),
+                    expected=(29.179154096175836+22.126690357535043j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-3.9316537064827854,
+                    c=-15.963511401609862,
+                    z=(-0.736842105263158-0.10526315789473695j),
+                    expected=(0.20820247892032057-0.04763956711248794j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-15.964218273004214,
+                    c=-1.9631175993998025,
+                    z=(-0.3157894736842106-0.5263157894736843j),
+                    expected=(-157471.63920142158+991294.0587828817j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-7.949900487447654,
+                    c=-7.93846038215665,
+                    z=(-0.10526315789473695-0.10526315789473695j),
+                    expected=(0.30765349653210194-0.2979706363594157j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=1.0561196186065624,
+                    c=8.031683612216888,
+                    z=(-0.9473684210526316-0.10526315789473695j),
+                    expected=(1.6787607400597109+0.10056620134616838j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=16.088264119063613,
+                    c=4.078873014294075,
+                    z=(-0.5263157894736843-0.736842105263158j),
+                    expected=(7062.07842506049-12768.77955655703j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=16.088264119063613,
+                    c=2.0397202577726152,
+                    z=(-0.3157894736842106+0.7368421052631575j),
+                    expected=(54749.216391029935-23078.144720887536j),
+                    rtol=2e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=1.0561196186065624,
+                    c=-0.906685989801748,
+                    z=(-0.10526315789473695-0.10526315789473695j),
+                    expected=(1.21521766411428-4.449385173946672j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=4.0013768449590685,
+                    c=-1.9631175993998025,
+                    z=(-0.736842105263158+0.5263157894736841j),
+                    expected=(19234693144.196907+1617913967.7294445j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=1.0561196186065624,
+                    c=-15.963511401609862,
+                    z=(-0.5263157894736843+0.3157894736842106j),
+                    expected=(0.9345201094534371+0.03745712558992195j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(-0.10526315789473695+0.10526315789473673j),
+                    expected=(0.605732446296829+0.398171533680972j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=-15.964218273004214,
+                    c=2.0397202577726152,
+                    z=(-0.10526315789473695-0.5263157894736843j),
+                    expected=(-9.753761888305416-4.590126012666959j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-1.92872979730171,
+                    c=2.0397202577726152,
+                    z=(-0.10526315789473695+0.3157894736842106j),
+                    expected=(0.45587226291120714+1.0694545265819797j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=-0.906685989801748,
+                    z=(-0.736842105263158+0.3157894736842106j),
+                    expected=(12.334808243233418-76.26089051819054j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=-15.963511401609862,
+                    z=(-0.5263157894736843+0.10526315789473673j),
+                    expected=(1.2396019687632678-0.047507973161146286j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=-0.9629749245209605,
+                    c=-0.906685989801748,
+                    z=(-0.3157894736842106-0.5263157894736843j),
+                    expected=(97.7889554372208-18.999754543400016j),
+                    rtol=5e-13,
+                ),
+            ),
+        ]
+    )
+    def test_region2(self, hyp2f1_test_case):
+        """|z| < 1 and real(z) < 0."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert abs(z) < 1 and z.real < 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-3.75,
+                    c=-3.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-1279.4894322256655-2302.914821389276j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=8.25,
+                    c=-1.5,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(-8889.452798586273-11961.162305065242j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.25,
+                    b=2.25,
+                    c=-1.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-236.58971357952055-238.5228224781136j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.75,
+                    b=-7.75,
+                    c=-15.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(0.8116076584352279-0.29360565398246036j),
+                    rtol=5e-16,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.25,
+                    b=4.25,
+                    c=-0.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-28.119407485189985+98.89858821348005j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.75,
+                    b=2.25,
+                    c=1.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(0.5311049067450484-0.9434347326448517j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-15.75,
+                    c=-7.5,
+                    z=(0.9473684210526314+0.10526315789473673j),
+                    expected=(1262084.378141873+1775569.6338380123j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-7.75,
+                    c=-15.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-0.009810480794804165+0.3648997569257999j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=2.25,
+                    c=-3.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(585660.8815535795-33646.68398590896j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.9316537064827854,
+                    c=-15.963511401609862,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(181899621848365.2-173207123998705.7j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=8.25,
+                    c=-0.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.04271686244952705-0.14087902824639406j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-1.92872979730171,
+                    c=-0.906685989801748,
+                    z=(0.9473684210526314-0.3157894736842106j),
+                    expected=(-449.5119088817207+320.1423128036188j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=1.0561196186065624,
+                    c=8.031683612216888,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.6361479738012501+0.028575620091205088j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=16.25,
+                    c=16.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-0.9038811840552261-1.5356250756164884j),
+                    rtol=1e-8,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-1.75,
+                    c=-1.5,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(653.0109150415394-4554.162605155542j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-3.75,
+                    c=4.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(118.7009859241035-34.18713648654642j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=-15.75,
+                    c=-3.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-540204.4774526551+4970059.109251281j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-15.75,
+                    c=-0.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(2253490.972258385+3318620.683390017j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-7.75,
+                    c=-7.5,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(-46159826.46716958-17880663.82218242j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=-7.93846038215665,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.07116833581404514+0.11823358038036977j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=4.0013768449590685,
+                    c=-7.93846038215665,
+                    z=(0.7368421052631575+0.5263157894736841j),
+                    expected=(4.7724909620664006e+17-6.039064078946702e+16j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.25,
+                    b=-7.75,
+                    c=1.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.0188022179759303+0.002921737281641378j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=1.0561196186065624,
+                    c=-7.93846038215665,
+                    z=(0.7368421052631575-0.5263157894736843j),
+                    expected=(-9203.462928334846+12390.110518017136j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-15.75,
+                    c=8.5,
+                    z=(0.7368421052631575+0.5263157894736841j),
+                    expected=(6.468457061368628+24.190040684917374j),
+                    rtol=5e-16,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=16.088264119063613,
+                    c=2.0397202577726152,
+                    z=(0.7368421052631575+0.5263157894736841j),
+                    expected=(2408.3451340186543-4275.257316636014j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-7.75,
+                    c=8.5,
+                    z=(0.7368421052631575-0.5263157894736843j),
+                    expected=(4.1379984626381345-5.183654781039423j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-7.75,
+                    c=-0.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-81177.775295738+56079.73286548954j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=2.050308316530781,
+                    c=-0.906685989801748,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(1192868.5068926765+3624210.8182139914j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-1.92872979730171,
+                    c=8.031683612216888,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(1.8286341846195202+1.9295255682312178j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=1.0561196186065624,
+                    c=16.056809865262608,
+                    z=(0.7368421052631575-0.5263157894736843j),
+                    expected=(1.0514645669696452-0.0430834059440128j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-15.964218273004214,
+                    c=2.0397202577726152,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(541983.236432269+288200.2043029435j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.25,
+                    b=8.25,
+                    c=1.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-10.931988086039945+1.9136272843579096j),
+                    rtol=1e-15,
+                ),
+            ),
+        ]
+    )
+    def test_region3(self, hyp2f1_test_case):
+        """0.9 <= |z| <= 1 and |1 - z| < 0.9."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=4.25,
+                    c=2.5,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(38.41207903409937-30.510151276075792j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.0,
+                    b=16.087593263474208,
+                    c=16.088264119063613,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(-0.6667857912761286-1.0206224321443573j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.0,
+                    b=1.0272592605282642,
+                    c=-7.949900487447654,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(1679024.1647997478-2748129.775857212j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=16.0,
+                    c=-7.949900487447654,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(424747226301.16986-1245539049327.2856j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=-15.964218273004214,
+                    c=4.0,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(-0.0057826199201757595+0.026359861999025885j),
+                    rtol=5e-06,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(0.4671901063492606+0.7769632229834897j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.0,
+                    b=-3.956227226099288,
+                    c=-7.949900487447654,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(0.9422283708145973+1.3476905754773343j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0,
+                    b=-15.980848054962111,
+                    c=-15.964218273004214,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(0.4168719497319604-0.9770953555235625j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=16.088264119063613,
+                    c=2.5,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(1.279096377550619-2.173827694297929j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=4.0013768449590685,
+                    c=2.0397202577726152,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-2.071520656161738-0.7846098268395909j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=8.0,
+                    c=-0.9629749245209605,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(-7.740015495862889+3.386766435696699j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=16.088264119063613,
+                    c=-7.93846038215665,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-6318.553685853241-7133.416085202879j),
+                    rtol=5e-9,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=-3.9316537064827854,
+                    c=16.056809865262608,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(-0.8854577905547399+8.135089099967278j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=-0.9629749245209605,
+                    c=4.078873014294075,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(1.224291301521487+0.36014711766402485j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-0.75,
+                    c=-1.5,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-1.5765685855028473-3.9399766961046323j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=-1.92872979730171,
+                    c=-7.93846038215665,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(56.794588688231194+4.556286783533971j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=4.5,
+                    c=2.050308316530781,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(-4.251456563455306+6.737837111569671j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=8.5,
+                    c=-1.92872979730171,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(2177143.9156599627-3313617.2748088865j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=-1.5,
+                    c=4.0013768449590685,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(0.45563554481603946+0.6212000158060831j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-7.5,
+                    c=-15.964218273004214,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(61.03201617828073-37.185626416756214j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=16.5,
+                    c=4.0013768449590685,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-33143.425963520735+20790.608514722644j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=4.5,
+                    c=-0.9629749245209605,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(30.778600270824423-26.65160354466787j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-3.5,
+                    c=16.088264119063613,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(1.0629792615560487-0.08308454486044772j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=-7.5,
+                    c=-0.9629749245209605,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(17431.571802591767+3553.7129767034507j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.25,
+                    b=8.25,
+                    c=16.5,
+                    z=(0.11379310344827598+0.9482758620689657j),
+                    expected=(0.4468600750211926+0.7313214934036885j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=16.25,
+                    c=4.5,
+                    z=(0.3413793103448277+0.8724137931034486j),
+                    expected=(-3.905704438293991+3.693347860329299j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=4.25,
+                    c=-0.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-40.31777941834244-89.89852492432011j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=8.0,
+                    c=-15.964218273004214,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(52584.347773055284-109197.86244309516j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-15.964218273004214,
+                    c=16.056809865262608,
+                    z=(0.03793103448275881+0.9482758620689657j),
+                    expected=(-1.187733570412592-1.5147865053584582j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.9316537064827854,
+                    c=1.0651378143226575,
+                    z=(0.26551724137931054+0.9482758620689657j),
+                    expected=(13.077494677898947+35.071599628224966j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.5,
+                    c=-3.5,
+                    z=(0.26551724137931054+0.8724137931034486j),
+                    expected=(-0.5359656237994614-0.2344483936591811j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=-3.75,
+                    c=-1.5,
+                    z=(0.26551724137931054+0.9482758620689657j),
+                    expected=(1204.8114871663133+64.41022826840198j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=16.0,
+                    c=4.0013768449590685,
+                    z=(0.03793103448275881-0.9482758620689655j),
+                    expected=(-9.85268872413994+7.011107558429154j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=16.0,
+                    c=4.0013768449590685,
+                    z=(0.3413793103448277-0.8724137931034484j),
+                    expected=(528.5522951158454-1412.21630264791j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=1.0561196186065624,
+                    c=-7.5,
+                    z=(0.4172413793103451+0.8724137931034486j),
+                    expected=(133306.45260685298+256510.7045225382j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=8.077282662161238,
+                    c=-15.963511401609862,
+                    z=(0.3413793103448277-0.8724137931034484j),
+                    expected=(-0.998555715276967+2.774198742229889j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.75,
+                    b=-0.75,
+                    c=1.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(2.072445019723025-2.9793504811373515j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-1.92872979730171,
+                    c=1.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-41.87581944176649-32.52980303527139j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-15.75,
+                    c=-0.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-3729.6214864209774-30627.510509112635j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-15.964218273004214,
+                    c=-0.906685989801748,
+                    z=(0.03793103448275881+0.9482758620689657j),
+                    expected=(-131615.07820609974+145596.13384245415j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=16.5,
+                    c=16.088264119063613,
+                    z=(0.26551724137931054+0.8724137931034486j),
+                    expected=(0.18981844071070744+0.7855036242583742j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.5,
+                    b=8.5,
+                    c=-3.9316537064827854,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(110224529.2376068+128287212.04290268j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=-7.5,
+                    c=4.0013768449590685,
+                    z=(0.3413793103448277-0.8724137931034484j),
+                    expected=(0.2722302180888523-0.21790187837266162j),
+                    rtol=1e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-7.5,
+                    c=-15.964218273004214,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-2.8252338010989035+2.430661949756161j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=16.5,
+                    c=4.0013768449590685,
+                    z=(0.03793103448275881+0.9482758620689657j),
+                    expected=(-20.604894257647945+74.5109432558078j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=8.5,
+                    c=-0.9629749245209605,
+                    z=(0.3413793103448277+0.8724137931034486j),
+                    expected=(-2764422.521269463-3965966.9965808876j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.5,
+                    b=-0.5,
+                    c=1.0561196186065624,
+                    z=(0.26551724137931054+0.9482758620689657j),
+                    expected=(1.2262338560994905+0.6545051266925549j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-15.5,
+                    c=-7.949900487447654,
+                    z=(0.4172413793103451-0.8724137931034484j),
+                    expected=(-2258.1590330318213+8860.193389158803j),
+                    rtol=1.4e-10,
+                ),
+            ),
+        ]
+    )
+    def test_region4(self, hyp2f1_test_case):
+        """0.9 <= |z| <= 1 and |1 - z| >= 1.
+
+        This region is unhandled by of the standard transformations and
+        needs special care.
+        """
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=16.088264119063613,
+                    c=8.5,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(0.018601324701770394-0.07618420586062377j),
+                    rtol=5e-08,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=4.25,
+                    c=4.5,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(-1.391549471425551-0.118036604903893j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=2.050308316530781,
+                    c=-1.9631175993998025,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(-2309.178768155151-1932.7247727595172j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=1.0,
+                    c=-15.964218273004214,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(85592537010.05054-8061416766688.324j),
+                    rtol=2e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-0.5,
+                    c=1.5,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(1.2334498208515172-2.1639498536219732j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-15.964218273004214,
+                    c=4.0,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(102266.35398605966-44976.97828737755j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.0,
+                    b=-3.956227226099288,
+                    c=-15.964218273004214,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(-2.9590030930007236-4.190770764773225j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-15.5,
+                    c=-7.5,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(-112554838.92074208+174941462.9202412j),
+                    rtol=5e-05,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=2.050308316530781,
+                    c=1.0,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(3.7519882374080145+7.360753798667486j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=2.050308316530781,
+                    c=4.0,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(0.000181132943964693+0.07742903103815582j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=4.0013768449590685,
+                    c=-1.9631175993998025,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(386338.760913596-386166.51762171905j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=8.0,
+                    c=-1.92872979730171,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(1348667126.3444858-2375132427.158893j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=-0.9629749245209605,
+                    c=4.5,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(1.428353429538678+0.6472718120804372j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(3.1439267526119643-3.145305240375117j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=-15.964218273004214,
+                    c=-7.93846038215665,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(75.27467675681773+144.0946946292215j),
+                    rtol=1e-07,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-7.75,
+                    c=-7.5,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(-0.3699450626264222+0.8732812475910993j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=16.5,
+                    c=1.0561196186065624,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(5.5361025821300665-2.4709693474656285j),
+                    rtol=5e-09,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=8.5,
+                    c=-3.9316537064827854,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(-782805.6699207705-537192.581278909j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=-15.5,
+                    c=1.0561196186065624,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(12.345113400639693-14.993248992902007j),
+                    rtol=0.0005,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=-0.5,
+                    c=-15.964218273004214,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(23.698109392667842+97.15002033534108j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=16.5,
+                    c=4.0013768449590685,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(1115.2978631811834+915.9212658718577j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=16.5,
+                    c=-0.9629749245209605,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(642077722221.6489+535274495398.21027j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=-3.5,
+                    c=4.0013768449590685,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(-5.689219222945697+16.877463062787143j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-1.5,
+                    c=-0.9629749245209605,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(-44.32070290703576+1026.9127058617403j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=2.25,
+                    c=4.5,
+                    z=(0.11379310344827598-1.024137931034483j),
+                    expected=(-0.021965227124574663+0.009908300237809064j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=1.5,
+                    c=16.5,
+                    z=(0.26551724137931054+1.024137931034483j),
+                    expected=(1.0046072901244183+0.19945500134119992j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=1.0,
+                    c=-3.9316537064827854,
+                    z=(0.3413793103448277+0.9482758620689657j),
+                    expected=(21022.30133421465+49175.98317370489j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=16.088264119063613,
+                    c=-1.9631175993998025,
+                    z=(0.4172413793103451-0.9482758620689655j),
+                    expected=(-7024239.358547302+2481375.02681063j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-15.75,
+                    c=1.5,
+                    z=(0.18965517241379315+1.024137931034483j),
+                    expected=(92371704.94848-403546832.548352j),
+                    rtol=5e-06,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-7.949900487447654,
+                    c=8.5,
+                    z=(0.26551724137931054-1.024137931034483j),
+                    expected=(1.9335109845308265+5.986542524829654j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-1.92872979730171,
+                    c=-7.93846038215665,
+                    z=(0.4931034482758623+0.8724137931034486j),
+                    expected=(-122.52639696039328-59.72428067512221j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-1.75,
+                    c=-1.5,
+                    z=(0.4931034482758623+0.9482758620689657j),
+                    expected=(-90.40642053579428+50.50649180047921j),
+                    rtol=5e-08,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=8.077282662161238,
+                    c=16.5,
+                    z=(0.4931034482758623+0.9482758620689657j),
+                    expected=(-0.2155745818150323-0.564628986876639j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=1.0561196186065624,
+                    c=8.031683612216888,
+                    z=(0.4172413793103451-0.9482758620689655j),
+                    expected=(0.9503140488280465+0.11574960074292677j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.75,
+                    b=2.25,
+                    c=-15.5,
+                    z=(0.4172413793103451+0.9482758620689657j),
+                    expected=(0.9285862488442175+0.8203699266719692j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.75,
+                    b=4.25,
+                    c=-15.5,
+                    z=(0.3413793103448277-0.9482758620689655j),
+                    expected=(-1.0509834850116921-1.1145522325486075j),
+                    rtol=1.1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(0.4931034482758623-0.9482758620689655j),
+                    expected=(2.88119116536769-3.4249933450696806j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-15.964218273004214,
+                    c=16.5,
+                    z=(0.18965517241379315+1.024137931034483j),
+                    expected=(199.65868451496038+347.79384207302877j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-15.75,
+                    c=-3.5,
+                    z=(0.4931034482758623-0.8724137931034484j),
+                    expected=(-208138312553.07013+58631611809.026955j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-15.5,
+                    c=-7.5,
+                    z=(0.3413793103448277+0.9482758620689657j),
+                    expected=(-23032.90519856288-18256.94050457296j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=1.5,
+                    c=1.0561196186065624,
+                    z=(0.4931034482758623-0.8724137931034484j),
+                    expected=(1.507342459587056+1.2332023580148403j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=4.5,
+                    c=-3.9316537064827854,
+                    z=(0.4172413793103451+0.9482758620689657j),
+                    expected=(7044.766127108853-40210.365567285575j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=-1.5,
+                    c=1.0561196186065624,
+                    z=(0.03793103448275881+1.024137931034483j),
+                    expected=(0.2725347741628333-2.247314875514784j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=-1.5,
+                    c=-7.949900487447654,
+                    z=(0.26551724137931054+1.024137931034483j),
+                    expected=(-11.250200011017546+12.597393659160472j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=8.5,
+                    c=16.088264119063613,
+                    z=(0.26551724137931054+1.024137931034483j),
+                    expected=(-0.18515160890991517+0.7959014164484782j),
+                    rtol=2e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=16.5,
+                    c=-3.9316537064827854,
+                    z=(0.3413793103448277-1.024137931034483j),
+                    expected=(998246378.8556538+1112032928.103645j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.5,
+                    b=-3.5,
+                    c=2.050308316530781,
+                    z=(0.03793103448275881+1.024137931034483j),
+                    expected=(0.5527670397711952+2.697662715303637j),
+                    rtol=1.2e-15,       # rtol bumped from 1e-15 in gh18414
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-1.5,
+                    c=-0.9629749245209605,
+                    z=(0.4931034482758623-0.8724137931034484j),
+                    expected=(55.396931662136886+968.467463806326j),
+                    rtol=5e-14,
+                ),
+            ),
+        ]
+    )
+    def test_region5(self, hyp2f1_test_case):
+        """1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0"""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=4.0013768449590685,
+                    c=4.078873014294075,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(-0.0018093573941378783+0.003481887377423739j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=2.050308316530781,
+                    c=1.0651378143226575,
+                    z=(-0.736842105263158-0.736842105263158j),
+                    expected=(-0.00023401243818780545-1.7983496305603562e-05j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=8.077282662161238,
+                    c=4.078873014294075,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(0.22359773002226846-0.24092487123993353j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=2.050308316530781,
+                    c=-15.963511401609862,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(1.191573745740011+0.14347394589721466j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=4.0013768449590685,
+                    c=-15.963511401609862,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(31.822620756901784-66.09094396747611j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=8.077282662161238,
+                    c=-7.93846038215665,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(207.16750179245952+34.80478274924269j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-7.949900487447654,
+                    c=8.031683612216888,
+                    z=(-0.736842105263158+0.7368421052631575j),
+                    expected=(-159.62429364277145+9.154224290644898j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-1.92872979730171,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(1.121122351247184-0.07170260470126685j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-0.9629749245209605,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(1.9040596681316053-0.4951799449960107j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-1.92872979730171,
+                    c=-0.906685989801748,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(-14.496623497780739-21.897524523299875j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.9316537064827854,
+                    c=-3.9924618758357022,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(36.33473466026878+253.88728442029577j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-15.964218273004214,
+                    c=-0.906685989801748,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(1505052.5653144997-50820766.81043443j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=4.0013768449590685,
+                    c=1.0651378143226575,
+                    z=(-0.5263157894736843+0.9473684210526314j),
+                    expected=(-127.79407519260877-28.69899444941112j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=8.077282662161238,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(2.0623331933754976+0.741234463565458j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=8.077282662161238,
+                    c=2.0397202577726152,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(30.729193458862525-292.5700835046965j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=1.0561196186065624,
+                    c=-1.9631175993998025,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(1.1285917906203495-0.735264575450189j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=1.0561196186065624,
+                    c=-3.9924618758357022,
+                    z=(-0.736842105263158+0.7368421052631575j),
+                    expected=(0.6356474446678052-0.02429663008952248j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=16.088264119063613,
+                    c=-7.93846038215665,
+                    z=(-0.736842105263158+0.7368421052631575j),
+                    expected=(0.4718880510273174+0.655083067736377j),
+                    rtol=1e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-3.9316537064827854,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(-0.14681550942352714+0.16092206364265146j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-15.964218273004214,
+                    c=1.0651378143226575,
+                    z=(-0.5263157894736843+0.9473684210526314j),
+                    expected=(-6.436835190526225+22.883156700606182j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=4.078873014294075,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(-0.7505682955068583-1.1026583264249945j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-3.9316537064827854,
+                    c=-7.93846038215665,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(3.6247814989198166+2.596041360148318j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-15.964218273004214,
+                    c=-1.9631175993998025,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(-59537.65287927933-669074.4342539902j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-15.964218273004214,
+                    c=-1.9631175993998025,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(-433084.9970266166+431088.393918521j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1,
+                    b=1,
+                    c=4,
+                    z=(3 + 4j),
+                    expected=(0.49234384000963544+0.6051340616612397j),
+                    rtol=5e-14,
+                ),
+            ),
+        ]
+    )
+    def test_region6(self, hyp2f1_test_case):
+        """|z| > 1 but not in region 5."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert (
+            abs(z) > 1 and
+            not (1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0)
+        )
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            # Broke when fixing gamma pole behavior in gh-21827
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.3,
+                    b=-0.2,
+                    c=0.3,
+                    z=-2.1,
+                    expected=1.8202169687521206,
+                    rtol=5e-15,
+                ),
+            ),
+        ]
+    )
+    def test_miscellaneous(self, hyp2f1_test_case ):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.slow
+    @check_version(mpmath, "1.0.0")
+    def test_test_hyp2f1(self):
+        """Test that expected values match what is computed by mpmath.
+
+        This gathers the parameters for the test cases out of the pytest marks.
+        The parameters are a, b, c, z, expected, rtol, where expected should
+        be the value of hyp2f1(a, b, c, z) computed with mpmath. The test
+        recomputes hyp2f1(a, b, c, z) using mpmath and verifies that expected
+        actually is the correct value. This allows the data for the tests to
+        live within the test code instead of an external datafile, while
+        avoiding having to compute the results with mpmath during the test,
+        except for when slow tests are being run.
+        """
+        test_methods = [
+            test_method for test_method in dir(self)
+            if test_method.startswith('test') and
+            # Filter properties and attributes (futureproofing).
+            callable(getattr(self, test_method)) and
+            # Filter out this test
+            test_method != 'test_test_hyp2f1'
+        ]
+        for test_method in test_methods:
+            params = self._get_test_parameters(getattr(self, test_method))
+            for a, b, c, z, expected, _ in params:
+                assert_allclose(mp_hyp2f1(a, b, c, z), expected, rtol=2.25e-16)
+
+    def _get_test_parameters(self, test_method):
+        """Get pytest.mark parameters for a test in this class."""
+        return [
+            case.values[0] for mark in test_method.pytestmark
+            if mark.name == 'parametrize'
+            for case in mark.args[1]
+        ]
+
+class TestHyp2f1ExtremeInputs:
+
+    @pytest.mark.parametrize("a", [1.0, 2.0, 3.0, -np.inf, np.inf])
+    @pytest.mark.parametrize("b", [3.0, 4.0, 5.0, -np.inf, np.inf])
+    @pytest.mark.parametrize("c", [3.0, 5.0, 6.0, 7.0])
+    @pytest.mark.parametrize("z", [4.0 + 1.0j])
+    def test_inf_a_b(self, a, b, c, z):
+        if np.any(np.isinf(np.asarray([a, b]))):
+            assert(np.isnan(hyp2f1(a, b, c, z)))
+
+    def test_large_a_b(self):
+        assert(np.isnan(hyp2f1(10**7, 1.0, 3.0, 4.0 + 1.0j)))
+        assert(np.isnan(hyp2f1(-10**7, 1.0, 3.0, 4.0 + 1.0j)))
+
+        assert(np.isnan(hyp2f1(1.0, 10**7, 3.0, 4.0 + 1.0j)))
+        assert(np.isnan(hyp2f1(1.0, -10**7, 3.0, 4.0 + 1.0j)))
+
+        # Already correct in main but testing for surety
+        assert(np.isnan(hyp2f1(np.inf, 1.0, 3.0, 4.0)))
+        assert(np.isnan(hyp2f1(1.0, np.inf, 3.0, 4.0)))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ad092491905ae66c39cd881836054aef3dc6f6e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py
@@ -0,0 +1,234 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import scipy.special as sc
+
+
+class TestHyperu:
+
+    def test_negative_x(self):
+        a, b, x = np.meshgrid(
+            [-1, -0.5, 0, 0.5, 1],
+            [-1, -0.5, 0, 0.5, 1],
+            np.linspace(-100, -1, 10),
+        )
+        assert np.all(np.isnan(sc.hyperu(a, b, x)))
+
+    def test_special_cases(self):
+        assert sc.hyperu(0, 1, 1) == 1.0
+
+    @pytest.mark.parametrize('a', [0.5, 1, np.nan])
+    @pytest.mark.parametrize('b', [1, 2, np.nan])
+    @pytest.mark.parametrize('x', [0.25, 3, np.nan])
+    def test_nan_inputs(self, a, b, x):
+        assert np.isnan(sc.hyperu(a, b, x)) == np.any(np.isnan([a, b, x]))
+
+    @pytest.mark.parametrize(
+        'a,b,x,expected',
+        [(0.21581740448533887, 1.0, 1e-05, 3.6030558839391325),
+         (0.21581740448533887, 1.0, 0.00021544346900318823, 2.8783254988948976),
+         (0.21581740448533887, 1.0, 0.004641588833612777, 2.154928216691109),
+         (0.21581740448533887, 1.0, 0.1, 1.446546638718792),
+         (0.0030949064301273865, 1.0, 1e-05, 1.0356696454116199),
+         (0.0030949064301273865, 1.0, 0.00021544346900318823, 1.0261510362481985),
+         (0.0030949064301273865, 1.0, 0.004641588833612777, 1.0166326903402296),
+         (0.0030949064301273865, 1.0, 0.1, 1.0071174207698674),
+         (0.1509924314279033, 1.0, 1e-05, 2.806173846998948),
+         (0.1509924314279033, 1.0, 0.00021544346900318823, 2.3092158526816124),
+         (0.1509924314279033, 1.0, 0.004641588833612777, 1.812905980588048),
+         (0.1509924314279033, 1.0, 0.1, 1.3239738117634872),
+         (-0.010678995342969011, 1.0, 1e-05, 0.8775194903781114),
+         (-0.010678995342969011, 1.0, 0.00021544346900318823, 0.9101008998540128),
+         (-0.010678995342969011, 1.0, 0.004641588833612777, 0.9426854294058609),
+         (-0.010678995342969011, 1.0, 0.1, 0.9753065150174902),
+         (-0.06556622211831487, 1.0, 1e-05, 0.26435429752668904),
+         (-0.06556622211831487, 1.0, 0.00021544346900318823, 0.4574756033875781),
+         (-0.06556622211831487, 1.0, 0.004641588833612777, 0.6507121093358457),
+         (-0.06556622211831487, 1.0, 0.1, 0.8453129788602187),
+         (-0.21628242470175185, 1.0, 1e-05, -1.2318314201114489),
+         (-0.21628242470175185, 1.0, 0.00021544346900318823, -0.6704694233529538),
+         (-0.21628242470175185, 1.0, 0.004641588833612777, -0.10795098653682857),
+         (-0.21628242470175185, 1.0, 0.1, 0.4687227684115524)]
+    )
+    def test_gh_15650_mp(self, a, b, x, expected):
+        # See https://github.com/scipy/scipy/issues/15650
+        # b == 1, |a| < 0.25, 0 < x < 1
+        #
+        # This purpose of this test is to check the accuracy of results
+        # in the region that was impacted by gh-15650.
+        #
+        # Reference values computed with mpmath using the script:
+        #
+        # import itertools as it
+        # import numpy as np
+        #
+        # from mpmath import mp
+        #
+        # rng = np.random.default_rng(1234)
+        #
+        # cases = []
+        # for a, x in it.product(
+        #         np.random.uniform(-0.25, 0.25, size=6),
+        #         np.logspace(-5, -1, 4),
+        # ):
+        #     with mp.workdps(100):
+        #         cases.append((float(a), 1.0, float(x), float(mp.hyperu(a, 1.0, x))))
+        assert_allclose(sc.hyperu(a, b, x), expected, rtol=1e-13)
+
+    def test_gh_15650_sanity(self):
+        # The purpose of this test is to sanity check hyperu in the region that
+        # was impacted by gh-15650 by making sure there are no excessively large
+        # results, as were reported there.
+        a = np.linspace(-0.5, 0.5, 500)
+        x = np.linspace(1e-6, 1e-1, 500)
+        a, x = np.meshgrid(a, x)
+        results = sc.hyperu(a, 1.0, x)
+        assert np.all(np.abs(results) < 1e3)
+
+
+class TestHyp1f1:
+
+    @pytest.mark.parametrize('a, b, x', [
+        (np.nan, 1, 1),
+        (1, np.nan, 1),
+        (1, 1, np.nan)
+    ])
+    def test_nan_inputs(self, a, b, x):
+        assert np.isnan(sc.hyp1f1(a, b, x))
+
+    def test_poles(self):
+        assert_equal(sc.hyp1f1(1, [0, -1, -2, -3, -4], 0.5), np.inf)
+
+    @pytest.mark.parametrize('a, b, x, result', [
+        (-1, 1, 0.5, 0.5),
+        (1, 1, 0.5, 1.6487212707001281468),
+        (2, 1, 0.5, 2.4730819060501922203),
+        (1, 2, 0.5, 1.2974425414002562937),
+        (-10, 1, 0.5, -0.38937441413785204475)
+    ])
+    def test_special_cases(self, a, b, x, result):
+        # Hit all the special case branches at the beginning of the
+        # function. Desired answers computed using Mpmath.
+        assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15)
+
+    @pytest.mark.parametrize('a, b, x, result', [
+        (1, 1, 0.44, 1.5527072185113360455),
+        (-1, 1, 0.44, 0.55999999999999999778),
+        (100, 100, 0.89, 2.4351296512898745592),
+        (-100, 100, 0.89, 0.40739062490768104667),
+        (1.5, 100, 59.99, 3.8073513625965598107),
+        (-1.5, 100, 59.99, 0.25099240047125826943)
+    ])
+    def test_geometric_convergence(self, a, b, x, result):
+        # Test the region where we are relying on the ratio of
+        #
+        # (|a| + 1) * |x| / |b|
+        #
+        # being small. Desired answers computed using Mpmath
+        assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15)
+
+    @pytest.mark.parametrize('a, b, x, result', [
+        (-1, 1, 1.5, -0.5),
+        (-10, 1, 1.5, 0.41801777430943080357),
+        (-25, 1, 1.5, 0.25114491646037839809),
+        (-50, 1, 1.5, -0.25683643975194756115),
+        (-80, 1, 1.5, -0.24554329325751503601),
+        (-150, 1, 1.5, -0.173364795515420454496),
+    ])
+    def test_a_negative_integer(self, a, b, x, result):
+        # Desired answers computed using Mpmath.
+        assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=2e-14)
+
+    @pytest.mark.parametrize('a, b, x, expected', [
+        (0.01, 150, -4, 0.99973683897677527773),        # gh-3492
+        (1, 5, 0.01, 1.0020033381011970966),            # gh-3593
+        (50, 100, 0.01, 1.0050126452421463411),         # gh-3593
+        (1, 0.3, -1e3, -7.011932249442947651455e-04),   # gh-14149
+        (1, 0.3, -1e4, -7.001190321418937164734e-05),   # gh-14149
+        (9, 8.5, -350, -5.224090831922378361082e-20),   # gh-17120
+        (9, 8.5, -355, -4.595407159813368193322e-20),   # gh-17120
+        (75, -123.5, 15, 3.425753920814889017493e+06),
+    ])
+    def test_assorted_cases(self, a, b, x, expected):
+        # Expected values were computed with mpmath.hyp1f1(a, b, x).
+        assert_allclose(sc.hyp1f1(a, b, x), expected, atol=0, rtol=1e-14)
+
+    def test_a_neg_int_and_b_equal_x(self):
+        # This is a case where the Boost wrapper will call hypergeometric_pFq
+        # instead of hypergeometric_1F1.  When we use a version of Boost in
+        # which https://github.com/boostorg/math/issues/833 is fixed, this
+        # test case can probably be moved into test_assorted_cases.
+        # The expected value was computed with mpmath.hyp1f1(a, b, x).
+        a = -10.0
+        b = 2.5
+        x = 2.5
+        expected = 0.0365323664364104338721
+        computed = sc.hyp1f1(a, b, x)
+        assert_allclose(computed, expected, atol=0, rtol=1e-13)
+
+    @pytest.mark.parametrize('a, b, x, desired', [
+        (-1, -2, 2, 2),
+        (-1, -4, 10, 3.5),
+        (-2, -2, 1, 2.5)
+    ])
+    def test_gh_11099(self, a, b, x, desired):
+        # All desired results computed using Mpmath
+        assert sc.hyp1f1(a, b, x) == desired
+
+    @pytest.mark.parametrize('a', [-3, -2])
+    def test_x_zero_a_and_b_neg_ints_and_a_ge_b(self, a):
+        assert sc.hyp1f1(a, -3, 0) == 1
+
+    # In the following tests with complex z, the reference values
+    # were computed with mpmath.hyp1f1(a, b, z), and verified with
+    # Wolfram Alpha Hypergeometric1F1(a, b, z), except for the
+    # case a=0.1, b=1, z=7-24j, where Wolfram Alpha reported
+    # "Standard computation time exceeded".  That reference value
+    # was confirmed in an online Matlab session, with the commands
+    #
+    #  > format long
+    #  > hypergeom(0.1, 1, 7-24i)
+    #  ans =
+    #   -3.712349651834209 + 4.554636556672912i
+    #
+    @pytest.mark.parametrize(
+        'a, b, z, ref',
+        [(-0.25, 0.5, 1+2j, 1.1814553180903435-1.2792130661292984j),
+         (0.25, 0.5, 1+2j, 0.24636797405707597+1.293434354945675j),
+         (25, 1.5, -2j, -516.1771262822523+407.04142751922024j),
+         (12, -1.5, -10+20j, -5098507.422706547-1341962.8043508842j),
+         pytest.param(
+             10, 250, 10-15j, 1.1985998416598884-0.8613474402403436j,
+             marks=pytest.mark.xfail,
+         ),
+         pytest.param(
+             0.1, 1, 7-24j, -3.712349651834209+4.554636556672913j,
+             marks=pytest.mark.xfail,
+         )
+         ],
+    )
+    def test_complex_z(self, a, b, z, ref):
+        h = sc.hyp1f1(a, b, z)
+        assert_allclose(h, ref, rtol=4e-15)
+
+    # The "legacy edge cases" mentioned in the comments in the following
+    # tests refers to the behavior of hyp1f1(a, b, x) when b is a nonpositive
+    # integer.  In some subcases, the behavior of SciPy does not match that
+    # of Boost (1.81+), mpmath and Mathematica (via Wolfram Alpha online).
+    # If the handling of these edges cases is changed to agree with those
+    # libraries, these test will have to be updated.
+
+    @pytest.mark.parametrize('b', [0, -1, -5])
+    def test_legacy_case1(self, b):
+        # Test results of hyp1f1(0, n, x) for n <= 0.
+        # This is a legacy edge case.
+        # Boost (versions greater than 1.80), Mathematica (via Wolfram Alpha
+        # online) and mpmath all return 1 in this case, but SciPy's hyp1f1
+        # returns inf.
+        assert_equal(sc.hyp1f1(0, b, [-1.5, 0, 1.5]), [np.inf, np.inf, np.inf])
+
+    def test_legacy_case2(self):
+        # This is a legacy edge case.
+        # In software such as boost (1.81+), mpmath and Mathematica,
+        # the value is 1.
+        assert sc.hyp1f1(-4, -3, 0) == np.inf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..dafc35982c4d4869ead2136e74466f1c44c64556
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py
@@ -0,0 +1,249 @@
+# This file contains unit tests for iv_ratio() and related functions.
+
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy.special._ufuncs import (  # type: ignore[attr-defined]
+    _iv_ratio as iv_ratio,
+    _iv_ratio_c as iv_ratio_c,
+)
+
+
+class TestIvRatio:
+
+    @pytest.mark.parametrize('v,x,r', [
+        (0.5, 0.16666666666666666, 0.16514041292462933),
+        (0.5, 0.3333333333333333, 0.32151273753163434),
+        (0.5, 0.5, 0.46211715726000974),
+        (0.5, 0.6666666666666666, 0.5827829453479101),
+        (0.5, 0.8333333333333335, 0.6822617902381698),
+        (1, 0.3380952380952381, 0.1666773049170313),
+        (1, 0.7083333333333333, 0.33366443586989925),
+        (1, 1.1666666666666667, 0.5023355231537423),
+        (1, 1.8666666666666665, 0.674616572252164),
+        (1, 3.560606060606061, 0.844207659503163),
+        (2.34, 0.7975238095238094, 0.16704903081553285),
+        (2.34, 1.7133333333333334, 0.3360215931268845),
+        (2.34, 2.953333333333333, 0.50681909317803),
+        (2.34, 5.0826666666666656, 0.6755252698800679),
+        (2.34, 10.869696969696973, 0.8379351104498762),
+        (56.789, 19.46575238095238, 0.1667020505391409),
+        (56.789, 42.55008333333333, 0.33353809996933026),
+        (56.789, 75.552, 0.5003932381177826),
+        (56.789, 135.76026666666667, 0.6670528221946127),
+        (56.789, 307.8642424242425, 0.8334999441460798),
+    ])
+    def test_against_reference_values(self, v, x, r):
+        """The reference values are computed using mpmath as follows.
+
+        from mpmath import mp
+        mp.dps = 100
+
+        def iv_ratio_mp(v, x):
+            return mp.besseli(v, x) / mp.besseli(v - 1, x)
+
+        def _sample(n, *, v):
+            '''Return n positive real numbers x such that iv_ratio(v, x) are
+            roughly evenly spaced over (0, 1).  The formula is taken from [1].
+
+            [1] Banerjee A., Dhillon, I. S., Ghosh, J., Sra, S. (2005).
+                "Clustering on the Unit Hypersphere using von Mises-Fisher
+                Distributions."  Journal of Machine Learning Research,
+                6(46):1345-1382.
+            '''
+            r = np.arange(1, n+1) / (n+1)
+            return r * (2*v-r*r) / (1-r*r)
+
+        for v in (0.5, 1, 2.34, 56.789):
+            xs = _sample(5, v=v)
+            for x in xs:
+                print(f"({v}, {x}, {float(iv_ratio_mp(v,x))}),")
+        """
+        assert_allclose(iv_ratio(v, x), r, rtol=4e-16, atol=0)
+
+    @pytest.mark.parametrize('v,x,r', [
+        (1, np.inf, 1),
+        (np.inf, 1, 0),
+    ])
+    def test_inf(self, v, x, r):
+        """If exactly one of v or x is inf and the other is within domain,
+        should return 0 or 1 accordingly."""
+        assert_equal(iv_ratio(v, x), r)
+
+    @pytest.mark.parametrize('v', [0.49, -np.inf, np.nan, np.inf])
+    @pytest.mark.parametrize('x', [-np.finfo(float).smallest_normal,
+                                   -np.finfo(float).smallest_subnormal,
+                                   -np.inf, np.nan, np.inf])
+    def test_nan(self, v, x):
+        """If at least one argument is out of domain, or if v = x = inf,
+        the function should return nan."""
+        assert_equal(iv_ratio(v, x), np.nan)
+
+    @pytest.mark.parametrize('v', [0.5, 1, np.finfo(float).max, np.inf])
+    def test_zero_x(self, v):
+        """If x is +/-0.0, return x to ensure iv_ratio is an odd function."""
+        assert_equal(iv_ratio(v, 0.0), 0.0)
+        assert_equal(iv_ratio(v, -0.0), -0.0)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, np.finfo(float).smallest_normal),
+        (1, np.finfo(float).smallest_subnormal),
+        (1, np.finfo(float).smallest_subnormal*2),
+        (1e20, 123),
+        (np.finfo(float).max, 1),
+        (np.finfo(float).max, np.sqrt(np.finfo(float).max)),
+    ])
+    def test_tiny_x(self, v, x):
+        """If x is much less than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to R ~= x/2v.  Test against this asymptotic expression.
+        """
+        assert_equal(iv_ratio(v, x), (0.5*x)/v)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, 1e16),
+        (1e20, 1e40),
+        (np.sqrt(np.finfo(float).max), np.finfo(float).max),
+    ])
+    def test_huge_x(self, v, x):
+        """If x is much greater than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= ---------------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-0.5+sqrt(x**2+(v-0.5)**2)
+
+        collapses to R ~= 1.  Test against this asymptotic expression.
+        """
+        assert_equal(iv_ratio(v, x), 1.0)
+
+    @pytest.mark.parametrize('v,x', [
+        (np.finfo(float).max, np.finfo(float).max),
+        (np.finfo(float).max / 3, np.finfo(float).max),
+        (np.finfo(float).max, np.finfo(float).max / 3),
+    ])
+    def test_huge_v_x(self, v, x):
+        """If both x and v are very large, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to R ~= x/(v+sqrt(x**2+v**2).  Test against this asymptotic
+        expression, and in particular that no numerical overflow occurs during
+        intermediate calculations.
+        """
+        t = x / v
+        expected = t / (1 + np.hypot(1, t))
+        assert_allclose(iv_ratio(v, x), expected, rtol=4e-16, atol=0)
+
+
+class TestIvRatioC:
+
+    @pytest.mark.parametrize('v,x,r', [
+        (0.5, 0.16666666666666666, 0.8348595870753707),
+        (0.5, 0.3333333333333333, 0.6784872624683657),
+        (0.5, 0.5, 0.5378828427399902),
+        (0.5, 0.6666666666666666, 0.4172170546520899),
+        (0.5, 0.8333333333333335, 0.3177382097618302),
+        (1, 0.3380952380952381, 0.8333226950829686),
+        (1, 0.7083333333333333, 0.6663355641301008),
+        (1, 1.1666666666666667, 0.4976644768462577),
+        (1, 1.8666666666666665, 0.325383427747836),
+        (1, 3.560606060606061, 0.155792340496837),
+        (2.34, 0.7975238095238094, 0.8329509691844672),
+        (2.34, 1.7133333333333334, 0.6639784068731155),
+        (2.34, 2.953333333333333, 0.49318090682197),
+        (2.34, 5.0826666666666656, 0.3244747301199321),
+        (2.34, 10.869696969696973, 0.16206488955012377),
+        (56.789, 19.46575238095238, 0.8332979494608591),
+        (56.789, 42.55008333333333, 0.6664619000306697),
+        (56.789, 75.552, 0.4996067618822174),
+        (56.789, 135.76026666666667, 0.3329471778053873),
+        (56.789, 307.8642424242425, 0.16650005585392025),
+    ])
+    def test_against_reference_values(self, v, x, r):
+        """The reference values are one minus those of TestIvRatio."""
+        assert_allclose(iv_ratio_c(v, x), r, rtol=1e-15, atol=0)
+
+    @pytest.mark.parametrize('v,x,r', [
+        (1, np.inf, 0),
+        (np.inf, 1, 1),
+    ])
+    def test_inf(self, v, x, r):
+        """If exactly one of v or x is inf and the other is within domain,
+        should return 0 or 1 accordingly."""
+        assert_equal(iv_ratio_c(v, x), r)
+
+    @pytest.mark.parametrize('v', [0.49, -np.inf, np.nan, np.inf])
+    @pytest.mark.parametrize('x', [-np.finfo(float).smallest_normal,
+                                   -np.finfo(float).smallest_subnormal,
+                                   -np.inf, np.nan, np.inf])
+    def test_nan(self, v, x):
+        """If at least one argument is out of domain, or if v = x = inf,
+        the function should return nan."""
+        assert_equal(iv_ratio_c(v, x), np.nan)
+
+    @pytest.mark.parametrize('v', [0.5, 1, np.finfo(float).max, np.inf])
+    def test_zero_x(self, v):
+        """If x is +/-0.0, return 1."""
+        assert_equal(iv_ratio_c(v, 0.0), 1.0)
+        assert_equal(iv_ratio_c(v, -0.0), 1.0)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, np.finfo(float).smallest_normal),
+        (1, np.finfo(float).smallest_subnormal),
+        (1, np.finfo(float).smallest_subnormal*2),
+        (1e20, 123),
+        (np.finfo(float).max, 1),
+        (np.finfo(float).max, np.sqrt(np.finfo(float).max)),
+    ])
+    def test_tiny_x(self, v, x):
+        """If x is much less than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to 1-R ~= 1-x/2v.  Test against this asymptotic expression.
+        """
+        assert_equal(iv_ratio_c(v, x), 1.0-(0.5*x)/v)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, 1e16),
+        (1e20, 1e40),
+        (np.sqrt(np.finfo(float).max), np.finfo(float).max),
+    ])
+    def test_huge_x(self, v, x):
+        """If x is much greater than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= ---------------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-0.5+sqrt(x**2+(v-0.5)**2)
+
+        collapses to 1-R ~= (v-0.5)/x.  Test against this asymptotic expression.
+        """
+        assert_allclose(iv_ratio_c(v, x), (v-0.5)/x, rtol=1e-15, atol=0)
+
+    @pytest.mark.parametrize('v,x', [
+        (np.finfo(float).max, np.finfo(float).max),
+        (np.finfo(float).max / 3, np.finfo(float).max),
+        (np.finfo(float).max, np.finfo(float).max / 3),
+    ])
+    def test_huge_v_x(self, v, x):
+        """If both x and v are very large, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to 1 - R ~= 1 - x/(v+sqrt(x**2+v**2).  Test against this
+        asymptotic expression, and in particular that no numerical overflow
+        occurs during intermediate calculations.
+        """
+        t = x / v
+        expected = 1 - t / (1 + np.hypot(1, t))
+        assert_allclose(iv_ratio_c(v, x), expected, rtol=4e-16, atol=0)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py
new file mode 100644
index 0000000000000000000000000000000000000000..ade38115706808809890e1eba3b938562b0af6e6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py
@@ -0,0 +1,491 @@
+import itertools
+
+import numpy as np
+from numpy.testing import assert_
+from scipy.special._testutils import FuncData
+
+from scipy.special import kolmogorov, kolmogi, smirnov, smirnovi
+from scipy.special._ufuncs import (_kolmogc, _kolmogci, _kolmogp,
+                                   _smirnovc, _smirnovci, _smirnovp)
+
+_rtol = 1e-10
+
+class TestSmirnov:
+    def test_nan(self):
+        assert_(np.isnan(smirnov(1, np.nan)))
+
+    def test_basic(self):
+        dataset = [(1, 0.1, 0.9),
+                   (1, 0.875, 0.125),
+                   (2, 0.875, 0.125 * 0.125),
+                   (3, 0.875, 0.125 * 0.125 * 0.125)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0(self):
+        dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_1(self):
+        dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0point5(self):
+        dataset = [(1, 0.5, 0.5),
+                   (2, 0.5, 0.25),
+                   (3, 0.5, 0.166666666667),
+                   (4, 0.5, 0.09375),
+                   (5, 0.5, 0.056),
+                   (6, 0.5, 0.0327932098765),
+                   (7, 0.5, 0.0191958707681),
+                   (8, 0.5, 0.0112953186035),
+                   (9, 0.5, 0.00661933257355),
+                   (10, 0.5, 0.003888705)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_1(self):
+        x = np.linspace(0, 1, 101, endpoint=True)
+        dataset = np.column_stack([[1]*len(x), x, 1-x])
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_2(self):
+        x = np.linspace(0.5, 1, 101, endpoint=True)
+        p = np.power(1-x, 2)
+        n = np.array([2] * len(x))
+        dataset = np.column_stack([n, x, p])
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_3(self):
+        x = np.linspace(0.7, 1, 31, endpoint=True)
+        p = np.power(1-x, 3)
+        n = np.array([3] * len(x))
+        dataset = np.column_stack([n, x, p])
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_large(self):
+        # test for large values of n
+        # Probabilities should go down as n goes up
+        x = 0.4
+        pvals = np.array([smirnov(n, x) for n in range(400, 1100, 20)])
+        dfs = np.diff(pvals)
+        assert_(np.all(dfs <= 0), msg=f'Not all diffs negative {dfs}')
+
+
+class TestSmirnovi:
+    def test_nan(self):
+        assert_(np.isnan(smirnovi(1, np.nan)))
+
+    def test_basic(self):
+        dataset = [(1, 0.4, 0.6),
+                   (1, 0.6, 0.4),
+                   (1, 0.99, 0.01),
+                   (1, 0.01, 0.99),
+                   (2, 0.125 * 0.125, 0.875),
+                   (3, 0.125 * 0.125 * 0.125, 0.875),
+                   (10, 1.0 / 16 ** 10, 1 - 1.0 / 16)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0(self):
+        dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_1(self):
+        dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_1(self):
+        pp = np.linspace(0, 1, 101, endpoint=True)
+        # dataset = np.array([(1, p, 1-p) for p in pp])
+        dataset = np.column_stack([[1]*len(pp), pp, 1-pp])
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_2(self):
+        x = np.linspace(0.5, 1, 101, endpoint=True)
+        p = np.power(1-x, 2)
+        n = np.array([2] * len(x))
+        dataset = np.column_stack([n, p, x])
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_3(self):
+        x = np.linspace(0.7, 1, 31, endpoint=True)
+        p = np.power(1-x, 3)
+        n = np.array([3] * len(x))
+        dataset = np.column_stack([n, p, x])
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_round_trip(self):
+        def _sm_smi(n, p):
+            return smirnov(n, smirnovi(n, p))
+
+        def _smc_smci(n, p):
+            return _smirnovc(n, _smirnovci(n, p))
+
+        dataset = [(1, 0.4, 0.4),
+                   (1, 0.6, 0.6),
+                   (2, 0.875, 0.875),
+                   (3, 0.875, 0.875),
+                   (3, 0.125, 0.125),
+                   (10, 0.999, 0.999),
+                   (10, 0.0001, 0.0001)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            _sm_smi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        FuncData(
+            _smc_smci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0point5(self):
+        dataset = [(1, 0.5, 0.5),
+                   (2, 0.5, 0.366025403784),
+                   (2, 0.25, 0.5),
+                   (3, 0.5, 0.297156508177),
+                   (4, 0.5, 0.255520481121),
+                   (5, 0.5, 0.234559536069),
+                   (6, 0.5, 0.21715965898),
+                   (7, 0.5, 0.202722580034),
+                   (8, 0.5, 0.190621765256),
+                   (9, 0.5, 0.180363501362),
+                   (10, 0.5, 0.17157867006)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+
+class TestSmirnovp:
+    def test_nan(self):
+        assert_(np.isnan(_smirnovp(1, np.nan)))
+
+    def test_basic(self):
+        # Check derivative at endpoints
+        n1_10 = np.arange(1, 10)
+        dataset0 = np.column_stack([n1_10,
+                                    np.full_like(n1_10, 0),
+                                    np.full_like(n1_10, -1)])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+        n2_10 = np.arange(2, 10)
+        dataset1 = np.column_stack([n2_10,
+                                    np.full_like(n2_10, 1.0),
+                                    np.full_like(n2_10, 0)])
+        FuncData(
+            _smirnovp, dataset1, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneminusoneovern(self):
+        # Check derivative at x=1-1/n
+        n = np.arange(1, 20)
+        x = 1.0/n
+        xm1 = 1-1.0/n
+        pp1 = -n * x**(n-1)
+        pp1 -= (1-np.sign(n-2)**2) * 0.5  # n=2, x=0.5, 1-1/n = 0.5, need to adjust
+        dataset1 = np.column_stack([n, xm1, pp1])
+        FuncData(
+            _smirnovp, dataset1, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneovertwon(self):
+        # Check derivative at x=1/2n  (Discontinuous at x=1/n, so check at x=1/2n)
+        n = np.arange(1, 20)
+        x = 1.0/2/n
+        pp = -(n*x+1) * (1+x)**(n-2)
+        dataset0 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneovern(self):
+        # Check derivative at x=1/n
+        # (Discontinuous at x=1/n, hard to tell if x==1/n, only use n=power of 2)
+        n = 2**np.arange(1, 10)
+        x = 1.0/n
+        pp = -(n*x+1) * (1+x)**(n-2) + 0.5
+        dataset0 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneovernclose(self):
+        # Check derivative at x=1/n
+        # (Discontinuous at x=1/n, test on either side: x=1/n +/- 2epsilon)
+        n = np.arange(3, 20)
+
+        x = 1.0/n - 2*np.finfo(float).eps
+        pp = -(n*x+1) * (1+x)**(n-2)
+        dataset0 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+        x = 1.0/n + 2*np.finfo(float).eps
+        pp = -(n*x+1) * (1+x)**(n-2) + 1
+        dataset1 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset1, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+
+class TestKolmogorov:
+    def test_nan(self):
+        assert_(np.isnan(kolmogorov(np.nan)))
+
+    def test_basic(self):
+        dataset = [(0, 1.0),
+                   (0.5, 0.96394524366487511),
+                   (0.8275735551899077, 0.5000000000000000),
+                   (1, 0.26999967167735456),
+                   (2, 0.00067092525577969533)]
+
+        dataset = np.asarray(dataset)
+        FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_linspace(self):
+        x = np.linspace(0, 2.0, 21)
+        dataset = [1.0000000000000000, 1.0000000000000000, 0.9999999999994950,
+                   0.9999906941986655, 0.9971923267772983, 0.9639452436648751,
+                   0.8642827790506042, 0.7112351950296890, 0.5441424115741981,
+                   0.3927307079406543, 0.2699996716773546, 0.1777181926064012,
+                   0.1122496666707249, 0.0680922218447664, 0.0396818795381144,
+                   0.0222179626165251, 0.0119520432391966, 0.0061774306344441,
+                   0.0030676213475797, 0.0014636048371873, 0.0006709252557797]
+
+        dataset_c = [0.0000000000000000, 6.609305242245699e-53, 5.050407338670114e-13,
+                     9.305801334566668e-06, 0.0028076732227017, 0.0360547563351249,
+                     0.1357172209493958, 0.2887648049703110, 0.4558575884258019,
+                     0.6072692920593457, 0.7300003283226455, 0.8222818073935988,
+                     0.8877503333292751, 0.9319077781552336, 0.9603181204618857,
+                     0.9777820373834749, 0.9880479567608034, 0.9938225693655559,
+                     0.9969323786524203, 0.9985363951628127, 0.9993290747442203]
+
+        dataset = np.column_stack([x, dataset])
+        FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
+        dataset_c = np.column_stack([x, dataset_c])
+        FuncData(_kolmogc, dataset_c, (0,), 1, rtol=_rtol).check()
+
+    def test_linspacei(self):
+        p = np.linspace(0, 1.0, 21, endpoint=True)
+        dataset = [np.inf, 1.3580986393225507, 1.2238478702170823,
+                   1.1379465424937751, 1.0727491749396481, 1.0191847202536859,
+                   0.9730633753323726, 0.9320695842357622, 0.8947644549851197,
+                   0.8601710725555463, 0.8275735551899077, 0.7964065373291559,
+                   0.7661855555617682, 0.7364542888171910, 0.7067326523068980,
+                   0.6764476915028201, 0.6448126061663567, 0.6105590999244391,
+                   0.5711732651063401, 0.5196103791686224, 0.0000000000000000]
+
+        dataset_c = [0.0000000000000000, 0.5196103791686225, 0.5711732651063401,
+                     0.6105590999244391, 0.6448126061663567, 0.6764476915028201,
+                     0.7067326523068980, 0.7364542888171910, 0.7661855555617682,
+                     0.7964065373291559, 0.8275735551899077, 0.8601710725555463,
+                     0.8947644549851196, 0.9320695842357622, 0.9730633753323727,
+                     1.0191847202536859, 1.0727491749396481, 1.1379465424937754,
+                     1.2238478702170825, 1.3580986393225509, np.inf]
+
+        dataset = np.column_stack([p[1:], dataset[1:]])
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+        dataset_c = np.column_stack([p[:-1], dataset_c[:-1]])
+        FuncData(_kolmogci, dataset_c, (0,), 1, rtol=_rtol).check()
+
+    def test_smallx(self):
+        epsilon = 0.1 ** np.arange(1, 14)
+        x = np.array([0.571173265106, 0.441027698518, 0.374219690278, 0.331392659217,
+                      0.300820537459, 0.277539353999, 0.259023494805, 0.243829561254,
+                      0.231063086389, 0.220135543236, 0.210641372041, 0.202290283658,
+                      0.19487060742])
+
+        dataset = np.column_stack([x, 1-epsilon])
+        FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_round_trip(self):
+        def _ki_k(_x):
+            return kolmogi(kolmogorov(_x))
+
+        def _kci_kc(_x):
+            return _kolmogci(_kolmogc(_x))
+
+        x = np.linspace(0.0, 2.0, 21, endpoint=True)
+        # Exclude 0.1, 0.2.  0.2 almost makes succeeds, but 0.1 has no chance.
+        x02 = x[(x == 0) | (x > 0.21)]
+        dataset02 = np.column_stack([x02, x02])
+        FuncData(_ki_k, dataset02, (0,), 1, rtol=_rtol).check()
+
+        dataset = np.column_stack([x, x])
+        FuncData(_kci_kc, dataset, (0,), 1, rtol=_rtol).check()
+
+
+class TestKolmogi:
+    def test_nan(self):
+        assert_(np.isnan(kolmogi(np.nan)))
+
+    def test_basic(self):
+        dataset = [(1.0, 0),
+                   (0.96394524366487511, 0.5),
+                   (0.9, 0.571173265106),
+                   (0.5000000000000000, 0.8275735551899077),
+                   (0.26999967167735456, 1),
+                   (0.00067092525577969533, 2)]
+
+        dataset = np.asarray(dataset)
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_smallpcdf(self):
+        epsilon = 0.5 ** np.arange(1, 55, 3)
+        # kolmogi(1-p) == _kolmogci(p) if  1-(1-p) == p, but not necessarily otherwise
+        # Use epsilon s.t. 1-(1-epsilon)) == epsilon,
+        # so can use same x-array for both results
+
+        x = np.array([0.8275735551899077, 0.5345255069097583, 0.4320114038786941,
+                      0.3736868442620478, 0.3345161714909591, 0.3057833329315859,
+                      0.2835052890528936, 0.2655578150208676, 0.2506869966107999,
+                      0.2380971058736669, 0.2272549289962079, 0.2177876361600040,
+                      0.2094254686862041, 0.2019676748836232, 0.1952612948137504,
+                      0.1891874239646641, 0.1836520225050326, 0.1785795904846466])
+
+        dataset = np.column_stack([1-epsilon, x])
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+
+        dataset = np.column_stack([epsilon, x])
+        FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_smallpsf(self):
+        epsilon = 0.5 ** np.arange(1, 55, 3)
+        # kolmogi(p) == _kolmogci(1-p) if  1-(1-p) == p, but not necessarily otherwise
+        # Use epsilon s.t. 1-(1-epsilon)) == epsilon,
+        # so can use same x-array for both results
+
+        x = np.array([0.8275735551899077, 1.3163786275161036, 1.6651092133663343,
+                      1.9525136345289607, 2.2027324540033235, 2.4272929437460848,
+                      2.6327688477341593, 2.8233300509220260, 3.0018183401530627,
+                      3.1702735084088891, 3.3302184446307912, 3.4828258153113318,
+                      3.6290214150152051, 3.7695513262825959, 3.9050272690877326,
+                      4.0359582187082550, 4.1627730557884890, 4.2858371743264527])
+
+        dataset = np.column_stack([epsilon, x])
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+
+        dataset = np.column_stack([1-epsilon, x])
+        FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_round_trip(self):
+        def _k_ki(_p):
+            return kolmogorov(kolmogi(_p))
+
+        p = np.linspace(0.1, 1.0, 10, endpoint=True)
+        dataset = np.column_stack([p, p])
+        FuncData(_k_ki, dataset, (0,), 1, rtol=_rtol).check()
+
+
+class TestKolmogp:
+    def test_nan(self):
+        assert_(np.isnan(_kolmogp(np.nan)))
+
+    def test_basic(self):
+        dataset = [(0.000000, -0.0),
+                   (0.200000, -1.532420541338916e-10),
+                   (0.400000, -0.1012254419260496),
+                   (0.600000, -1.324123244249925),
+                   (0.800000, -1.627024345636592),
+                   (1.000000, -1.071948558356941),
+                   (1.200000, -0.538512430720529),
+                   (1.400000, -0.2222133182429472),
+                   (1.600000, -0.07649302775520538),
+                   (1.800000, -0.02208687346347873),
+                   (2.000000, -0.005367402045629683)]
+
+        dataset = np.asarray(dataset)
+        FuncData(_kolmogp, dataset, (0,), 1, rtol=_rtol).check()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7fde685406661b821bb1dc490ca0da173eb4bd0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py
@@ -0,0 +1,109 @@
+#
+# Tests for the lambertw function,
+# Adapted from the MPMath tests [1] by Yosef Meller, mellerf@netvision.net.il
+# Distributed under the same license as SciPy itself.
+#
+# [1] mpmath source code, Subversion revision 992
+#     http://code.google.com/p/mpmath/source/browse/trunk/mpmath/tests/test_functions2.py?spec=svn994&r=992
+
+import pytest
+import numpy as np
+from numpy.testing import assert_, assert_equal, assert_array_almost_equal
+from scipy.special import lambertw
+from numpy import nan, inf, pi, e, isnan, log, r_, array, complex128
+
+from scipy.special._testutils import FuncData
+
+
+def test_values():
+    assert_(isnan(lambertw(nan)))
+    assert_equal(lambertw(inf,1).real, inf)
+    assert_equal(lambertw(inf,1).imag, 2*pi)
+    assert_equal(lambertw(-inf,1).real, inf)
+    assert_equal(lambertw(-inf,1).imag, 3*pi)
+
+    assert_equal(lambertw(1.), lambertw(1., 0))
+
+    data = [
+        (0,0, 0),
+        (0+0j,0, 0),
+        (inf,0, inf),
+        (0,-1, -inf),
+        (0,1, -inf),
+        (0,3, -inf),
+        (e,0, 1),
+        (1,0, 0.567143290409783873),
+        (-pi/2,0, 1j*pi/2),
+        (-log(2)/2,0, -log(2)),
+        (0.25,0, 0.203888354702240164),
+        (-0.25,0, -0.357402956181388903),
+        (-1./10000,0, -0.000100010001500266719),
+        (-0.25,-1, -2.15329236411034965),
+        (0.25,-1, -3.00899800997004620-4.07652978899159763j),
+        (-0.25,-1, -2.15329236411034965),
+        (0.25,1, -3.00899800997004620+4.07652978899159763j),
+        (-0.25,1, -3.48973228422959210+7.41405453009603664j),
+        (-4,0, 0.67881197132094523+1.91195078174339937j),
+        (-4,1, -0.66743107129800988+7.76827456802783084j),
+        (-4,-1, 0.67881197132094523-1.91195078174339937j),
+        (1000,0, 5.24960285240159623),
+        (1000,1, 4.91492239981054535+5.44652615979447070j),
+        (1000,-1, 4.91492239981054535-5.44652615979447070j),
+        (1000,5, 3.5010625305312892+29.9614548941181328j),
+        (3+4j,0, 1.281561806123775878+0.533095222020971071j),
+        (-0.4+0.4j,0, -0.10396515323290657+0.61899273315171632j),
+        (3+4j,1, -0.11691092896595324+5.61888039871282334j),
+        (3+4j,-1, 0.25856740686699742-3.85211668616143559j),
+        (-0.5,-1, -0.794023632344689368-0.770111750510379110j),
+        (-1./10000,1, -11.82350837248724344+6.80546081842002101j),
+        (-1./10000,-1, -11.6671145325663544),
+        (-1./10000,-2, -11.82350837248724344-6.80546081842002101j),
+        (-1./100000,4, -14.9186890769540539+26.1856750178782046j),
+        (-1./100000,5, -15.0931437726379218666+32.5525721210262290086j),
+        ((2+1j)/10,0, 0.173704503762911669+0.071781336752835511j),
+        ((2+1j)/10,1, -3.21746028349820063+4.56175438896292539j),
+        ((2+1j)/10,-1, -3.03781405002993088-3.53946629633505737j),
+        ((2+1j)/10,4, -4.6878509692773249+23.8313630697683291j),
+        (-(2+1j)/10,0, -0.226933772515757933-0.164986470020154580j),
+        (-(2+1j)/10,1, -2.43569517046110001+0.76974067544756289j),
+        (-(2+1j)/10,-1, -3.54858738151989450-6.91627921869943589j),
+        (-(2+1j)/10,4, -4.5500846928118151+20.6672982215434637j),
+        (pi,0, 1.073658194796149172092178407024821347547745350410314531),
+
+        # Former bug in generated branch,
+        (-0.5+0.002j,0, -0.78917138132659918344 + 0.76743539379990327749j),
+        (-0.5-0.002j,0, -0.78917138132659918344 - 0.76743539379990327749j),
+        (-0.448+0.4j,0, -0.11855133765652382241 + 0.66570534313583423116j),
+        (-0.448-0.4j,0, -0.11855133765652382241 - 0.66570534313583423116j),
+    ]
+    data = array(data, dtype=complex128)
+
+    def w(x, y):
+        return lambertw(x, y.real.astype(int))
+    with np.errstate(all='ignore'):
+        FuncData(w, data, (0,1), 2, rtol=1e-10, atol=1e-13).check()
+
+
+def test_ufunc():
+    assert_array_almost_equal(
+        lambertw(r_[0., e, 1.]), r_[0., 1., 0.567143290409783873])
+
+
+def test_lambertw_ufunc_loop_selection():
+    # see https://github.com/scipy/scipy/issues/4895
+    dt = np.dtype(np.complex128)
+    assert_equal(lambertw(0, 0, 0).dtype, dt)
+    assert_equal(lambertw([0], 0, 0).dtype, dt)
+    assert_equal(lambertw(0, [0], 0).dtype, dt)
+    assert_equal(lambertw(0, 0, [0]).dtype, dt)
+    assert_equal(lambertw([0], [0], [0]).dtype, dt)
+
+
+@pytest.mark.parametrize('z', [1e-316, -2e-320j, -5e-318+1e-320j])
+def test_lambertw_subnormal_k0(z):
+    # Verify that subnormal inputs are handled correctly on
+    # the branch k=0 (regression test for gh-16291).
+    w = lambertw(z)
+    # For values this small, we can be sure that numerically,
+    # lambertw(z) is z.
+    assert w == z
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..430a4175426e30bde02be7972b3144eed4923b27
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py
@@ -0,0 +1,1518 @@
+import math
+
+import numpy as np
+
+import pytest
+from numpy.testing import (assert_equal, assert_almost_equal, assert_array_almost_equal,
+    assert_allclose, suppress_warnings)
+
+from scipy import special
+from scipy.special import (legendre_p, legendre_p_all, assoc_legendre_p,
+    assoc_legendre_p_all, sph_legendre_p, sph_legendre_p_all)
+
+# The functions lpn, lpmn, clpmn, appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all, and
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn)
+# respectively. The deprecated functions listed above are implemented as
+# shims around their respective replacements. The replacements are tested
+# separately, but tests for the deprecated functions remain to verify the
+# correctness of the shims.
+
+# Base polynomials come from Abrahmowitz and Stegan
+class TestLegendre:
+    def test_legendre(self):
+        leg0 = special.legendre(0)
+        leg1 = special.legendre(1)
+        leg2 = special.legendre(2)
+        leg3 = special.legendre(3)
+        leg4 = special.legendre(4)
+        leg5 = special.legendre(5)
+        assert_equal(leg0.c, [1])
+        assert_equal(leg1.c, [1,0])
+        assert_almost_equal(leg2.c, np.array([3,0,-1])/2.0, decimal=13)
+        assert_almost_equal(leg3.c, np.array([5,0,-3,0])/2.0)
+        assert_almost_equal(leg4.c, np.array([35,0,-30,0,3])/8.0)
+        assert_almost_equal(leg5.c, np.array([63,0,-70,0,15,0])/8.0)
+
+    @pytest.mark.parametrize('n', [1, 2, 3, 4, 5])
+    @pytest.mark.parametrize('zr', [0.5241717, 12.80232, -9.699001,
+                                    0.5122437, 0.1714377])
+    @pytest.mark.parametrize('zi', [9.766818, 0.2999083, 8.24726, -22.84843,
+                                    -0.8792666])
+    def test_lpn_against_clpmn(self, n, zr, zi):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            reslpn = special.lpn(n, zr + zi*1j)
+            resclpmn = special.clpmn(0, n, zr+zi*1j)
+
+        assert_allclose(reslpn[0], resclpmn[0][0])
+        assert_allclose(reslpn[1], resclpmn[1][0])
+
+class TestLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_ode(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 100, shape)
+        x = rng.uniform(-1, 1, shape)
+
+        p, p_jac, p_hess = legendre_p(n, x, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p
+        np.testing.assert_allclose(err, 0, atol=1e-10)
+
+    @pytest.mark.parametrize("n_max", [1, 2, 4, 8, 16, 32])
+    @pytest.mark.parametrize("x_shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_all_ode(self, n_max, x_shape):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-1, 1, x_shape)
+        p, p_jac, p_hess = legendre_p_all(n_max, x, diff_n=2)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 1)))
+
+        assert p.shape == (len(n),) + x.shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p
+        np.testing.assert_allclose(err, 0, atol=1e-10)
+
+    def test_legacy(self):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            p, pd = special.lpn(2, 0.5)
+
+        assert_array_almost_equal(p, [1.00000, 0.50000, -0.12500], 4)
+        assert_array_almost_equal(pd, [0.00000, 1.00000, 1.50000], 4)
+
+class TestAssocLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    @pytest.mark.parametrize("m_max", [5, 4])
+    @pytest.mark.parametrize("n_max", [7, 10])
+    def test_lpmn(self, shape, n_max, m_max):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-0.99, 0.99, shape)
+        p_all, p_all_jac, p_all_hess = \
+            assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
+
+        x = np.expand_dims(x, axis = (0, 1))
+        p, p_jac, p_hess = assoc_legendre_p(n, m, x, diff_n=2)
+
+        np.testing.assert_allclose(p, p_all)
+        np.testing.assert_allclose(p_jac, p_all_jac)
+        np.testing.assert_allclose(p_hess, p_all_hess)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_ode(self, shape, norm):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 10, shape)
+        m = rng.integers(-10, 10, shape)
+        x = rng.uniform(-1, 1, shape)
+
+        p, p_jac, p_hess = assoc_legendre_p(n, m, x, norm=norm, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        np.testing.assert_allclose((1 - x * x) * p_hess,
+            2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
+            rtol=1e-05, atol=1e-08)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_all(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n_max = 20
+        m_max = 20
+
+        x = rng.uniform(-0.99, 0.99, shape)
+
+        p, p_jac, p_hess = assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        n = np.arange(n_max + 1)
+
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
+        m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
+        np.testing.assert_allclose((1 - x * x) * p_hess,
+            2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
+            rtol=1e-05, atol=1e-08)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_specific(self, shape, norm):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-0.99, 0.99, shape)
+
+        p, p_jac = assoc_legendre_p_all(4, 4, x, norm=norm, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            assoc_legendre_p_0_0(x, norm=norm))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            assoc_legendre_p_1_0(x, norm=norm))
+        np.testing.assert_allclose(p[1, 1],
+            assoc_legendre_p_1_1(x, norm=norm))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            assoc_legendre_p_1_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[2, 0],
+            assoc_legendre_p_2_0(x, norm=norm))
+        np.testing.assert_allclose(p[2, 1],
+            assoc_legendre_p_2_1(x, norm=norm))
+        np.testing.assert_allclose(p[2, 2],
+            assoc_legendre_p_2_2(x, norm=norm))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            assoc_legendre_p_2_m2(x, norm=norm))
+        np.testing.assert_allclose(p[2, -1],
+            assoc_legendre_p_2_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[3, 0],
+            assoc_legendre_p_3_0(x, norm=norm))
+        np.testing.assert_allclose(p[3, 1],
+            assoc_legendre_p_3_1(x, norm=norm))
+        np.testing.assert_allclose(p[3, 2],
+            assoc_legendre_p_3_2(x, norm=norm))
+        np.testing.assert_allclose(p[3, 3],
+            assoc_legendre_p_3_3(x, norm=norm))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            assoc_legendre_p_3_m3(x, norm=norm))
+        np.testing.assert_allclose(p[3, -2],
+            assoc_legendre_p_3_m2(x, norm=norm))
+        np.testing.assert_allclose(p[3, -1],
+            assoc_legendre_p_3_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[4, 0],
+            assoc_legendre_p_4_0(x, norm=norm))
+        np.testing.assert_allclose(p[4, 1],
+            assoc_legendre_p_4_1(x, norm=norm))
+        np.testing.assert_allclose(p[4, 2],
+            assoc_legendre_p_4_2(x, norm=norm))
+        np.testing.assert_allclose(p[4, 3],
+            assoc_legendre_p_4_3(x, norm=norm))
+        np.testing.assert_allclose(p[4, 4],
+            assoc_legendre_p_4_4(x, norm=norm))
+        np.testing.assert_allclose(p[4, -4],
+            assoc_legendre_p_4_m4(x, norm=norm))
+        np.testing.assert_allclose(p[4, -3],
+            assoc_legendre_p_4_m3(x, norm=norm))
+        np.testing.assert_allclose(p[4, -2],
+            assoc_legendre_p_4_m2(x, norm=norm))
+        np.testing.assert_allclose(p[4, -1],
+            assoc_legendre_p_4_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            assoc_legendre_p_0_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            assoc_legendre_p_1_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 1],
+            assoc_legendre_p_1_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            assoc_legendre_p_1_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            assoc_legendre_p_2_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 1],
+            assoc_legendre_p_2_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 2],
+            assoc_legendre_p_2_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            assoc_legendre_p_2_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, -1],
+            assoc_legendre_p_2_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            assoc_legendre_p_3_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 1],
+            assoc_legendre_p_3_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 2],
+            assoc_legendre_p_3_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 3],
+            assoc_legendre_p_3_3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            assoc_legendre_p_3_m3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -2],
+            assoc_legendre_p_3_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -1],
+            assoc_legendre_p_3_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            assoc_legendre_p_4_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 1],
+            assoc_legendre_p_4_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 2],
+            assoc_legendre_p_4_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 3],
+            assoc_legendre_p_4_3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 4],
+            assoc_legendre_p_4_4_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -4],
+            assoc_legendre_p_4_m4_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -3],
+            assoc_legendre_p_4_m3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -2],
+            assoc_legendre_p_4_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -1],
+            assoc_legendre_p_4_m1_jac(x, norm=norm))
+
+    @pytest.mark.parametrize("m_max", [7])
+    @pytest.mark.parametrize("n_max", [10])
+    @pytest.mark.parametrize("x", [1, -1])
+    def test_all_limits(self, m_max, n_max, x):
+        p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
+
+        n = np.arange(n_max + 1)
+
+        np.testing.assert_allclose(p_jac[:, 0],
+            pow(x, n + 1) * n * (n + 1) / 2)
+        np.testing.assert_allclose(p_jac[:, 1],
+            np.where(n >= 1, pow(x, n) * np.inf, 0))
+        np.testing.assert_allclose(p_jac[:, 2],
+            np.where(n >= 2, -pow(x, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[:, -2],
+            np.where(n >= 2, -pow(x, n + 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[:, -1],
+            np.where(n >= 1, -pow(x, n) * np.inf, 0))
+
+        for m in range(3, m_max + 1):
+            np.testing.assert_allclose(p_jac[:, m], 0)
+            np.testing.assert_allclose(p_jac[:, -m], 0)
+
+    @pytest.mark.parametrize("m_max", [3, 5, 10])
+    @pytest.mark.parametrize("n_max", [10])
+    def test_legacy(self, m_max, n_max):
+        x = 0.5
+        p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+
+            p_legacy, p_jac_legacy = special.lpmn(m_max, n_max, x)
+            for m in range(m_max + 1):
+                np.testing.assert_allclose(p_legacy[m], p[:, m])
+
+            p_legacy, p_jac_legacy = special.lpmn(-m_max, n_max, x)
+            for m in range(m_max + 1):
+                np.testing.assert_allclose(p_legacy[m], p[:, -m])
+
+class TestMultiAssocLegendreP:
+    @pytest.mark.parametrize("shape", [(1000,), (4, 9), (3, 5, 7)])
+    @pytest.mark.parametrize("branch_cut", [2, 3])
+    @pytest.mark.parametrize("z_min, z_max", [(-10 - 10j, 10 + 10j),
+        (-1, 1), (-10j, 10j)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_specific(self, shape, branch_cut, z_min, z_max, norm):
+        rng = np.random.default_rng(1234)
+
+        z = rng.uniform(z_min.real, z_max.real, shape) + \
+            1j * rng.uniform(z_min.imag, z_max.imag, shape)
+
+        p, p_jac = assoc_legendre_p_all(4, 4,
+            z, branch_cut=branch_cut, norm=norm, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            assoc_legendre_p_0_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            assoc_legendre_p_1_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[1, 1],
+            assoc_legendre_p_1_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            assoc_legendre_p_1_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[2, 0],
+            assoc_legendre_p_2_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 1],
+            assoc_legendre_p_2_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 2],
+            assoc_legendre_p_2_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            assoc_legendre_p_2_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, -1],
+            assoc_legendre_p_2_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[3, 0],
+            assoc_legendre_p_3_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 1],
+            assoc_legendre_p_3_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 2],
+            assoc_legendre_p_3_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 3],
+            assoc_legendre_p_3_3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            assoc_legendre_p_3_m3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, -2],
+            assoc_legendre_p_3_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, -1],
+            assoc_legendre_p_3_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[4, 0],
+            assoc_legendre_p_4_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 1],
+            assoc_legendre_p_4_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 2],
+            assoc_legendre_p_4_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 3],
+            assoc_legendre_p_4_3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 4],
+            assoc_legendre_p_4_4(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -4],
+            assoc_legendre_p_4_m4(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -3],
+            assoc_legendre_p_4_m3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -2],
+            assoc_legendre_p_4_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -1],
+            assoc_legendre_p_4_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            assoc_legendre_p_0_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            assoc_legendre_p_1_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 1],
+            assoc_legendre_p_1_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            assoc_legendre_p_1_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            assoc_legendre_p_2_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 1],
+            assoc_legendre_p_2_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 2],
+            assoc_legendre_p_2_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            assoc_legendre_p_2_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, -1],
+            assoc_legendre_p_2_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            assoc_legendre_p_3_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 1],
+            assoc_legendre_p_3_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 2],
+            assoc_legendre_p_3_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 3],
+            assoc_legendre_p_3_3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            assoc_legendre_p_3_m3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -2],
+            assoc_legendre_p_3_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -1],
+            assoc_legendre_p_3_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            assoc_legendre_p_4_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 1],
+            assoc_legendre_p_4_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 2],
+            assoc_legendre_p_4_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 3],
+            assoc_legendre_p_4_3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 4],
+            assoc_legendre_p_4_4_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -4],
+            assoc_legendre_p_4_m4_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -3],
+            assoc_legendre_p_4_m3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -2],
+            assoc_legendre_p_4_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -1],
+            assoc_legendre_p_4_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+class TestSphLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_specific(self, shape):
+        rng = np.random.default_rng(1234)
+
+        theta = rng.uniform(-np.pi, np.pi, shape)
+
+        p, p_jac = sph_legendre_p_all(4, 4, theta, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            sph_legendre_p_0_0(theta))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            sph_legendre_p_1_0(theta))
+        np.testing.assert_allclose(p[1, 1],
+            sph_legendre_p_1_1(theta))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            sph_legendre_p_1_m1(theta))
+
+        np.testing.assert_allclose(p[2, 0],
+            sph_legendre_p_2_0(theta))
+        np.testing.assert_allclose(p[2, 1],
+            sph_legendre_p_2_1(theta))
+        np.testing.assert_allclose(p[2, 2],
+            sph_legendre_p_2_2(theta))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            sph_legendre_p_2_m2(theta))
+        np.testing.assert_allclose(p[2, -1],
+            sph_legendre_p_2_m1(theta))
+
+        np.testing.assert_allclose(p[3, 0],
+            sph_legendre_p_3_0(theta))
+        np.testing.assert_allclose(p[3, 1],
+            sph_legendre_p_3_1(theta))
+        np.testing.assert_allclose(p[3, 2],
+            sph_legendre_p_3_2(theta))
+        np.testing.assert_allclose(p[3, 3],
+            sph_legendre_p_3_3(theta))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            sph_legendre_p_3_m3(theta))
+        np.testing.assert_allclose(p[3, -2],
+            sph_legendre_p_3_m2(theta))
+        np.testing.assert_allclose(p[3, -1],
+            sph_legendre_p_3_m1(theta))
+
+        np.testing.assert_allclose(p[4, 0],
+            sph_legendre_p_4_0(theta))
+        np.testing.assert_allclose(p[4, 1],
+            sph_legendre_p_4_1(theta))
+        np.testing.assert_allclose(p[4, 2],
+            sph_legendre_p_4_2(theta))
+        np.testing.assert_allclose(p[4, 3],
+            sph_legendre_p_4_3(theta))
+        np.testing.assert_allclose(p[4, 4],
+            sph_legendre_p_4_4(theta))
+        np.testing.assert_allclose(p[4, -4],
+            sph_legendre_p_4_m4(theta))
+        np.testing.assert_allclose(p[4, -3],
+            sph_legendre_p_4_m3(theta))
+        np.testing.assert_allclose(p[4, -2],
+            sph_legendre_p_4_m2(theta))
+        np.testing.assert_allclose(p[4, -1],
+            sph_legendre_p_4_m1(theta))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            sph_legendre_p_0_0_jac(theta))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            sph_legendre_p_1_0_jac(theta))
+        np.testing.assert_allclose(p_jac[1, 1],
+            sph_legendre_p_1_1_jac(theta))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            sph_legendre_p_1_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            sph_legendre_p_2_0_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 1],
+            sph_legendre_p_2_1_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 2],
+            sph_legendre_p_2_2_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            sph_legendre_p_2_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[2, -1],
+            sph_legendre_p_2_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            sph_legendre_p_3_0_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 1],
+            sph_legendre_p_3_1_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 2],
+            sph_legendre_p_3_2_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 3],
+            sph_legendre_p_3_3_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            sph_legendre_p_3_m3_jac(theta))
+        np.testing.assert_allclose(p_jac[3, -2],
+            sph_legendre_p_3_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[3, -1],
+            sph_legendre_p_3_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            sph_legendre_p_4_0_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 1],
+            sph_legendre_p_4_1_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 2],
+            sph_legendre_p_4_2_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 3],
+            sph_legendre_p_4_3_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 4],
+            sph_legendre_p_4_4_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -4],
+            sph_legendre_p_4_m4_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -3],
+            sph_legendre_p_4_m3_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -2],
+            sph_legendre_p_4_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -1],
+            sph_legendre_p_4_m1_jac(theta))
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    def test_ode(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 10, shape)
+        m = rng.integers(-10, 10, shape)
+        theta = rng.uniform(-np.pi, np.pi, shape)
+
+        p, p_jac, p_hess = sph_legendre_p(n, m, theta, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        np.testing.assert_allclose(np.sin(theta) * p_hess, -np.cos(theta) * p_jac
+            - (n * (n + 1) * np.sin(theta) - m * m / np.sin(theta)) * p,
+            rtol=1e-05, atol=1e-08)
+
+class TestLegendreFunctions:
+    def test_clpmn(self):
+        z = 0.5+0.3j
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp = special.clpmn(2, 2, z, 3)
+
+        assert_array_almost_equal(clp,
+                   (np.array([[1.0000, z, 0.5*(3*z*z-1)],
+                           [0.0000, np.sqrt(z*z-1), 3*z*np.sqrt(z*z-1)],
+                           [0.0000, 0.0000, 3*(z*z-1)]]),
+                    np.array([[0.0000, 1.0000, 3*z],
+                           [0.0000, z/np.sqrt(z*z-1), 3*(2*z*z-1)/np.sqrt(z*z-1)],
+                           [0.0000, 0.0000, 6*z]])),
+                    7)
+
+    def test_clpmn_close_to_real_2(self):
+        eps = 1e-10
+        m = 1
+        n = 3
+        x = 0.5
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n]
+            clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n]
+
+        assert_array_almost_equal(np.array([clp_plus, clp_minus]),
+                                  np.array([special.lpmv(m, n, x),
+                                         special.lpmv(m, n, x)]),
+                                  7)
+
+    def test_clpmn_close_to_real_3(self):
+        eps = 1e-10
+        m = 1
+        n = 3
+        x = 0.5
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n]
+            clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n]
+
+        assert_array_almost_equal(np.array([clp_plus, clp_minus]),
+                                  np.array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi),
+                                         special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]),
+                                  7)
+
+    def test_clpmn_across_unit_circle(self):
+        eps = 1e-7
+        m = 1
+        n = 1
+        x = 1j
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for type in [2, 3]:
+                assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n],
+                                special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6)
+
+    def test_inf(self):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for z in (1, -1):
+                for n in range(4):
+                    for m in range(1, n):
+                        lp = special.clpmn(m, n, z)
+                        assert np.isinf(lp[1][1,1:]).all()
+                        lp = special.lpmn(m, n, z)
+                        assert np.isinf(lp[1][1,1:]).all()
+
+    def test_deriv_clpmn(self):
+        # data inside and outside of the unit circle
+        zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j,
+                 1+1j, -1+1j, -1-1j, 1-1j]
+        m = 2
+        n = 3
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for type in [2, 3]:
+                for z in zvals:
+                    for h in [1e-3, 1e-3j]:
+                        approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0]
+                                            - special.clpmn(m, n, z-0.5*h, type)[0])/h
+                        assert_allclose(special.clpmn(m, n, z, type)[1],
+                                        approx_derivative,
+                                        rtol=1e-4)
+
+    """
+    @pytest.mark.parametrize("m_max", [3])
+    @pytest.mark.parametrize("n_max", [5])
+    @pytest.mark.parametrize("z", [-1])
+    def test_clpmn_all_limits(self, m_max, n_max, z):
+        rng = np.random.default_rng(1234)
+
+        type = 2
+
+        p, p_jac = special.clpmn_all(m_max, n_max, type, z, diff_n=1)
+
+        n = np.arange(n_max + 1)
+
+        np.testing.assert_allclose(p_jac[0], pow(z, n + 1) * n * (n + 1) / 2)
+        np.testing.assert_allclose(p_jac[1], np.where(n >= 1, pow(z, n) * np.inf, 0))
+        np.testing.assert_allclose(p_jac[2], np.where(n >= 2,
+            -pow(z, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[-2], np.where(n >= 2, -pow(z, n + 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[-1], np.where(n >= 1, -pow(z, n) * np.inf, 0))
+
+        for m in range(3, m_max + 1):
+            np.testing.assert_allclose(p_jac[m], 0)
+            np.testing.assert_allclose(p_jac[-m], 0)
+    """
+
+    def test_lpmv(self):
+        lp = special.lpmv(0,2,.5)
+        assert_almost_equal(lp,-0.125,7)
+        lp = special.lpmv(0,40,.001)
+        assert_almost_equal(lp,0.1252678976534484,7)
+
+        # XXX: this is outside the domain of the current implementation,
+        #      so ensure it returns a NaN rather than a wrong answer.
+        with np.errstate(all='ignore'):
+            lp = special.lpmv(-1,-1,.001)
+        assert lp != 0 or np.isnan(lp)
+
+    def test_lqmn(self):
+        lqmnf = special.lqmn(0,2,.5)
+        lqf = special.lqn(2,.5)
+        assert_array_almost_equal(lqmnf[0][0],lqf[0],4)
+        assert_array_almost_equal(lqmnf[1][0],lqf[1],4)
+
+    def test_lqmn_gt1(self):
+        """algorithm for real arguments changes at 1.0001
+           test against analytical result for m=2, n=1
+        """
+        x0 = 1.0001
+        delta = 0.00002
+        for x in (x0-delta, x0+delta):
+            lq = special.lqmn(2, 1, x)[0][-1, -1]
+            expected = 2/(x*x-1)
+            assert_almost_equal(lq, expected)
+
+    def test_lqmn_shape(self):
+        a, b = special.lqmn(4, 4, 1.1)
+        assert_equal(a.shape, (5, 5))
+        assert_equal(b.shape, (5, 5))
+
+        a, b = special.lqmn(4, 0, 1.1)
+        assert_equal(a.shape, (5, 1))
+        assert_equal(b.shape, (5, 1))
+
+    def test_lqn(self):
+        lqf = special.lqn(2,.5)
+        assert_array_almost_equal(lqf,(np.array([0.5493, -0.7253, -0.8187]),
+                                       np.array([1.3333, 1.216, -0.8427])),4)
+
+    @pytest.mark.parametrize("function", [special.lpn, special.lqn])
+    @pytest.mark.parametrize("n", [1, 2, 4, 8, 16, 32])
+    @pytest.mark.parametrize("z_complex", [False, True])
+    @pytest.mark.parametrize("z_inexact", [False, True])
+    @pytest.mark.parametrize(
+        "input_shape",
+        [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1), (2, 2, 2)
+        ]
+    )
+    def test_array_inputs_lxn(self, function, n, z_complex, z_inexact, input_shape):
+        """Tests for correct output shapes."""
+        rng = np.random.default_rng(1234)
+        if z_inexact:
+            z = rng.integers(-3, 3, size=input_shape)
+        else:
+            z = rng.uniform(-1, 1, size=input_shape)
+
+        if z_complex:
+            z = 1j * z + 0.5j * z
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            P_z, P_d_z = function(n, z)
+        assert P_z.shape == (n + 1, ) + input_shape
+        assert P_d_z.shape == (n + 1, ) + input_shape
+
+    @pytest.mark.parametrize("function", [special.lqmn])
+    @pytest.mark.parametrize(
+        "m,n",
+        [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)]
+    )
+    @pytest.mark.parametrize("z_inexact", [False, True])
+    @pytest.mark.parametrize(
+        "input_shape", [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1)
+        ]
+    )
+    def test_array_inputs_lxmn(self, function, m, n, z_inexact, input_shape):
+        """Tests for correct output shapes and dtypes."""
+        rng = np.random.default_rng(1234)
+        if z_inexact:
+            z = rng.integers(-3, 3, size=input_shape)
+        else:
+            z = rng.uniform(-1, 1, size=input_shape)
+
+        P_z, P_d_z = function(m, n, z)
+        assert P_z.shape == (m + 1, n + 1) + input_shape
+        assert P_d_z.shape == (m + 1, n + 1) + input_shape
+
+    @pytest.mark.parametrize("function", [special.clpmn, special.lqmn])
+    @pytest.mark.parametrize(
+        "m,n",
+        [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)]
+    )
+    @pytest.mark.parametrize(
+        "input_shape", [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1)
+        ]
+    )
+    def test_array_inputs_clxmn(self, function, m, n, input_shape):
+        """Tests for correct output shapes and dtypes."""
+        rng = np.random.default_rng(1234)
+        z = rng.uniform(-1, 1, size=input_shape)
+        z = 1j * z + 0.5j * z
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            P_z, P_d_z = function(m, n, z)
+
+        assert P_z.shape == (m + 1, n + 1) + input_shape
+        assert P_d_z.shape == (m + 1, n + 1) + input_shape
+
+def assoc_legendre_factor(n, m, norm):
+    if norm:
+        return (math.sqrt((2 * n + 1) *
+            math.factorial(n - m) / (2 * math.factorial(n + m))))
+
+    return 1
+
+def assoc_legendre_p_0_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(0, 0, norm)
+
+    return np.full_like(z, fac)
+
+def assoc_legendre_p_1_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 0, norm)
+
+    return fac * z
+
+def assoc_legendre_p_1_1(z, *, branch_cut=2, norm=False):
+    branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1)
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, 1, norm)
+
+    w = np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z))
+
+    return branch_cut_sign * branch_sign * fac * w
+
+def assoc_legendre_p_1_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, -1, norm)
+
+    return (-branch_cut_sign * fac *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 0, norm)
+
+    return fac * (3 * z * z - 1) / 2
+
+def assoc_legendre_p_2_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 1, norm)
+
+    return (3 * fac * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_2_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, 2, norm)
+
+    return 3 * branch_cut_sign * fac * (1 - z * z)
+
+def assoc_legendre_p_2_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -2, norm)
+
+    return branch_cut_sign * fac * (1 - z * z) / 8
+
+def assoc_legendre_p_2_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -1, norm)
+
+    return (-branch_cut_sign * fac * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 0, norm)
+
+    return fac * (5 * z * z - 3) * z / 2
+
+def assoc_legendre_p_3_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 1, norm)
+
+    return (3 * fac * (5 * z * z - 1) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 2, norm)
+
+    return 15 * branch_cut_sign * fac * (1 - z * z) * z
+
+def assoc_legendre_p_3_3(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 3, norm)
+
+    return (15 * branch_cut_sign * fac * (1 - z * z) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_3_m3(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, -3, norm)
+
+    return (fac * (z * z - 1) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_3_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -2, norm)
+
+    return branch_cut_sign * fac * (1 - z * z) * z / 8
+
+def assoc_legendre_p_3_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -1, norm)
+
+    return (branch_cut_sign * fac * (1 - 5 * z * z) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_4_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 0, norm)
+
+    return fac * ((35 * z * z - 30) * z * z + 3) / 8
+
+def assoc_legendre_p_4_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 1, norm)
+
+    return (5 * fac * (7 * z * z - 3) * z *
+       assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_4_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 2, norm)
+
+    return 15 * branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 2
+
+def assoc_legendre_p_4_3(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 3, norm)
+
+    return (105 * branch_cut_sign * fac * (1 - z * z) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_4_4(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 4, norm)
+
+    return 105 * fac * np.square(z * z - 1)
+
+def assoc_legendre_p_4_m4(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -4, norm)
+
+    return fac * np.square(z * z - 1) / 384
+
+def assoc_legendre_p_4_m3(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -3, norm)
+
+    return (fac * (z * z - 1) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_4_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -2, norm)
+
+    return branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 48
+
+def assoc_legendre_p_4_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -1, norm)
+
+    return (branch_cut_sign * fac * (3 - 7 * z * z) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_1_1_jac_div_z(z, branch_cut=2):
+    branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1)
+
+    out11_div_z = (-branch_sign /
+        np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z)))
+
+    return out11_div_z
+
+def assoc_legendre_p_0_0_jac(z, *, branch_cut=2, norm=False):
+    return np.zeros_like(z)
+
+def assoc_legendre_p_1_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 0, norm)
+
+    return np.full_like(z, fac)
+
+def assoc_legendre_p_1_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 1, norm)
+
+    return (fac * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_1_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, -1, norm)
+
+    return (-branch_cut_sign * fac * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 0, norm)
+
+    return 3 * fac * z
+
+def assoc_legendre_p_2_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 1, norm)
+
+    return (3 * fac * (2 * z * z - 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_2_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, 2, norm)
+
+    return -6 * branch_cut_sign * fac * z
+
+def assoc_legendre_p_2_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -1, norm)
+
+    return (branch_cut_sign * fac * (1 - 2 * z * z) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -2, norm)
+
+    return -branch_cut_sign * fac * z / 4
+
+def assoc_legendre_p_3_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 0, norm)
+
+    return 3 * fac * (5 * z * z - 1) / 2
+
+def assoc_legendre_p_3_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 1, norm)
+
+    return (3 * fac * (15 * z * z - 11) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 2, norm)
+
+    return 15 * branch_cut_sign * fac * (1 - 3 * z * z)
+
+def assoc_legendre_p_3_3_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 3, norm)
+
+    return (45 * branch_cut_sign * fac * (1 - z * z) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_3_m3_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, -3, norm)
+
+    return (fac * (z * z - 1) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 16)
+
+def assoc_legendre_p_3_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -2, norm)
+
+    return branch_cut_sign * fac * (1 - 3 * z * z) / 8
+
+def assoc_legendre_p_3_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -1, norm)
+
+    return (branch_cut_sign * fac * (11 - 15 * z * z) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_4_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 0, norm)
+
+    return 5 * fac * (7 * z * z - 3) * z / 2
+
+def assoc_legendre_p_4_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 1, norm)
+
+    return (5 * fac * ((28 * z * z - 27) * z * z + 3) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_4_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 2, norm)
+
+    return 30 * branch_cut_sign * fac * (4 - 7 * z * z) * z
+
+def assoc_legendre_p_4_3_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 3, norm)
+
+    return (105 * branch_cut_sign * fac * ((5 - 4 * z * z) * z * z - 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_4_4_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 4, norm)
+
+    return 420 * fac * (z * z - 1) * z
+
+def assoc_legendre_p_4_m4_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -4, norm)
+
+    return fac * (z * z - 1) * z / 96
+
+def assoc_legendre_p_4_m3_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -3, norm)
+
+    return (fac * ((4 * z * z - 5) * z * z + 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_4_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -2, norm)
+
+    return branch_cut_sign * fac * (4 - 7 * z * z) * z / 12
+
+def assoc_legendre_p_4_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -1, norm)
+
+    return (branch_cut_sign * fac * ((27 - 28 * z * z) * z * z - 3) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8)
+
+def sph_legendre_factor(n, m):
+    return assoc_legendre_factor(n, m, norm=True) / np.sqrt(2 * np.pi)
+
+def sph_legendre_p_0_0(theta):
+    fac = sph_legendre_factor(0, 0)
+
+    return np.full_like(theta, fac)
+
+def sph_legendre_p_1_0(theta):
+    fac = sph_legendre_factor(1, 0)
+
+    return fac * np.cos(theta)
+
+def sph_legendre_p_1_1(theta):
+    fac = sph_legendre_factor(1, 1)
+
+    return -fac * np.abs(np.sin(theta))
+
+def sph_legendre_p_1_m1(theta):
+    fac = sph_legendre_factor(1, -1)
+
+    return fac * np.abs(np.sin(theta)) / 2
+
+def sph_legendre_p_2_0(theta):
+    fac = sph_legendre_factor(2, 0)
+
+    return fac * (3 * np.square(np.cos(theta)) - 1) / 2
+
+def sph_legendre_p_2_1(theta):
+    fac = sph_legendre_factor(2, 1)
+
+    return -3 * fac * np.abs(np.sin(theta)) * np.cos(theta)
+
+def sph_legendre_p_2_2(theta):
+    fac = sph_legendre_factor(2, 2)
+
+    return 3 * fac * (1 - np.square(np.cos(theta)))
+
+def sph_legendre_p_2_m2(theta):
+    fac = sph_legendre_factor(2, -2)
+
+    return fac * (1 - np.square(np.cos(theta))) / 8
+
+def sph_legendre_p_2_m1(theta):
+    fac = sph_legendre_factor(2, -1)
+
+    return fac * np.cos(theta) * np.abs(np.sin(theta)) / 2
+
+def sph_legendre_p_3_0(theta):
+    fac = sph_legendre_factor(3, 0)
+
+    return (fac * (5 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) / 2)
+
+def sph_legendre_p_3_1(theta):
+    fac = sph_legendre_factor(3, 1)
+
+    return (-3 * fac * (5 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) / 2)
+
+def sph_legendre_p_3_2(theta):
+    fac = sph_legendre_factor(3, 2)
+
+    return (-15 * fac * (np.square(np.cos(theta)) - 1) *
+        np.cos(theta))
+
+def sph_legendre_p_3_3(theta):
+    fac = sph_legendre_factor(3, 3)
+
+    return -15 * fac * np.power(np.abs(np.sin(theta)), 3)
+
+def sph_legendre_p_3_m3(theta):
+    fac = sph_legendre_factor(3, -3)
+
+    return fac * np.power(np.abs(np.sin(theta)), 3) / 48
+
+def sph_legendre_p_3_m2(theta):
+    fac = sph_legendre_factor(3, -2)
+
+    return (-fac * (np.square(np.cos(theta)) - 1) *
+        np.cos(theta) / 8)
+
+def sph_legendre_p_3_m1(theta):
+    fac = sph_legendre_factor(3, -1)
+
+    return (fac * (5 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) / 8)
+
+def sph_legendre_p_4_0(theta):
+    fac = sph_legendre_factor(4, 0)
+
+    return (fac * (35 * np.square(np.square(np.cos(theta))) -
+        30 * np.square(np.cos(theta)) + 3) / 8)
+
+def sph_legendre_p_4_1(theta):
+    fac = sph_legendre_factor(4, 1)
+
+    return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) * np.abs(np.sin(theta)) / 2)
+
+def sph_legendre_p_4_2(theta):
+    fac = sph_legendre_factor(4, 2)
+
+    return (-15 * fac * (7 * np.square(np.cos(theta)) - 1) *
+        (np.square(np.cos(theta)) - 1) / 2)
+
+def sph_legendre_p_4_3(theta):
+    fac = sph_legendre_factor(4, 3)
+
+    return -105 * fac * np.power(np.abs(np.sin(theta)), 3) * np.cos(theta)
+
+def sph_legendre_p_4_4(theta):
+    fac = sph_legendre_factor(4, 4)
+
+    return 105 * fac * np.square(np.square(np.cos(theta)) - 1)
+
+def sph_legendre_p_4_m4(theta):
+    fac = sph_legendre_factor(4, -4)
+
+    return fac * np.square(np.square(np.cos(theta)) - 1) / 384
+
+def sph_legendre_p_4_m3(theta):
+    fac = sph_legendre_factor(4, -3)
+
+    return (fac * np.power(np.abs(np.sin(theta)), 3) *
+        np.cos(theta) / 48)
+
+def sph_legendre_p_4_m2(theta):
+    fac = sph_legendre_factor(4, -2)
+
+    return (-fac * (7 * np.square(np.cos(theta)) - 1) *
+        (np.square(np.cos(theta)) - 1) / 48)
+
+def sph_legendre_p_4_m1(theta):
+    fac = sph_legendre_factor(4, -1)
+
+    return (fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) * np.abs(np.sin(theta)) / 8)
+
+def sph_legendre_p_0_0_jac(theta):
+    return np.zeros_like(theta)
+
+def sph_legendre_p_1_0_jac(theta):
+    fac = sph_legendre_factor(1, 0)
+
+    return -fac * np.sin(theta)
+
+def sph_legendre_p_1_1_jac(theta):
+    fac = sph_legendre_factor(1, 1)
+
+    return -fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1)
+
+def sph_legendre_p_1_m1_jac(theta):
+    fac = sph_legendre_factor(1, -1)
+
+    return fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1) / 2
+
+def sph_legendre_p_2_0_jac(theta):
+    fac = sph_legendre_factor(2, 0)
+
+    return -3 * fac * np.cos(theta) * np.sin(theta)
+
+def sph_legendre_p_2_1_jac(theta):
+    fac = sph_legendre_factor(2, 1)
+
+    return (3 * fac * (-np.square(np.cos(theta)) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) +
+        np.abs(np.sin(theta)) * np.sin(theta)))
+
+def sph_legendre_p_2_2_jac(theta):
+    fac = sph_legendre_factor(2, 2)
+
+    return 6 * fac * np.sin(theta) * np.cos(theta)
+
+def sph_legendre_p_2_m2_jac(theta):
+    fac = sph_legendre_factor(2, -2)
+
+    return fac * np.sin(theta) * np.cos(theta) / 4
+
+def sph_legendre_p_2_m1_jac(theta):
+    fac = sph_legendre_factor(2, -1)
+
+    return (-fac * (-np.square(np.cos(theta)) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) +
+        np.abs(np.sin(theta)) * np.sin(theta)) / 2)
+
+def sph_legendre_p_3_0_jac(theta):
+    fac = sph_legendre_factor(3, 0)
+
+    return 3 * fac * (1 - 5 * np.square(np.cos(theta))) * np.sin(theta) / 2
+
+def sph_legendre_p_3_1_jac(theta):
+    fac = sph_legendre_factor(3, 1)
+
+    return (3 * fac * (11 - 15 * np.square(np.cos(theta))) * np.cos(theta) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 2)
+
+def sph_legendre_p_3_2_jac(theta):
+    fac = sph_legendre_factor(3, 2)
+
+    return 15 * fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta)
+
+def sph_legendre_p_3_3_jac(theta):
+    fac = sph_legendre_factor(3, 3)
+
+    return -45 * fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta)
+
+def sph_legendre_p_3_m3_jac(theta):
+    fac = sph_legendre_factor(3, -3)
+
+    return fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta) / 16
+
+def sph_legendre_p_3_m2_jac(theta):
+    fac = sph_legendre_factor(3, -2)
+
+    return fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta) / 8
+
+def sph_legendre_p_3_m1_jac(theta):
+    fac = sph_legendre_factor(3, -1)
+
+    return (-fac * (11 - 15 * np.square(np.cos(theta))) *
+        np.cos(theta) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 8)
+
+def sph_legendre_p_4_0_jac(theta):
+    fac = sph_legendre_factor(4, 0)
+
+    return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.sin(theta) * np.cos(theta) / 2)
+
+def sph_legendre_p_4_1_jac(theta):
+    fac = sph_legendre_factor(4, 1)
+
+    return (5 * fac * (-3 + 27 * np.square(np.cos(theta)) -
+        28 * np.square(np.square(np.cos(theta)))) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 2)
+
+def sph_legendre_p_4_2_jac(theta):
+    fac = sph_legendre_factor(4, 2)
+
+    return (30 * fac * (7 * np.square(np.cos(theta)) - 4) *
+        np.sin(theta) * np.cos(theta))
+
+def sph_legendre_p_4_3_jac(theta):
+    fac = sph_legendre_factor(4, 3)
+
+    return (-105 * fac * (4 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) * np.sin(theta))
+
+def sph_legendre_p_4_4_jac(theta):
+    fac = sph_legendre_factor(4, 4)
+
+    return (-420 * fac * (np.square(np.cos(theta)) - 1) *
+        np.sin(theta) * np.cos(theta))
+
+def sph_legendre_p_4_m4_jac(theta):
+    fac = sph_legendre_factor(4, -4)
+
+    return (-fac * (np.square(np.cos(theta)) - 1) *
+        np.sin(theta) * np.cos(theta) / 96)
+
+def sph_legendre_p_4_m3_jac(theta):
+    fac = sph_legendre_factor(4, -3)
+
+    return (fac * (4 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) * np.sin(theta) / 48)
+
+def sph_legendre_p_4_m2_jac(theta):
+    fac = sph_legendre_factor(4, -2)
+
+    return (fac * (7 * np.square(np.cos(theta)) - 4) * np.sin(theta) *
+        np.cos(theta) / 12)
+
+def sph_legendre_p_4_m1_jac(theta):
+    fac = sph_legendre_factor(4, -1)
+
+    return (-fac * (-3 + 27 * np.square(np.cos(theta)) -
+        28 * np.square(np.square(np.cos(theta)))) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 8)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3a5071fc671d8d4a7ef6c7655ca4212ced4f45
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py
@@ -0,0 +1,109 @@
+import numpy as np
+from numpy.testing import assert_allclose
+
+import pytest
+
+import scipy.special as sc
+
+
+@pytest.mark.parametrize('x, expected', [
+    (np.array([1000, 1]), np.array([0, -999])),
+
+    # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+    # converted to float.
+    (np.arange(4), np.array([-3.4401896985611953,
+                             -2.4401896985611953,
+                             -1.4401896985611953,
+                             -0.44018969856119533]))
+])
+def test_log_softmax(x, expected):
+    assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
+
+
+@pytest.fixture
+def log_softmax_x():
+    x = np.arange(4)
+    return x
+
+
+@pytest.fixture
+def log_softmax_expected():
+    # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+    # converted to float.
+    expected = np.array([-3.4401896985611953,
+                         -2.4401896985611953,
+                         -1.4401896985611953,
+                         -0.44018969856119533])
+    return expected
+
+
+def test_log_softmax_translation(log_softmax_x, log_softmax_expected):
+    # Translation property.  If all the values are changed by the same amount,
+    # the softmax result does not change.
+    x = log_softmax_x + 100
+    expected = log_softmax_expected
+    assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
+
+
+def test_log_softmax_noneaxis(log_softmax_x, log_softmax_expected):
+    # When axis=None, softmax operates on the entire array, and preserves
+    # the shape.
+    x = log_softmax_x.reshape(2, 2)
+    expected = log_softmax_expected.reshape(2, 2)
+    assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
+
+
+@pytest.mark.parametrize('axis_2d, expected_2d', [
+    (0, np.log(0.5) * np.ones((2, 2))),
+    (1, np.array([[0, -999], [0, -999]]))
+])
+def test_axes(axis_2d, expected_2d):
+    assert_allclose(
+        sc.log_softmax([[1000, 1], [1000, 1]], axis=axis_2d),
+        expected_2d,
+        rtol=1e-13,
+    )
+
+
+@pytest.fixture
+def log_softmax_2d_x():
+    x = np.arange(8).reshape(2, 4)
+    return x
+
+
+@pytest.fixture
+def log_softmax_2d_expected():
+    # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+    # converted to float.
+    expected = np.array([[-3.4401896985611953,
+                         -2.4401896985611953,
+                         -1.4401896985611953,
+                         -0.44018969856119533],
+                        [-3.4401896985611953,
+                         -2.4401896985611953,
+                         -1.4401896985611953,
+                         -0.44018969856119533]])
+    return expected
+
+
+def test_log_softmax_2d_axis1(log_softmax_2d_x, log_softmax_2d_expected):
+    x = log_softmax_2d_x
+    expected = log_softmax_2d_expected
+    assert_allclose(sc.log_softmax(x, axis=1), expected, rtol=1e-13)
+
+
+def test_log_softmax_2d_axis0(log_softmax_2d_x, log_softmax_2d_expected):
+    x = log_softmax_2d_x.T
+    expected = log_softmax_2d_expected.T
+    assert_allclose(sc.log_softmax(x, axis=0), expected, rtol=1e-13)
+
+
+def test_log_softmax_3d(log_softmax_2d_x, log_softmax_2d_expected):
+    # 3-d input, with a tuple for the axis.
+    x_3d = log_softmax_2d_x.reshape(2, 2, 2)
+    expected_3d = log_softmax_2d_expected.reshape(2, 2, 2)
+    assert_allclose(sc.log_softmax(x_3d, axis=(1, 2)), expected_3d, rtol=1e-13)
+
+
+def test_log_softmax_scalar():
+    assert_allclose(sc.log_softmax(1.0), 0.0, rtol=1e-13)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fcb5a20037de46df939895d38fbe5fe6b85c9aa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py
@@ -0,0 +1,70 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_
+
+from scipy.special._testutils import FuncData
+from scipy.special import gamma, gammaln, loggamma
+
+
+def test_identities1():
+    # test the identity exp(loggamma(z)) = gamma(z)
+    x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5])
+    y = x.copy()
+    x, y = np.meshgrid(x, y)
+    z = (x + 1J*y).flatten()
+    dataset = np.vstack((z, gamma(z))).T
+
+    def f(z):
+        return np.exp(loggamma(z))
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_identities2():
+    # test the identity loggamma(z + 1) = log(z) + loggamma(z)
+    x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5])
+    y = x.copy()
+    x, y = np.meshgrid(x, y)
+    z = (x + 1J*y).flatten()
+    dataset = np.vstack((z, np.log(z) + loggamma(z))).T
+
+    def f(z):
+        return loggamma(z + 1)
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_complex_dispatch_realpart():
+    # Test that the real parts of loggamma and gammaln agree on the
+    # real axis.
+    x = np.r_[-np.logspace(10, -10), np.logspace(-10, 10)] + 0.5
+
+    dataset = np.vstack((x, gammaln(x))).T
+
+    def f(z):
+        z = np.array(z, dtype='complex128')
+        return loggamma(z).real
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_real_dispatch():
+    x = np.logspace(-10, 10) + 0.5
+    dataset = np.vstack((x, gammaln(x))).T
+
+    FuncData(loggamma, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+    assert_(loggamma(0) == np.inf)
+    assert_(np.isnan(loggamma(-1)))
+
+
+def test_gh_6536():
+    z = loggamma(complex(-3.4, +0.0))
+    zbar = loggamma(complex(-3.4, -0.0))
+    assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0)
+
+
+def test_branch_cut():
+    # Make sure negative zero is treated correctly
+    x = -np.logspace(300, -30, 100)
+    z = np.asarray([complex(x0, 0.0) for x0 in x])
+    zbar = np.asarray([complex(x0, -0.0) for x0 in x])
+    assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py
new file mode 100644
index 0000000000000000000000000000000000000000..050e8db5cb408c5c576c6cd292175d2df7c8f756
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py
@@ -0,0 +1,162 @@
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_allclose)
+from scipy.special import logit, expit, log_expit
+
+
+class TestLogit:
+
+    def check_logit_out(self, a, expected):
+        actual = logit(a)
+        assert_equal(actual.dtype, a.dtype)
+        rtol = 16*np.finfo(a.dtype).eps
+        assert_allclose(actual, expected, rtol=rtol)
+
+    def test_float32(self):
+        a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float32),
+                            [np.float32(0.0001), np.float32(0.49999),
+                             np.float32(0.50001)]))
+        # Expected values computed with mpmath from float32 inputs, e.g.
+        #   from mpmath import mp
+        #   mp.dps = 200
+        #   a = np.float32(1/9)
+        #   print(np.float32(mp.log(a) - mp.log1p(-a)))
+        # prints `-2.0794415`.
+        expected = np.array([-np.inf, -2.0794415, -1.2527629, -6.9314712e-01,
+                             -2.2314353e-01,  2.2314365e-01,  6.9314724e-01,
+                             1.2527630, 2.0794415, np.inf,
+                             -9.2102404, -4.0054321e-05, 4.0054321e-05],
+                            dtype=np.float32)
+        self.check_logit_out(a, expected)
+
+    def test_float64(self):
+        a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float64),
+                            [1e-8, 0.4999999999999, 0.50000000001]))
+        # Expected values computed with mpmath.
+        expected = np.array([-np.inf,
+                             -2.079441541679836,
+                             -1.252762968495368,
+                             -0.6931471805599454,
+                             -0.22314355131420985,
+                             0.22314355131420985,
+                             0.6931471805599452,
+                             1.2527629684953674,
+                             2.0794415416798353,
+                             np.inf,
+                             -18.420680733952366,
+                             -3.999023334699814e-13,
+                             4.000000330961484e-11])
+        self.check_logit_out(a, expected)
+
+    def test_nan(self):
+        expected = np.array([np.nan]*4)
+        with np.errstate(invalid='ignore'):
+            actual = logit(np.array([-3., -2., 2., 3.]))
+
+        assert_equal(expected, actual)
+
+
+class TestExpit:
+    def check_expit_out(self, dtype, expected):
+        a = np.linspace(-4, 4, 10)
+        a = np.array(a, dtype=dtype)
+        actual = expit(a)
+        assert_almost_equal(actual, expected)
+        assert_equal(actual.dtype, np.dtype(dtype))
+
+    def test_float32(self):
+        expected = np.array([0.01798621, 0.04265125,
+                            0.09777259, 0.20860852,
+                            0.39068246, 0.60931754,
+                            0.79139149, 0.9022274,
+                            0.95734876, 0.98201376], dtype=np.float32)
+        self.check_expit_out('f4', expected)
+
+    def test_float64(self):
+        expected = np.array([0.01798621, 0.04265125,
+                            0.0977726, 0.20860853,
+                            0.39068246, 0.60931754,
+                            0.79139147, 0.9022274,
+                            0.95734875, 0.98201379])
+        self.check_expit_out('f8', expected)
+
+    def test_large(self):
+        for dtype in (np.float32, np.float64, np.longdouble):
+            for n in (88, 89, 709, 710, 11356, 11357):
+                n = np.array(n, dtype=dtype)
+                assert_allclose(expit(n), 1.0, atol=1e-20)
+                assert_allclose(expit(-n), 0.0, atol=1e-20)
+                assert_equal(expit(n).dtype, dtype)
+                assert_equal(expit(-n).dtype, dtype)
+
+
+class TestLogExpit:
+
+    def test_large_negative(self):
+        x = np.array([-10000.0, -750.0, -500.0, -35.0])
+        y = log_expit(x)
+        assert_equal(y, x)
+
+    def test_large_positive(self):
+        x = np.array([750.0, 1000.0, 10000.0])
+        y = log_expit(x)
+        # y will contain -0.0, and -0.0 is used in the expected value,
+        # but assert_equal does not check the sign of zeros, and I don't
+        # think the sign is an essential part of the test (i.e. it would
+        # probably be OK if log_expit(1000) returned 0.0 instead of -0.0).
+        assert_equal(y, np.array([-0.0, -0.0, -0.0]))
+
+    def test_basic_float64(self):
+        x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9,
+                      0, 1e-9, 0.1, 1, 10, 100, 500, 710, 725, 735])
+        y = log_expit(x)
+        #
+        # Expected values were computed with mpmath:
+        #
+        #   import mpmath
+        #
+        #   mpmath.mp.dps = 100
+        #
+        #   def mp_log_expit(x):
+        #       return -mpmath.log1p(mpmath.exp(-x))
+        #
+        #   expected = [float(mp_log_expit(t)) for t in x]
+        #
+        expected = [-32.000000000000014, -20.000000002061153,
+                    -10.000045398899218, -3.048587351573742,
+                    -1.3132616875182228, -0.7443966600735709,
+                    -0.6931471810599453, -0.6931471805599453,
+                    -0.6931471800599454, -0.6443966600735709,
+                    -0.3132616875182228, -4.539889921686465e-05,
+                    -3.720075976020836e-44, -7.124576406741286e-218,
+                    -4.47628622567513e-309, -1.36930634e-315,
+                    -6.217e-320]
+
+        # When tested locally, only one value in y was not exactly equal to
+        # expected.  That was for x=1, and the y value differed from the
+        # expected by 1 ULP.  For this test, however, I'll use rtol=1e-15.
+        assert_allclose(y, expected, rtol=1e-15)
+
+    def test_basic_float32(self):
+        x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9,
+                      0, 1e-9, 0.1, 1, 10, 100], dtype=np.float32)
+        y = log_expit(x)
+        #
+        # Expected values were computed with mpmath:
+        #
+        #   import mpmath
+        #
+        #   mpmath.mp.dps = 100
+        #
+        #   def mp_log_expit(x):
+        #       return -mpmath.log1p(mpmath.exp(-x))
+        #
+        #   expected = [np.float32(mp_log_expit(t)) for t in x]
+        #
+        expected = np.array([-32.0, -20.0, -10.000046, -3.0485873,
+                             -1.3132616, -0.7443967, -0.6931472,
+                             -0.6931472, -0.6931472, -0.64439666,
+                             -0.3132617, -4.5398898e-05, -3.8e-44],
+                            dtype=np.float32)
+
+        assert_allclose(y, expected, rtol=5e-7)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..420c0d89f438701b57c4786ce7fa62279c668e5e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py
@@ -0,0 +1,327 @@
+import math
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import array_namespace, is_array_api_strict
+from scipy._lib._array_api_no_0d import (xp_assert_equal, xp_assert_close,
+                                         xp_assert_less)
+
+from scipy.special import logsumexp, softmax
+from scipy.special._logsumexp import _wrap_radians
+
+
+dtypes = ['float32', 'float64', 'int32', 'int64', 'complex64', 'complex128']
+integral_dtypes = ['int32', 'int64']
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('jax.numpy',
+                              reason="JAX arrays do not support item assignment")
+def test_wrap_radians(xp):
+    x = xp.asarray([-math.pi-1, -math.pi, -1, -1e-300,
+                    0, 1e-300, 1, math.pi, math.pi+1])
+    ref = xp.asarray([math.pi-1, math.pi, -1, -1e-300,
+                    0, 1e-300, 1, math.pi, -math.pi+1])
+    res = _wrap_radians(x, xp)
+    xp_assert_close(res, ref, atol=0)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('jax.numpy',
+                              reason="JAX arrays do not support item assignment")
+class TestLogSumExp:
+    def test_logsumexp(self, xp):
+        # Test with zero-size array
+        a = xp.asarray([])
+        desired = xp.asarray(-xp.inf)
+        xp_assert_equal(logsumexp(a), desired)
+
+        # Test whether logsumexp() function correctly handles large inputs.
+        a = xp.arange(200., dtype=xp.float64)
+        desired = xp.log(xp.sum(xp.exp(a)))
+        xp_assert_close(logsumexp(a), desired)
+
+        # Now test with large numbers
+        b = xp.asarray([1000., 1000.])
+        desired = xp.asarray(1000.0 + math.log(2.0))
+        xp_assert_close(logsumexp(b), desired)
+
+        n = 1000
+        b = xp.full((n,), 10000)
+        desired = xp.asarray(10000.0 + math.log(n))
+        xp_assert_close(logsumexp(b), desired)
+
+        x = xp.asarray([1e-40] * 1000000)
+        logx = xp.log(x)
+        X = xp.stack([x, x])
+        logX = xp.stack([logx, logx])
+        xp_assert_close(xp.exp(logsumexp(logX)), xp.sum(X))
+        xp_assert_close(xp.exp(logsumexp(logX, axis=0)), xp.sum(X, axis=0))
+        xp_assert_close(xp.exp(logsumexp(logX, axis=1)), xp.sum(X, axis=1))
+
+        # Handling special values properly
+        inf = xp.asarray([xp.inf])
+        nan = xp.asarray([xp.nan])
+        xp_assert_equal(logsumexp(inf), inf[0])
+        xp_assert_equal(logsumexp(-inf), -inf[0])
+        xp_assert_equal(logsumexp(nan), nan[0])
+        xp_assert_equal(logsumexp(xp.asarray([-xp.inf, -xp.inf])), -inf[0])
+
+        # Handling an array with different magnitudes on the axes
+        a = xp.asarray([[1e10, 1e-10],
+                        [-1e10, -np.inf]])
+        ref = xp.asarray([1e10, -1e10])
+        xp_assert_close(logsumexp(a, axis=-1), ref)
+
+        # Test keeping dimensions
+        xp_test = array_namespace(a) # `torch` needs `expand_dims`
+        ref = xp_test.expand_dims(ref, axis=-1)
+        xp_assert_close(logsumexp(a, axis=-1, keepdims=True), ref)
+
+        # Test multiple axes
+        xp_assert_close(logsumexp(a, axis=(-1, -2)), xp.asarray(1e10))
+
+    def test_logsumexp_b(self, xp):
+        a = xp.arange(200., dtype=xp.float64)
+        b = xp.arange(200., 0., -1.)
+        desired = xp.log(xp.sum(b*xp.exp(a)))
+        xp_assert_close(logsumexp(a, b=b), desired)
+
+        a = xp.asarray([1000, 1000])
+        b = xp.asarray([1.2, 1.2])
+        desired = xp.asarray(1000 + math.log(2 * 1.2))
+        xp_assert_close(logsumexp(a, b=b), desired)
+
+        x = xp.asarray([1e-40] * 100000)
+        b = xp.linspace(1, 1000, 100000)
+        logx = xp.log(x)
+        X = xp.stack((x, x))
+        logX = xp.stack((logx, logx))
+        B = xp.stack((b, b))
+        xp_assert_close(xp.exp(logsumexp(logX, b=B)), xp.sum(B * X))
+        xp_assert_close(xp.exp(logsumexp(logX, b=B, axis=0)), xp.sum(B * X, axis=0))
+        xp_assert_close(xp.exp(logsumexp(logX, b=B, axis=1)), xp.sum(B * X, axis=1))
+
+    def test_logsumexp_sign(self, xp):
+        a = xp.asarray([1, 1, 1])
+        b = xp.asarray([1, -1, -1])
+
+        r, s = logsumexp(a, b=b, return_sign=True)
+        xp_assert_close(r, xp.asarray(1.))
+        xp_assert_equal(s, xp.asarray(-1.))
+
+    def test_logsumexp_sign_zero(self, xp):
+        a = xp.asarray([1, 1])
+        b = xp.asarray([1, -1])
+
+        r, s = logsumexp(a, b=b, return_sign=True)
+        assert not xp.isfinite(r)
+        assert not xp.isnan(r)
+        assert r < 0
+        assert s == 0
+
+    def test_logsumexp_sign_shape(self, xp):
+        a = xp.ones((1, 2, 3, 4))
+        b = xp.ones_like(a)
+
+        r, s = logsumexp(a, axis=2, b=b, return_sign=True)
+        assert r.shape == s.shape == (1, 2, 4)
+
+        r, s = logsumexp(a, axis=(1, 3), b=b, return_sign=True)
+        assert r.shape == s.shape == (1,3)
+
+    def test_logsumexp_complex_sign(self, xp):
+        a = xp.asarray([1 + 1j, 2 - 1j, -2 + 3j])
+
+        r, s = logsumexp(a, return_sign=True)
+
+        expected_sumexp = xp.sum(xp.exp(a))
+        # This is the numpy>=2.0 convention for np.sign
+        expected_sign = expected_sumexp / xp.abs(expected_sumexp)
+
+        xp_assert_close(s, expected_sign)
+        xp_assert_close(s * xp.exp(r), expected_sumexp)
+
+    def test_logsumexp_shape(self, xp):
+        a = xp.ones((1, 2, 3, 4))
+        b = xp.ones_like(a)
+
+        r = logsumexp(a, axis=2, b=b)
+        assert r.shape == (1, 2, 4)
+
+        r = logsumexp(a, axis=(1, 3), b=b)
+        assert r.shape == (1, 3)
+
+    def test_logsumexp_b_zero(self, xp):
+        a = xp.asarray([1, 10000])
+        b = xp.asarray([1, 0])
+
+        xp_assert_close(logsumexp(a, b=b), xp.asarray(1.))
+
+    def test_logsumexp_b_shape(self, xp):
+        a = xp.zeros((4, 1, 2, 1))
+        b = xp.ones((3, 1, 5))
+
+        logsumexp(a, b=b)
+
+    @pytest.mark.parametrize('arg', (1, [1, 2, 3]))
+    @pytest.mark.skip_xp_backends(np_only=True)
+    def test_xp_invalid_input(self, arg, xp):
+        assert logsumexp(arg) == logsumexp(np.asarray(np.atleast_1d(arg)))
+
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason="Lists correspond with NumPy backend")
+    def test_list(self, xp):
+        a = [1000, 1000]
+        desired = xp.asarray(1000.0 + math.log(2.0), dtype=np.float64)
+        xp_assert_close(logsumexp(a), desired)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    def test_dtypes_a(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        a = xp.asarray([1000., 1000.], dtype=dtype)
+        xp_test = array_namespace(a)  # torch needs compatible `isdtype`
+        desired_dtype = (xp.asarray(1.).dtype if xp_test.isdtype(dtype, 'integral')
+                         else dtype)  # true for all libraries tested
+        desired = xp.asarray(1000.0 + math.log(2.0), dtype=desired_dtype)
+        xp_assert_close(logsumexp(a), desired)
+
+    @pytest.mark.parametrize('dtype_a', dtypes)
+    @pytest.mark.parametrize('dtype_b', dtypes)
+    def test_dtypes_ab(self, dtype_a, dtype_b, xp):
+        xp_dtype_a = getattr(xp, dtype_a)
+        xp_dtype_b = getattr(xp, dtype_b)
+        a = xp.asarray([2, 1], dtype=xp_dtype_a)
+        b = xp.asarray([1, -1], dtype=xp_dtype_b)
+        xp_test = array_namespace(a, b)  # torch needs compatible result_type
+        if is_array_api_strict(xp):
+            xp_float_dtypes = [dtype for dtype in [xp_dtype_a, xp_dtype_b]
+                               if not xp_test.isdtype(dtype, 'integral')]
+            if len(xp_float_dtypes) < 2:  # at least one is integral
+                xp_float_dtypes.append(xp.asarray(1.).dtype)
+            desired_dtype = xp_test.result_type(*xp_float_dtypes)
+        else:
+            # True for all libraries tested
+            desired_dtype = xp_test.result_type(xp_dtype_a, xp_dtype_b, xp.float32)
+        desired = xp.asarray(math.log(math.exp(2) - math.exp(1)), dtype=desired_dtype)
+        xp_assert_close(logsumexp(a, b=b), desired)
+
+    def test_gh18295(self, xp):
+        # gh-18295 noted loss of precision when real part of one element is much
+        # larger than the rest. Check that this is resolved.
+        a = xp.asarray([0.0, -40.0])
+        res = logsumexp(a)
+        ref = xp.logaddexp(a[0], a[1])
+        xp_assert_close(res, ref)
+
+    @pytest.mark.parametrize('dtype', ['complex64', 'complex128'])
+    def test_gh21610(self, xp, dtype):
+        # gh-21610 noted that `logsumexp` could return imaginary components
+        # outside the range (-pi, pi]. Check that this is resolved.
+        # While working on this, I noticed that all other tests passed even
+        # when the imaginary component of the result was zero. This suggested
+        # the need of a stronger test with imaginary dtype.
+        rng = np.random.default_rng(324984329582349862)
+        dtype = getattr(xp, dtype)
+        shape = (10, 100)
+        x = rng.uniform(1, 40, shape) + 1.j * rng.uniform(1, 40, shape)
+        x = xp.asarray(x, dtype=dtype)
+
+        res = logsumexp(x, axis=1)
+        ref = xp.log(xp.sum(xp.exp(x), axis=1))
+        max = xp.full_like(xp.imag(res), xp.asarray(xp.pi))
+        xp_assert_less(xp.abs(xp.imag(res)), max)
+        xp_assert_close(res, ref)
+
+        out, sgn = logsumexp(x, return_sign=True, axis=1)
+        ref = xp.sum(xp.exp(x), axis=1)
+        xp_assert_less(xp.abs(xp.imag(sgn)), max)
+        xp_assert_close(out, xp.real(xp.log(ref)))
+        xp_assert_close(sgn, ref/xp.abs(ref))
+
+    def test_gh21709_small_imaginary(self, xp):
+        # Test that `logsumexp` does not lose relative precision of
+        # small imaginary components
+        x = xp.asarray([0, 0.+2.2204460492503132e-17j])
+        res = logsumexp(x)
+        # from mpmath import mp
+        # mp.dps = 100
+        # x, y = mp.mpc(0), mp.mpc('0', '2.2204460492503132e-17')
+        # ref = complex(mp.log(mp.exp(x) + mp.exp(y)))
+        ref = xp.asarray(0.6931471805599453+1.1102230246251566e-17j)
+        xp_assert_close(xp.real(res), xp.real(ref))
+        xp_assert_close(xp.imag(res), xp.imag(ref), atol=0, rtol=1e-15)
+
+    def test_gh22903(self, xp):
+        # gh-22903 reported that `logsumexp` produced NaN where the weight associated
+        # with the max magnitude element was negative and `return_sign=False`, even if
+        # the net result should be the log of a positive number.
+
+        # result is log of positive number
+        a = xp.asarray([3.06409428, 0.37251854, 3.87471931])
+        b = xp.asarray([1.88190708, 2.84174795, -0.85016884])
+        xp_assert_close(logsumexp(a, b=b), logsumexp(a, b=b, return_sign=True)[0])
+
+        # result is log of negative number
+        b = xp.asarray([1.88190708, 2.84174795, -3.85016884])
+        xp_assert_close(logsumexp(a, b=b), xp.asarray(xp.nan))
+
+
+class TestSoftmax:
+    def test_softmax_fixtures(self):
+        assert_allclose(softmax([1000, 0, 0, 0]), np.array([1, 0, 0, 0]),
+                        rtol=1e-13)
+        assert_allclose(softmax([1, 1]), np.array([.5, .5]), rtol=1e-13)
+        assert_allclose(softmax([0, 1]), np.array([1, np.e])/(1 + np.e),
+                        rtol=1e-13)
+
+        # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+        # converted to float.
+        x = np.arange(4)
+        expected = np.array([0.03205860328008499,
+                            0.08714431874203256,
+                            0.23688281808991013,
+                            0.6439142598879722])
+
+        assert_allclose(softmax(x), expected, rtol=1e-13)
+
+        # Translation property.  If all the values are changed by the same amount,
+        # the softmax result does not change.
+        assert_allclose(softmax(x + 100), expected, rtol=1e-13)
+
+        # When axis=None, softmax operates on the entire array, and preserves
+        # the shape.
+        assert_allclose(softmax(x.reshape(2, 2)), expected.reshape(2, 2),
+                        rtol=1e-13)
+
+
+    def test_softmax_multi_axes(self):
+        assert_allclose(softmax([[1000, 0], [1000, 0]], axis=0),
+                        np.array([[.5, .5], [.5, .5]]), rtol=1e-13)
+        assert_allclose(softmax([[1000, 0], [1000, 0]], axis=1),
+                        np.array([[1, 0], [1, 0]]), rtol=1e-13)
+
+        # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+        # converted to float.
+        x = np.array([[-25, 0, 25, 50],
+                    [1, 325, 749, 750]])
+        expected = np.array([[2.678636961770877e-33,
+                            1.9287498479371314e-22,
+                            1.3887943864771144e-11,
+                            0.999999999986112],
+                            [0.0,
+                            1.9444526359919372e-185,
+                            0.2689414213699951,
+                            0.7310585786300048]])
+        assert_allclose(softmax(x, axis=1), expected, rtol=1e-13)
+        assert_allclose(softmax(x.T, axis=0), expected.T, rtol=1e-13)
+
+        # 3-d input, with a tuple for the axis.
+        x3d = x.reshape(2, 2, 2)
+        assert_allclose(softmax(x3d, axis=(1, 2)), expected.reshape(2, 2, 2),
+                        rtol=1e-13)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py
new file mode 100644
index 0000000000000000000000000000000000000000..43e84e444f2eda03aef77ea923ca2d498aef4126
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py
@@ -0,0 +1,2292 @@
+"""
+Test SciPy functions versus mpmath, if available.
+
+"""
+import numpy as np
+from numpy.testing import assert_, assert_allclose, suppress_warnings
+from numpy import pi
+import pytest
+import itertools
+
+from scipy._lib import _pep440
+
+import scipy.special as sc
+from scipy.special._testutils import (
+    MissingModule, check_version, FuncData,
+    assert_func_equal)
+from scipy.special._mptestutils import (
+    Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal,
+    nonfunctional_tooslow, trace_args, time_limited, exception_to_nan,
+    inf_to_nan)
+from scipy.special._ufuncs import (
+    _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx,
+    _igam_fac)
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule('mpmath')
+
+
+# ------------------------------------------------------------------------------
+# expi
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.10')
+def test_expi_complex():
+    dataset = []
+    for r in np.logspace(-99, 2, 10):
+        for p in np.linspace(0, 2*np.pi, 30):
+            z = r*np.exp(1j*p)
+            dataset.append((z, complex(mpmath.ei(z))))
+    dataset = np.array(dataset, dtype=np.cdouble)
+
+    FuncData(sc.expi, dataset, 0, 1).check()
+
+
+# ------------------------------------------------------------------------------
+# expn
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_expn_large_n():
+    # Test the transition to the asymptotic regime of n.
+    dataset = []
+    for n in [50, 51]:
+        for x in np.logspace(0, 4, 200):
+            with mpmath.workdps(100):
+                dataset.append((n, x, float(mpmath.expint(n, x))))
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check()
+
+# ------------------------------------------------------------------------------
+# hyp0f1
+# ------------------------------------------------------------------------------
+
+
+@check_version(mpmath, '0.19')
+def test_hyp0f1_gh5764():
+    # Do a small and somewhat systematic test that runs quickly
+    dataset = []
+    axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]
+    for v in axis:
+        for x in axis:
+            for y in axis:
+                z = x + 1j*y
+                # mpmath computes the answer correctly at dps ~ 17 but
+                # fails for 20 < dps < 120 (uses a different method);
+                # set the dps high enough that this isn't an issue
+                with mpmath.workdps(120):
+                    res = complex(mpmath.hyp0f1(v, z))
+                dataset.append((v, z, res))
+    dataset = np.array(dataset)
+
+    FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2,
+             rtol=1e-13).check()
+
+
+@check_version(mpmath, '0.19')
+def test_hyp0f1_gh_1609():
+    # this is a regression test for gh-1609
+    vv = np.linspace(150, 180, 21)
+    af = sc.hyp0f1(vv, 0.5)
+    mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv])
+    assert_allclose(af, mf.astype(float), rtol=1e-12)
+
+
+# ------------------------------------------------------------------------------
+# hyperu
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '1.1.0')
+def test_hyperu_around_0():
+    dataset = []
+    # DLMF 13.2.14-15 test points.
+    for n in np.arange(-5, 5):
+        for b in np.linspace(-5, 5, 20):
+            a = -n
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+            a = -n + b - 1
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+    # DLMF 13.2.16-22 test points.
+    for a in [-10.5, -1.5, -0.5, 0, 0.5, 1, 10]:
+        for b in [-1.0, -0.5, 0, 0.5, 1, 1.5, 2, 2.5]:
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+    dataset = np.array(dataset)
+
+    FuncData(sc.hyperu, dataset, (0, 1, 2), 3, rtol=1e-15, atol=5e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# hyp2f1
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '1.0.0')
+def test_hyp2f1_strange_points():
+    pts = [
+        (2, -1, -1, 0.7),  # expected: 2.4
+        (2, -2, -2, 0.7),  # expected: 3.87
+    ]
+    pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4))
+    pts = [
+        (a, b, c, x) for a, b, c, x in pts
+        if b == c and round(b) == b and b < 0 and b != -1000
+    ]
+    kw = dict(eliminate=True)
+    dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.13')
+def test_hyp2f1_real_some_points():
+    pts = [
+        (1, 2, 3, 0),
+        (1./3, 2./3, 5./6, 27./32),
+        (1./4, 1./2, 3./4, 80./81),
+        (2,-2, -3, 3),
+        (2, -3, -2, 3),
+        (2, -1.5, -1.5, 3),
+        (1, 2, 3, 0),
+        (0.7235, -1, -5, 0.3),
+        (0.25, 1./3, 2, 0.999),
+        (0.25, 1./3, 2, -1),
+        (2, 3, 5, 0.99),
+        (3./2, -0.5, 3, 0.99),
+        (2, 2.5, -3.25, 0.999),
+        (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
+        (-10, 900, -10.5, 0.99),
+        (-10, 900, 10.5, 0.99),
+        (-1, 2, 1, 1.0),
+        (-1, 2, 1, -1.0),
+        (-3, 13, 5, 1.0),
+        (-3, 13, 5, -1.0),
+        (0.5, 1 - 270.5, 1.5, 0.999**2),  # from issue 1561
+    ]
+    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.14')
+def test_hyp2f1_some_points_2():
+    # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
+    # was fixed in their SVN since then
+    pts = [
+        (112, (51,10), (-9,10), -0.99999),
+        (10,-900,10.5,0.99),
+        (10,-900,-10.5,0.99),
+    ]
+
+    def fev(x):
+        if isinstance(x, tuple):
+            return float(x[0]) / x[1]
+        else:
+            return x
+
+    dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.13')
+def test_hyp2f1_real_some():
+    dataset = []
+    for a in [-10, -5, -1.8, 1.8, 5, 10]:
+        for b in [-2.5, -1, 1, 7.4]:
+            for c in [-9, -1.8, 5, 20.4]:
+                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
+                    try:
+                        v = float(mpmath.hyp2f1(a, b, c, z))
+                    except Exception:
+                        continue
+                    dataset.append((a, b, c, z, v))
+    dataset = np.array(dataset, dtype=np.float64)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9,
+                 ignore_inf_sign=True).check()
+
+
+@check_version(mpmath, '0.12')
+@pytest.mark.slow
+def test_hyp2f1_real_random():
+    npoints = 500
+    dataset = np.zeros((npoints, 5), np.float64)
+
+    np.random.seed(1234)
+    dataset[:, 0] = np.random.pareto(1.5, npoints)
+    dataset[:, 1] = np.random.pareto(1.5, npoints)
+    dataset[:, 2] = np.random.pareto(1.5, npoints)
+    dataset[:, 3] = 2*np.random.rand(npoints) - 1
+
+    dataset[:, 0] *= (-1)**np.random.randint(2, npoints)
+    dataset[:, 1] *= (-1)**np.random.randint(2, npoints)
+    dataset[:, 2] *= (-1)**np.random.randint(2, npoints)
+
+    for ds in dataset:
+        if mpmath.__version__ < '0.14':
+            # mpmath < 0.14 fails for c too much smaller than a, b
+            if abs(ds[:2]).max() > abs(ds[2]):
+                ds[2] = abs(ds[:2]).max()
+        ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4])))
+
+    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
+
+
+# ------------------------------------------------------------------------------
+# erf (complex)
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.14')
+def test_erf_complex():
+    # need to increase mpmath precision for this test
+    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+    try:
+        mpmath.mp.dps = 70
+        x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11))
+        x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11))
+        points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()]
+
+        assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points,
+                          vectorized=False, rtol=1e-13)
+        assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points,
+                          vectorized=False, rtol=1e-13)
+    finally:
+        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+
+# ------------------------------------------------------------------------------
+# lpmv
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.15')
+def test_lpmv():
+    pts = []
+    for x in [-0.99, -0.557, 1e-6, 0.132, 1]:
+        pts.extend([
+            (1, 1, x),
+            (1, -1, x),
+            (-1, 1, x),
+            (-1, -2, x),
+            (1, 1.7, x),
+            (1, -1.7, x),
+            (-1, 1.7, x),
+            (-1, -2.7, x),
+            (1, 10, x),
+            (1, 11, x),
+            (3, 8, x),
+            (5, 11, x),
+            (-3, 8, x),
+            (-5, 11, x),
+            (3, -8, x),
+            (5, -11, x),
+            (-3, -8, x),
+            (-5, -11, x),
+            (3, 8.3, x),
+            (5, 11.3, x),
+            (-3, 8.3, x),
+            (-5, 11.3, x),
+            (3, -8.3, x),
+            (5, -11.3, x),
+            (-3, -8.3, x),
+            (-5, -11.3, x),
+        ])
+
+    def mplegenp(nu, mu, x):
+        if mu == int(mu) and x == 1:
+            # mpmath 0.17 gets this wrong
+            if mu == 0:
+                return 1
+            else:
+                return 0
+        return mpmath.legenp(nu, mu, x)
+
+    dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    def evf(mu, nu, x):
+        return sc.lpmv(mu.astype(int), nu, x)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# beta
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.15')
+def test_beta():
+    np.random.seed(1234)
+
+    b = np.r_[np.logspace(-200, 200, 4),
+              np.logspace(-10, 10, 4),
+              np.logspace(-1, 1, 4),
+              np.arange(-10, 11, 1),
+              np.arange(-10, 11, 1) + 0.5,
+              -1, -2.3, -3, -100.3, -10003.4]
+    a = b
+
+    ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T
+
+    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+    try:
+        mpmath.mp.dps = 400
+
+        assert_func_equal(sc.beta,
+                          lambda a, b: float(mpmath.beta(a, b)),
+                          ab,
+                          vectorized=False,
+                          rtol=1e-10,
+                          ignore_inf_sign=True)
+
+        assert_func_equal(
+            sc.betaln,
+            lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))),
+            ab,
+            vectorized=False,
+            rtol=1e-10)
+    finally:
+        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+
+# ------------------------------------------------------------------------------
+# loggamma
+# ------------------------------------------------------------------------------
+
+LOGGAMMA_TAYLOR_RADIUS = 0.2
+
+
+@check_version(mpmath, '0.19')
+def test_loggamma_taylor_transition():
+    # Make sure there isn't a big jump in accuracy when we move from
+    # using the Taylor series to using the recurrence relation.
+
+    r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1])
+    theta = np.linspace(0, 2*np.pi, 20)
+    r, theta = np.meshgrid(r, theta)
+    dz = r*np.exp(1j*theta)
+    z = np.r_[1 + dz, 2 + dz].flatten()
+
+    dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
+    dataset = np.array(dataset)
+
+    FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
+
+
+@check_version(mpmath, '0.19')
+def test_loggamma_taylor():
+    # Test around the zeros at z = 1, 2.
+
+    r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10)
+    theta = np.linspace(0, 2*np.pi, 20)
+    r, theta = np.meshgrid(r, theta)
+    dz = r*np.exp(1j*theta)
+    z = np.r_[1 + dz, 2 + dz].flatten()
+
+    dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
+    dataset = np.array(dataset)
+
+    FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# rgamma
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_rgamma_zeros():
+    # Test around the zeros at z = 0, -1, -2, ...,  -169. (After -169 we
+    # get values that are out of floating point range even when we're
+    # within 0.1 of the zero.)
+
+    # Can't use too many points here or the test takes forever.
+    dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = np.arange(0, -170, -1).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    with mpmath.workdps(100):
+        dataset = [(z0, complex(mpmath.rgamma(z0))) for z0 in z]
+
+    dataset = np.array(dataset)
+    FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check()
+
+
+# ------------------------------------------------------------------------------
+# digamma
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_digamma_roots():
+    # Test the special-cased roots for digamma.
+    root = mpmath.findroot(mpmath.digamma, 1.5)
+    roots = [float(root)]
+    root = mpmath.findroot(mpmath.digamma, -0.5)
+    roots.append(float(root))
+    roots = np.array(roots)
+
+    # If we test beyond a radius of 0.24 mpmath will take forever.
+    dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    z = (roots + np.dstack((dz,)*roots.size)).flatten()
+    with mpmath.workdps(30):
+        dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
+
+    dataset = np.array(dataset)
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
+
+
+@check_version(mpmath, '0.19')
+def test_digamma_negreal():
+    # Test digamma around the negative real axis. Don't do this in
+    # TestSystematic because the points need some jiggering so that
+    # mpmath doesn't take forever.
+
+    digamma = exception_to_nan(mpmath.digamma)
+
+    x = -np.logspace(300, -30, 100)
+    y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)]
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    with mpmath.workdps(40):
+        dataset = [(z0, complex(digamma(z0))) for z0 in z]
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
+
+
+@check_version(mpmath, '0.19')
+def test_digamma_boundary():
+    # Check that there isn't a jump in accuracy when we switch from
+    # using the asymptotic series to the reflection formula.
+
+    x = -np.logspace(300, -30, 100)
+    y = np.array([-6.1, -5.9, 5.9, 6.1])
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    with mpmath.workdps(30):
+        dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# gammainc
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_gammainc_boundary():
+    # Test the transition to the asymptotic series.
+    small = 20
+    a = np.linspace(0.5*small, 2*small, 50)
+    x = a.copy()
+    a, x = np.meshgrid(a, x)
+    a, x = a.flatten(), x.flatten()
+    with mpmath.workdps(100):
+        dataset = [(a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True)))
+                   for a0, x0 in zip(a, x)]
+    dataset = np.array(dataset)
+
+    FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check()
+
+
+# ------------------------------------------------------------------------------
+# spence
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_spence_circle():
+    # The trickiest region for spence is around the circle |z - 1| = 1,
+    # so test that region carefully.
+
+    def spence(z):
+        return complex(mpmath.polylog(2, 1 - z))
+
+    r = np.linspace(0.5, 1.5)
+    theta = np.linspace(0, 2*pi)
+    z = (1 + np.outer(r, np.exp(1j*theta))).flatten()
+    dataset = np.asarray([(z0, spence(z0)) for z0 in z])
+
+    FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# sinpi and cospi
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_sinpi_zeros():
+    eps = np.finfo(float).eps
+    dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = np.arange(-100, 100, 1).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    dataset = np.asarray([(z0, complex(mpmath.sinpi(z0)))
+                          for z0 in z])
+    FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check()
+
+
+@check_version(mpmath, '0.19')
+def test_cospi_zeros():
+    eps = np.finfo(float).eps
+    dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    dataset = np.asarray([(z0, complex(mpmath.cospi(z0)))
+                          for z0 in z])
+
+    FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check()
+
+
+# ------------------------------------------------------------------------------
+# ellipj
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_dn_quarter_period():
+    def dn(u, m):
+        return sc.ellipj(u, m)[2]
+
+    def mpmath_dn(u, m):
+        return float(mpmath.ellipfun("dn", u=u, m=m))
+
+    m = np.linspace(0, 1, 20)
+    du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)]
+    dataset = []
+    for m0 in m:
+        u0 = float(mpmath.ellipk(m0))
+        for du0 in du:
+            p = u0 + du0
+            dataset.append((p, m0, mpmath_dn(p, m0)))
+    dataset = np.asarray(dataset)
+
+    FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check()
+
+
+# ------------------------------------------------------------------------------
+# Wright Omega
+# ------------------------------------------------------------------------------
+
+def _mpmath_wrightomega(z, dps):
+    with mpmath.workdps(dps):
+        z = mpmath.mpc(z)
+        unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi))
+        res = mpmath.lambertw(mpmath.exp(z), unwind)
+    return res
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_branch():
+    x = -np.logspace(10, 0, 25)
+    picut_above = [np.nextafter(np.pi, np.inf)]
+    picut_below = [np.nextafter(np.pi, -np.inf)]
+    npicut_above = [np.nextafter(-np.pi, np.inf)]
+    npicut_below = [np.nextafter(-np.pi, -np.inf)]
+    for i in range(50):
+        picut_above.append(np.nextafter(picut_above[-1], np.inf))
+        picut_below.append(np.nextafter(picut_below[-1], -np.inf))
+        npicut_above.append(np.nextafter(npicut_above[-1], np.inf))
+        npicut_below.append(np.nextafter(npicut_below[-1], -np.inf))
+    y = np.hstack((picut_above, picut_below, npicut_above, npicut_below))
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check()
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_region1():
+    # This region gets less coverage in the TestSystematic test
+    x = np.linspace(-2, 1)
+    y = np.linspace(1, 2*np.pi)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_region2():
+    # This region gets less coverage in the TestSystematic test
+    x = np.linspace(-2, 1)
+    y = np.linspace(-2*np.pi, -1)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
+
+
+# ------------------------------------------------------------------------------
+# lambertw
+# ------------------------------------------------------------------------------
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_lambertw_smallz():
+    x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(mpmath.lambertw(z0)))
+                          for z0 in z])
+
+    FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# Systematic tests
+# ------------------------------------------------------------------------------
+
+# The functions lpn, lpmn, clpmn, and sph_harm appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all,
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn),
+# and sph_harm_y respectively. The deprecated functions listed above are
+# implemented as shims around their respective replacements. The replacements
+# are tested separately, but tests for the deprecated functions remain to
+# verify the correctness of the shims.
+
+HYPERKW = dict(maxprec=200, maxterms=200)
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.17')
+class TestSystematic:
+
+    def test_airyai(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [Arg(-1e3, 1e3)])
+
+    def test_airyai_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [ComplexArg()])
+
+    def test_airyai_prime(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airyai_prime_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [ComplexArg()])
+
+    def test_airybi(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airybi_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [ComplexArg()])
+
+    def test_airybi_prime(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airybi_prime_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [ComplexArg()])
+
+    def test_bei(self):
+        assert_mpmath_equal(sc.bei,
+                            exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)),
+                            [Arg(-1e3, 1e3)])
+
+    def test_ber(self):
+        assert_mpmath_equal(sc.ber,
+                            exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)),
+                            [Arg(-1e3, 1e3)])
+
+    def test_bernoulli(self):
+        assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)],
+                            lambda n: float(mpmath.bernoulli(int(n))),
+                            [IntArg(0, 13000)],
+                            rtol=1e-9, n=13000)
+
+    def test_besseli(self):
+        assert_mpmath_equal(
+            sc.iv,
+            exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg()],
+            atol=1e-270,
+        )
+
+    def test_besseli_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.iv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), ComplexArg()],
+        )
+
+    def test_besselj(self):
+        assert_mpmath_equal(
+            sc.jv,
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg(-1e3, 1e3)],
+            ignore_inf_sign=True,
+        )
+
+        # loss of precision at large arguments due to oscillation
+        assert_mpmath_equal(
+            sc.jv,
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
+            ignore_inf_sign=True,
+            rtol=1e-5,
+        )
+
+    def test_besselj_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.jv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(), ComplexArg()]
+        )
+
+    def test_besselk(self):
+        assert_mpmath_equal(
+            sc.kv,
+            mpmath.besselk,
+            [Arg(-200, 200), Arg(0, np.inf)],
+            nan_ok=False,
+            rtol=1e-12,
+        )
+
+    def test_besselk_int(self):
+        assert_mpmath_equal(
+            sc.kn,
+            mpmath.besselk,
+            [IntArg(-200, 200), Arg(0, np.inf)],
+            nan_ok=False,
+            rtol=1e-12,
+        )
+
+    def test_besselk_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.kv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), ComplexArg()],
+        )
+
+    def test_bessely(self):
+        def mpbessely(v, x):
+            r = float(mpmath.bessely(v, x, **HYPERKW))
+            if abs(r) > 1e305:
+                # overflowing to inf a bit earlier is OK
+                r = np.inf * np.sign(r)
+            if abs(r) == 0 and x == 0:
+                # invalid result from mpmath, point x=0 is a divergence
+                return np.nan
+            return r
+        assert_mpmath_equal(
+            sc.yv,
+            exception_to_nan(mpbessely),
+            [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
+            n=5000,
+        )
+
+    def test_bessely_complex(self):
+        def mpbessely(v, x):
+            r = complex(mpmath.bessely(v, x, **HYPERKW))
+            if abs(r) > 1e305:
+                # overflowing to inf a bit earlier is OK
+                with np.errstate(invalid='ignore'):
+                    r = np.inf * np.sign(r)
+            return r
+        assert_mpmath_equal(
+            lambda v, z: sc.yv(v.real, z),
+            exception_to_nan(mpbessely),
+            [Arg(), ComplexArg()],
+            n=15000,
+        )
+
+    def test_bessely_int(self):
+        def mpbessely(v, x):
+            r = float(mpmath.bessely(v, x))
+            if abs(r) == 0 and x == 0:
+                # invalid result from mpmath, point x=0 is a divergence
+                return np.nan
+            return r
+        assert_mpmath_equal(
+            lambda v, z: sc.yn(int(v), z),
+            exception_to_nan(mpbessely),
+            [IntArg(-1000, 1000), Arg(-1e8, 1e8)],
+        )
+
+    def test_beta(self):
+        bad_points = []
+
+        def beta(a, b, nonzero=False):
+            if a < -1e12 or b < -1e12:
+                # Function is defined here only at integers, but due
+                # to loss of precision this is numerically
+                # ill-defined. Don't compare values here.
+                return np.nan
+            if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0:
+                # close to a zero of the function: mpmath and scipy
+                # will not round here the same, so the test needs to be
+                # run with an absolute tolerance
+                if nonzero:
+                    bad_points.append((float(a), float(b)))
+                    return np.nan
+            return mpmath.beta(a, b)
+
+        assert_mpmath_equal(
+            sc.beta,
+            lambda a, b: beta(a, b, nonzero=True),
+            [Arg(), Arg()],
+            dps=400,
+            ignore_inf_sign=True,
+        )
+
+        assert_mpmath_equal(
+            sc.beta,
+            beta,
+            np.array(bad_points),
+            dps=400,
+            ignore_inf_sign=True,
+            atol=1e-11,
+        )
+
+    def test_betainc(self):
+        assert_mpmath_equal(
+            sc.betainc,
+            time_limited()(
+                exception_to_nan(
+                    lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True)
+                )
+            ),
+            [Arg(), Arg(), Arg()],
+        )
+
+    def test_betaincc(self):
+        assert_mpmath_equal(
+            sc.betaincc,
+            time_limited()(
+                exception_to_nan(
+                    lambda a, b, x: mpmath.betainc(a, b, x, 1, regularized=True)
+                )
+            ),
+            [Arg(), Arg(), Arg()],
+            dps=400,
+        )
+
+    def test_binom(self):
+        bad_points = []
+
+        def binomial(n, k, nonzero=False):
+            if abs(k) > 1e8*(abs(n) + 1):
+                # The binomial is rapidly oscillating in this region,
+                # and the function is numerically ill-defined. Don't
+                # compare values here.
+                return np.nan
+            if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15:
+                # close to a zero of the function: mpmath and scipy
+                # will not round here the same, so the test needs to be
+                # run with an absolute tolerance
+                if nonzero:
+                    bad_points.append((float(n), float(k)))
+                    return np.nan
+            return mpmath.binomial(n, k)
+
+        assert_mpmath_equal(
+            sc.binom,
+            lambda n, k: binomial(n, k, nonzero=True),
+            [Arg(), Arg()],
+            dps=400,
+        )
+
+        assert_mpmath_equal(
+            sc.binom,
+            binomial,
+            np.array(bad_points),
+            dps=400,
+            atol=1e-14,
+        )
+
+    def test_chebyt_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_chebyt(int(n), x),
+            exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)),
+            [IntArg(), Arg()],
+            dps=50,
+        )
+
+    @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
+    def test_chebyt(self):
+        assert_mpmath_equal(
+            sc.eval_chebyt,
+            lambda n, x: time_limited()(
+                exception_to_nan(mpmath.chebyt)
+            )(n, x, **HYPERKW),
+            [Arg(-101, 101), Arg()],
+            n=10000,
+        )
+
+    def test_chebyu_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_chebyu(int(n), x),
+            exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)),
+            [IntArg(), Arg()],
+            dps=50,
+        )
+
+    @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
+    def test_chebyu(self):
+        assert_mpmath_equal(
+            sc.eval_chebyu,
+            lambda n, x: time_limited()(
+                exception_to_nan(mpmath.chebyu)
+            )(n, x, **HYPERKW),
+            [Arg(-101, 101), Arg()],
+        )
+
+    def test_chi(self):
+        def chi(x):
+            return sc.shichi(x)[1]
+        assert_mpmath_equal(chi, mpmath.chi, [Arg()])
+        # check asymptotic series cross-over
+        assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
+
+    def test_chi_complex(self):
+        def chi(z):
+            return sc.shichi(z)[1]
+        # chi oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            chi,
+            mpmath.chi,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-12,
+        )
+
+    def test_ci(self):
+        def ci(x):
+            return sc.sici(x)[1]
+        # oscillating function: limit range
+        assert_mpmath_equal(ci, mpmath.ci, [Arg(-1e8, 1e8)])
+
+    def test_ci_complex(self):
+        def ci(z):
+            return sc.sici(z)[1]
+        # ci oscillates as Re[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            ci,
+            mpmath.ci,
+            [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
+            rtol=1e-8,
+        )
+
+    def test_cospi(self):
+        eps = np.finfo(float).eps
+        assert_mpmath_equal(_cospi, mpmath.cospi, [Arg()], nan_ok=False, rtol=2*eps)
+
+    def test_cospi_complex(self):
+        assert_mpmath_equal(
+            _cospi,
+            mpmath.cospi,
+            [ComplexArg()],
+            nan_ok=False,
+            rtol=1e-13,
+        )
+
+    def test_digamma(self):
+        assert_mpmath_equal(
+            sc.digamma,
+            exception_to_nan(mpmath.digamma),
+            [Arg()],
+            rtol=1e-12,
+            dps=50,
+        )
+
+    def test_digamma_complex(self):
+        # Test on a cut plane because mpmath will hang. See
+        # test_digamma_negreal for tests on the negative real axis.
+        def param_filter(z):
+            return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True)
+
+        assert_mpmath_equal(
+            sc.digamma,
+            exception_to_nan(mpmath.digamma),
+            [ComplexArg()],
+            rtol=1e-13,
+            dps=40,
+            param_filter=param_filter
+        )
+
+    def test_e1(self):
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            [Arg()],
+            rtol=1e-14,
+        )
+
+    def test_e1_complex(self):
+        # E_1 oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-11,
+        )
+
+        # Check cross-over region
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            (np.linspace(-50, 50, 171)[:, None]
+             + np.r_[0, np.logspace(-3, 2, 61), -np.logspace(-3, 2, 11)]*1j).ravel(),
+            rtol=1e-11,
+        )
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            (np.linspace(-50, -35, 10000) + 0j),
+            rtol=1e-11,
+        )
+
+    def test_exprel(self):
+        assert_mpmath_equal(
+            sc.exprel,
+            lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
+            [Arg(a=-np.log(np.finfo(np.float64).max),
+                 b=np.log(np.finfo(np.float64).max))],
+        )
+        assert_mpmath_equal(
+            sc.exprel,
+            lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
+            np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]),
+            rtol=1e-11,
+        )
+        assert_(np.isinf(sc.exprel(np.inf)))
+        assert_(sc.exprel(-np.inf) == 0)
+
+    def test_expm1_complex(self):
+        # Oscillates as a function of Im[z], so limit range to avoid loss of precision
+        assert_mpmath_equal(
+            sc.expm1,
+            mpmath.expm1,
+            [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))],
+        )
+
+    def test_log1p_complex(self):
+        assert_mpmath_equal(
+            sc.log1p,
+            lambda x: mpmath.log(x+1),
+            [ComplexArg()],
+            dps=60,
+        )
+
+    def test_log1pmx(self):
+        assert_mpmath_equal(
+            _log1pmx,
+            lambda x: mpmath.log(x + 1) - x,
+            [Arg()],
+            dps=60,
+            rtol=1e-14,
+        )
+
+    def test_ei(self):
+        assert_mpmath_equal(sc.expi, mpmath.ei, [Arg()], rtol=1e-11)
+
+    def test_ei_complex(self):
+        # Ei oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            sc.expi,
+            mpmath.ei,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-9,
+        )
+
+    def test_ellipe(self):
+        assert_mpmath_equal(sc.ellipe, mpmath.ellipe, [Arg(b=1.0)])
+
+    def test_ellipeinc(self):
+        assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(-1e3, 1e3), Arg(b=1.0)])
+
+    def test_ellipeinc_largephi(self):
+        assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(), Arg()])
+
+    def test_ellipf(self):
+        assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(-1e3, 1e3), Arg()])
+
+    def test_ellipf_largephi(self):
+        assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(), Arg()])
+
+    def test_ellipk(self):
+        assert_mpmath_equal(sc.ellipk, mpmath.ellipk, [Arg(b=1.0)])
+        assert_mpmath_equal(
+            sc.ellipkm1,
+            lambda m: mpmath.ellipk(1 - m),
+            [Arg(a=0.0)],
+            dps=400,
+        )
+
+    def test_ellipkinc(self):
+        def ellipkinc(phi, m):
+            return mpmath.ellippi(0, phi, m)
+        assert_mpmath_equal(
+            sc.ellipkinc,
+            ellipkinc,
+            [Arg(-1e3, 1e3), Arg(b=1.0)],
+            ignore_inf_sign=True,
+        )
+
+    def test_ellipkinc_largephi(self):
+        def ellipkinc(phi, m):
+            return mpmath.ellippi(0, phi, m)
+        assert_mpmath_equal(
+            sc.ellipkinc,
+            ellipkinc,
+            [Arg(), Arg(b=1.0)],
+            ignore_inf_sign=True,
+        )
+
+    def test_ellipfun_sn(self):
+        def sn(u, m):
+            # mpmath doesn't get the zero at u = 0--fix that
+            if u == 0:
+                return 0
+            else:
+                return mpmath.ellipfun("sn", u=u, m=m)
+
+        # Oscillating function --- limit range of first argument; the
+        # loss of precision there is an expected numerical feature
+        # rather than an actual bug
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[0],
+            sn,
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_ellipfun_cn(self):
+        # see comment in ellipfun_sn
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[1],
+            lambda u, m: mpmath.ellipfun("cn", u=u, m=m),
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_ellipfun_dn(self):
+        # see comment in ellipfun_sn
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[2],
+            lambda u, m: mpmath.ellipfun("dn", u=u, m=m),
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_erf(self):
+        assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [Arg()])
+
+    def test_erf_complex(self):
+        assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [ComplexArg()], n=200)
+
+    def test_erfc(self):
+        assert_mpmath_equal(
+            sc.erfc,
+            exception_to_nan(lambda z: mpmath.erfc(z)),
+            [Arg()],
+            rtol=1e-13,
+        )
+
+    def test_erfc_complex(self):
+        assert_mpmath_equal(
+            sc.erfc,
+            exception_to_nan(lambda z: mpmath.erfc(z)),
+            [ComplexArg()],
+            n=200,
+        )
+
+    def test_erfi(self):
+        assert_mpmath_equal(sc.erfi, mpmath.erfi, [Arg()], n=200)
+
+    def test_erfi_complex(self):
+        assert_mpmath_equal(sc.erfi, mpmath.erfi, [ComplexArg()], n=200)
+
+    def test_ndtr(self):
+        assert_mpmath_equal(
+            sc.ndtr,
+            exception_to_nan(lambda z: mpmath.ncdf(z)),
+            [Arg()],
+            n=200,
+        )
+
+    def test_ndtr_complex(self):
+        assert_mpmath_equal(
+            sc.ndtr,
+            lambda z: mpmath.erfc(-z/np.sqrt(2.))/2.,
+            [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))],
+            n=400,
+        )
+
+    def test_log_ndtr(self):
+        assert_mpmath_equal(
+            sc.log_ndtr,
+            exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))),
+            [Arg()], n=600, dps=300, rtol=1e-13,
+        )
+
+    def test_log_ndtr_complex(self):
+        assert_mpmath_equal(
+            sc.log_ndtr,
+            exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)),
+            [ComplexArg(a=complex(-10000, -100), b=complex(10000, 100))],
+            n=200, dps=300,
+        )
+
+    def test_eulernum(self):
+        assert_mpmath_equal(
+            lambda n: sc.euler(n)[-1],
+            mpmath.eulernum,
+            [IntArg(1, 10000)],
+            n=10000,
+        )
+
+    def test_expint(self):
+        assert_mpmath_equal(
+            sc.expn,
+            mpmath.expint,
+            [IntArg(0, 200), Arg(0, np.inf)],
+            rtol=1e-13,
+            dps=160,
+        )
+
+    def test_fresnels(self):
+        def fresnels(x):
+            return sc.fresnel(x)[0]
+        assert_mpmath_equal(fresnels, mpmath.fresnels, [Arg()])
+
+    def test_fresnelc(self):
+        def fresnelc(x):
+            return sc.fresnel(x)[1]
+        assert_mpmath_equal(fresnelc, mpmath.fresnelc, [Arg()])
+
+    def test_gamma(self):
+        assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [Arg()])
+
+    def test_gamma_complex(self):
+        assert_mpmath_equal(
+            sc.gamma,
+            exception_to_nan(mpmath.gamma),
+            [ComplexArg()],
+            rtol=5e-13,
+        )
+
+    def test_gammainc(self):
+        # Larger arguments are tested in test_data.py:test_local
+        assert_mpmath_equal(
+            sc.gammainc,
+            lambda z, b: mpmath.gammainc(z, b=b, regularized=True),
+            [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
+            nan_ok=False,
+            rtol=1e-11,
+        )
+
+    def test_gammaincc(self):
+        # Larger arguments are tested in test_data.py:test_local
+        assert_mpmath_equal(
+            sc.gammaincc,
+            lambda z, a: mpmath.gammainc(z, a=a, regularized=True),
+            [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
+            nan_ok=False,
+            rtol=1e-11,
+        )
+
+    def test_gammaln(self):
+        # The real part of loggamma is log(|gamma(z)|).
+        def f(z):
+            return mpmath.loggamma(z).real
+
+        assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()])
+
+    @pytest.mark.xfail(run=False)
+    def test_gegenbauer(self):
+        assert_mpmath_equal(
+            sc.eval_gegenbauer,
+            exception_to_nan(mpmath.gegenbauer),
+            [Arg(-1e3, 1e3), Arg(), Arg()],
+        )
+
+    def test_gegenbauer_int(self):
+        # Redefine functions to deal with numerical + mpmath issues
+        def gegenbauer(n, a, x):
+            # Avoid overflow at large `a` (mpmath would need an even larger
+            # dps to handle this correctly, so just skip this region)
+            if abs(a) > 1e100:
+                return np.nan
+
+            # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these
+            # always correctly
+            if n == 0:
+                r = 1.0
+            elif n == 1:
+                r = 2*a*x
+            else:
+                r = mpmath.gegenbauer(n, a, x)
+
+            # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so
+            # compute the value by perturbing the result
+            if float(r) == 0 and a < -1 and float(a) == int(float(a)):
+                r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x)
+                if abs(r) < mpmath.mpf('1e-50'):
+                    r = mpmath.mpf('0.0')
+
+            # Differing overflow thresholds in scipy vs. mpmath
+            if abs(r) > 1e270:
+                return np.inf
+            return r
+
+        def sc_gegenbauer(n, a, x):
+            r = sc.eval_gegenbauer(int(n), a, x)
+            # Differing overflow thresholds in scipy vs. mpmath
+            if abs(r) > 1e270:
+                return np.inf
+            return r
+        assert_mpmath_equal(
+            sc_gegenbauer,
+            exception_to_nan(gegenbauer),
+            [IntArg(0, 100), Arg(-1e9, 1e9), Arg()],
+            n=40000, dps=100, ignore_inf_sign=True, rtol=1e-6,
+        )
+
+        # Check the small-x expansion
+        assert_mpmath_equal(
+            sc_gegenbauer,
+            exception_to_nan(gegenbauer),
+            [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))],
+            dps=100, ignore_inf_sign=True,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_gegenbauer_complex(self):
+        assert_mpmath_equal(
+            lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x),
+            exception_to_nan(mpmath.gegenbauer),
+            [IntArg(0, 100), Arg(), ComplexArg()],
+        )
+
+    @nonfunctional_tooslow
+    def test_gegenbauer_complex_general(self):
+        assert_mpmath_equal(
+            lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x),
+            exception_to_nan(mpmath.gegenbauer),
+            [Arg(-1e3, 1e3), Arg(), ComplexArg()],
+        )
+
+    def test_hankel1(self):
+        assert_mpmath_equal(
+            sc.hankel1,
+            exception_to_nan(lambda v, x: mpmath.hankel1(v, x, **HYPERKW)),
+            [Arg(-1e20, 1e20), Arg()],
+        )
+
+    def test_hankel2(self):
+        assert_mpmath_equal(
+            sc.hankel2,
+            exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)),
+            [Arg(-1e20, 1e20), Arg()],
+        )
+
+    @pytest.mark.xfail(run=False, reason="issues at intermediately large orders")
+    def test_hermite(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_hermite(int(n), x),
+            exception_to_nan(mpmath.hermite),
+            [IntArg(0, 10000), Arg()],
+        )
+
+    # hurwitz: same as zeta
+
+    def test_hyp0f1(self):
+        # mpmath reports no convergence unless maxterms is large enough
+        KW = dict(maxprec=400, maxterms=1500)
+        # n=500 (non-xslow default) fails for one bad point
+        assert_mpmath_equal(
+            sc.hyp0f1,
+            lambda a, x: mpmath.hyp0f1(a, x, **KW),
+            [Arg(-1e7, 1e7), Arg(0, 1e5)],
+            n=5000,
+        )
+        # NB: The range of the second parameter ("z") is limited from below
+        # because of an overflow in the intermediate calculations. The way
+        # for fix it is to implement an asymptotic expansion for Bessel J
+        # (similar to what is implemented for Bessel I here).
+
+    def test_hyp0f1_complex(self):
+        assert_mpmath_equal(
+            lambda a, z: sc.hyp0f1(a.real, z),
+            exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)),
+            [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))],
+        )
+        # NB: The range of the first parameter ("v") are limited by an overflow
+        # in the intermediate calculations. Can be fixed by implementing an
+        # asymptotic expansion for Bessel functions for large order.
+
+    def test_hyp1f1(self):
+        def mpmath_hyp1f1(a, b, x):
+            try:
+                return mpmath.hyp1f1(a, b, x)
+            except ZeroDivisionError:
+                return np.inf
+
+        assert_mpmath_equal(
+            sc.hyp1f1,
+            mpmath_hyp1f1,
+            [Arg(-50, 50), Arg(1, 50, inclusive_a=False), Arg(-50, 50)],
+            n=500,
+            nan_ok=False,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_hyp1f1_complex(self):
+        assert_mpmath_equal(
+            inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)),
+            exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
+            [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()],
+            n=2000,
+        )
+
+    @nonfunctional_tooslow
+    def test_hyp2f1_complex(self):
+        # SciPy's hyp2f1 seems to have performance and accuracy problems
+        assert_mpmath_equal(
+            lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x),
+            exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
+            [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()],
+            n=10,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_hyperu(self):
+        assert_mpmath_equal(
+            sc.hyperu,
+            exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)),
+            [Arg(), Arg(), Arg()],
+        )
+
+    @pytest.mark.xfail_on_32bit("mpmath issue gh-342: "
+                                "unsupported operand mpz, long for pow")
+    def test_igam_fac(self):
+        def mp_igam_fac(a, x):
+            return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a)
+
+        assert_mpmath_equal(
+            _igam_fac,
+            mp_igam_fac,
+            [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)],
+            rtol=1e-10,
+            dps=29,
+        )
+
+    def test_j0(self):
+        # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x)
+        # and at large arguments the phase of the cosine loses precision.
+        #
+        # This is numerically expected behavior, so we compare only up to
+        # 1e8 = 1e15 * 1e-7
+        assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e3, 1e3)])
+        assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e8, 1e8)], rtol=1e-5)
+
+    def test_j1(self):
+        # See comment in test_j0
+        assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e3, 1e3)])
+        assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e8, 1e8)], rtol=1e-5)
+
+    @pytest.mark.xfail(run=False)
+    def test_jacobi(self):
+        assert_mpmath_equal(
+            sc.eval_jacobi,
+            exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
+            [Arg(), Arg(), Arg(), Arg()],
+        )
+        assert_mpmath_equal(
+            lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x),
+            exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
+            [IntArg(), Arg(), Arg(), Arg()],
+        )
+
+    def test_jacobi_int(self):
+        # Redefine functions to deal with numerical + mpmath issues
+        def jacobi(n, a, b, x):
+            # Mpmath does not handle n=0 case always correctly
+            if n == 0:
+                return 1.0
+            return mpmath.jacobi(n, a, b, x)
+        assert_mpmath_equal(
+            lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x),
+            lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW),
+            [IntArg(), Arg(), Arg(), Arg()],
+            n=20000,
+            dps=50,
+        )
+
+    def test_kei(self):
+        def kei(x):
+            if x == 0:
+                # work around mpmath issue at x=0
+                return -pi/4
+            return exception_to_nan(mpmath.kei)(0, x, **HYPERKW)
+        assert_mpmath_equal(sc.kei, kei, [Arg(-1e30, 1e30)], n=1000)
+
+    def test_ker(self):
+        assert_mpmath_equal(
+            sc.ker,
+            exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)),
+            [Arg(-1e30, 1e30)],
+            n=1000,
+        )
+
+    @nonfunctional_tooslow
+    def test_laguerre(self):
+        assert_mpmath_equal(
+            trace_args(sc.eval_laguerre),
+            lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
+            [Arg(), Arg()],
+        )
+
+    def test_laguerre_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_laguerre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
+            [IntArg(), Arg()],
+            n=20000,
+        )
+
+    @pytest.mark.xfail_on_32bit("see gh-3551 for bad points")
+    def test_lambertw_real(self):
+        assert_mpmath_equal(
+            lambda x, k: sc.lambertw(x, int(k.real)),
+            lambda x, k: mpmath.lambertw(x, int(k.real)),
+            [ComplexArg(-np.inf, np.inf), IntArg(0, 10)],
+            rtol=1e-13, nan_ok=False,
+        )
+
+    def test_lanczos_sum_expg_scaled(self):
+        maxgamma = 171.624376956302725
+        e = np.exp(1)
+        g = 6.024680040776729583740234375
+
+        def gamma(x):
+            with np.errstate(over='ignore'):
+                fac = ((x + g - 0.5)/e)**(x - 0.5)
+                if fac != np.inf:
+                    res = fac*_lanczos_sum_expg_scaled(x)
+                else:
+                    fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5))
+                    res = fac*_lanczos_sum_expg_scaled(x)
+                    res *= fac
+            return res
+
+        assert_mpmath_equal(
+            gamma,
+            mpmath.gamma,
+            [Arg(0, maxgamma, inclusive_a=False)],
+            rtol=1e-13,
+        )
+
+    @nonfunctional_tooslow
+    def test_legendre(self):
+        assert_mpmath_equal(sc.eval_legendre, mpmath.legendre, [Arg(), Arg()])
+
+    def test_legendre_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_legendre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
+            [IntArg(), Arg()],
+            n=20000,
+        )
+
+        # Check the small-x expansion
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_legendre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
+            [IntArg(), FixedArg(np.logspace(-30, -4, 20))],
+        )
+
+    def test_legenp(self):
+        def lpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    v = sc.lpmn(m, n, z)[0][-1,-1]
+            except ValueError:
+                return np.nan
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = np.inf * np.sign(v.real)
+            return v
+
+        def lpnm_2(n, m, z):
+            v = sc.lpmv(m, n, z)
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = np.inf * np.sign(v.real)
+            return v
+
+        def legenp(n, m, z):
+            if (z == 1 or z == -1) and int(n) == n:
+                # Special case (mpmath may give inf, we take the limit by
+                # continuity)
+                if m == 0:
+                    if n < 0:
+                        n = -n - 1
+                    return mpmath.power(mpmath.sign(z), n)
+                else:
+                    return 0
+
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+
+            typ = 2 if abs(z) <= 1 else 3
+            v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ)
+
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = mpmath.inf * mpmath.sign(v.real)
+
+            return v
+
+        assert_mpmath_equal(lpnm, legenp, [IntArg(-100, 100), IntArg(-100, 100), Arg()])
+
+        assert_mpmath_equal(
+            lpnm_2,
+            legenp,
+            [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)],
+            atol=1e-10,
+        )
+
+    def test_legenp_complex_2(self):
+        def clpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1]
+            except ValueError:
+                return np.nan
+
+        def legenp(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2)
+
+        # mpmath is quite slow here
+        x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
+        y = np.array([-1e3, -0.5, 0.5, 1.3])
+        z = (x[:,None] + 1j*y[None,:]).ravel()
+
+        assert_mpmath_equal(
+            clpnm,
+            legenp,
+            [FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg(z)],
+            rtol=1e-6,
+            n=500,
+        )
+
+    def test_legenp_complex_3(self):
+        def clpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1]
+            except ValueError:
+                return np.nan
+
+        def legenp(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3)
+
+        # mpmath is quite slow here
+        x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
+        y = np.array([-1e3, -0.5, 0.5, 1.3])
+        z = (x[:,None] + 1j*y[None,:]).ravel()
+
+        assert_mpmath_equal(
+            clpnm,
+            legenp,
+            [FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg(z)],
+            rtol=1e-6,
+            n=500,
+        )
+
+    @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1")
+    def test_legenq(self):
+        def lqnm(n, m, z):
+            return sc.lqmn(m, n, z)[0][-1,-1]
+
+        def legenq(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenq)(n, m, z, type=2)
+
+        assert_mpmath_equal(
+            lqnm,
+            legenq,
+            [IntArg(0, 100), IntArg(0, 100), Arg()],
+        )
+
+    @nonfunctional_tooslow
+    def test_legenq_complex(self):
+        def lqnm(n, m, z):
+            return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1]
+
+        def legenq(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2)
+
+        assert_mpmath_equal(
+            lqnm,
+            legenq,
+            [IntArg(0, 100), IntArg(0, 100), ComplexArg()],
+            n=100,
+        )
+
+    def test_lgam1p(self):
+        def param_filter(x):
+            # Filter the poles
+            return np.where((np.floor(x) == x) & (x <= 0), False, True)
+
+        def mp_lgam1p(z):
+            # The real part of loggamma is log(|gamma(z)|)
+            return mpmath.loggamma(1 + z).real
+
+        assert_mpmath_equal(
+            _lgam1p,
+            mp_lgam1p,
+            [Arg()],
+            rtol=1e-13,
+            dps=100,
+            param_filter=param_filter,
+        )
+
+    def test_loggamma(self):
+        def mpmath_loggamma(z):
+            try:
+                res = mpmath.loggamma(z)
+            except ValueError:
+                res = complex(np.nan, np.nan)
+            return res
+
+        assert_mpmath_equal(
+            sc.loggamma,
+            mpmath_loggamma,
+            [ComplexArg()],
+            nan_ok=False,
+            distinguish_nan_and_inf=False,
+            rtol=5e-14,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_pcfd(self):
+        def pcfd(v, x):
+            return sc.pbdv(v, x)[0]
+        assert_mpmath_equal(
+            pcfd,
+            exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)),
+            [Arg(), Arg()],
+        )
+
+    @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- "
+                                         "maybe different definition?")
+    def test_pcfv(self):
+        def pcfv(v, x):
+            return sc.pbvv(v, x)[0]
+        assert_mpmath_equal(
+            pcfv,
+            lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW),
+            [Arg(), Arg()],
+            n=1000,
+        )
+
+    def test_pcfw(self):
+        def pcfw(a, x):
+            return sc.pbwa(a, x)[0]
+
+        def dpcfw(a, x):
+            return sc.pbwa(a, x)[1]
+
+        def mpmath_dpcfw(a, x):
+            return mpmath.diff(mpmath.pcfw, (a, x), (0, 1))
+
+        # The Zhang and Jin implementation only uses Taylor series and
+        # is thus accurate in only a very small range.
+        assert_mpmath_equal(
+            pcfw,
+            mpmath.pcfw,
+            [Arg(-5, 5), Arg(-5, 5)],
+            rtol=2e-8,
+            n=100,
+        )
+
+        assert_mpmath_equal(
+            dpcfw,
+            mpmath_dpcfw,
+            [Arg(-5, 5), Arg(-5, 5)],
+            rtol=2e-9,
+            n=100,
+        )
+
+    @pytest.mark.xfail(run=False,
+                       reason="issues at large arguments (atol OK, rtol not) "
+                              "and = _pep440.Version("1.0.0"):
+            # no workarounds needed
+            mppoch = mpmath.rf
+        else:
+            def mppoch(a, m):
+                # deal with cases where the result in double precision
+                # hits exactly a non-positive integer, but the
+                # corresponding extended-precision mpf floats don't
+                if float(a + m) == int(a + m) and float(a + m) <= 0:
+                    a = mpmath.mpf(a)
+                    m = int(a + m) - a
+                return mpmath.rf(a, m)
+
+        assert_mpmath_equal(sc.poch, mppoch, [Arg(), Arg()], dps=400)
+
+    def test_sinpi(self):
+        eps = np.finfo(float).eps
+        assert_mpmath_equal(
+            _sinpi,
+            mpmath.sinpi,
+            [Arg()],
+            nan_ok=False,
+            rtol=2*eps,
+        )
+
+    def test_sinpi_complex(self):
+        assert_mpmath_equal(
+            _sinpi,
+            mpmath.sinpi,
+            [ComplexArg()],
+            nan_ok=False,
+            rtol=2e-14,
+        )
+
+    def test_shi(self):
+        def shi(x):
+            return sc.shichi(x)[0]
+        assert_mpmath_equal(shi, mpmath.shi, [Arg()])
+        # check asymptotic series cross-over
+        assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
+
+    def test_shi_complex(self):
+        def shi(z):
+            return sc.shichi(z)[0]
+        # shi oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            shi,
+            mpmath.shi,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-12,
+        )
+
+    def test_si(self):
+        def si(x):
+            return sc.sici(x)[0]
+        assert_mpmath_equal(si, mpmath.si, [Arg()])
+
+    def test_si_complex(self):
+        def si(z):
+            return sc.sici(z)[0]
+        # si oscillates as Re[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            si,
+            mpmath.si,
+            [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
+            rtol=1e-12,
+        )
+
+    def test_spence(self):
+        # mpmath uses a different convention for the dilogarithm
+        def dilog(x):
+            return mpmath.polylog(2, 1 - x)
+        # Spence has a branch cut on the negative real axis
+        assert_mpmath_equal(
+            sc.spence,
+            exception_to_nan(dilog),
+            [Arg(0, np.inf)],
+            rtol=1e-14,
+        )
+
+    def test_spence_complex(self):
+        def dilog(z):
+            return mpmath.polylog(2, 1 - z)
+        assert_mpmath_equal(
+            sc.spence,
+            exception_to_nan(dilog),
+            [ComplexArg()],
+            rtol=1e-14,
+        )
+
+    def test_spherharm(self):
+        def spherharm(l, m, theta, phi):
+            if m > l:
+                return np.nan
+            with suppress_warnings() as sup:
+                sup.filter(category=DeprecationWarning)
+                return sc.sph_harm(m, l, phi, theta)
+        assert_mpmath_equal(
+            spherharm,
+            mpmath.spherharm,
+            [IntArg(0, 100), IntArg(0, 100), Arg(a=0, b=pi), Arg(a=0, b=2*pi)],
+            atol=1e-8,
+            n=6000,
+            dps=150,
+        )
+
+    def test_struveh(self):
+        assert_mpmath_equal(
+            sc.struve,
+            exception_to_nan(mpmath.struveh),
+            [Arg(-1e4, 1e4), Arg(0, 1e4)],
+            rtol=5e-10,
+        )
+
+    def test_struvel(self):
+        def mp_struvel(v, z):
+            if v < 0 and z < -v and abs(v) > 1000:
+                # larger DPS needed for correct results
+                old_dps = mpmath.mp.dps
+                try:
+                    mpmath.mp.dps = 500
+                    return mpmath.struvel(v, z)
+                finally:
+                    mpmath.mp.dps = old_dps
+            return mpmath.struvel(v, z)
+
+        assert_mpmath_equal(
+            sc.modstruve,
+            exception_to_nan(mp_struvel),
+            [Arg(-1e4, 1e4), Arg(0, 1e4)],
+            rtol=5e-10,
+            ignore_inf_sign=True,
+        )
+
+    def test_wrightomega_real(self):
+        def mpmath_wrightomega_real(x):
+            return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
+
+        # For x < -1000 the Wright Omega function is just 0 to double
+        # precision, and for x > 1e21 it is just x to double
+        # precision.
+        assert_mpmath_equal(
+            sc.wrightomega,
+            mpmath_wrightomega_real,
+            [Arg(-1000, 1e21)],
+            rtol=5e-15,
+            atol=0,
+            nan_ok=False,
+        )
+
+    def test_wrightomega(self):
+        assert_mpmath_equal(
+            sc.wrightomega,
+            lambda z: _mpmath_wrightomega(z, 25),
+            [ComplexArg()],
+            rtol=1e-14,
+            nan_ok=False,
+        )
+
+    def test_hurwitz_zeta(self):
+        assert_mpmath_equal(
+            sc.zeta,
+            exception_to_nan(mpmath.zeta),
+            [Arg(a=1, b=1e10, inclusive_a=False), Arg(a=0, inclusive_a=False)],
+        )
+
+    def test_riemann_zeta(self):
+        assert_mpmath_equal(
+            sc.zeta,
+            lambda x: mpmath.zeta(x) if x != 1 else mpmath.inf,
+            [Arg(-100, 100)],
+            nan_ok=False,
+            rtol=5e-13,
+        )
+
+    def test_zetac(self):
+        assert_mpmath_equal(
+            sc.zetac,
+            lambda x: mpmath.zeta(x) - 1 if x != 1 else mpmath.inf,
+            [Arg(-100, 100)],
+            nan_ok=False,
+            dps=45,
+            rtol=5e-13,
+        )
+
+    def test_boxcox(self):
+
+        def mp_boxcox(x, lmbda):
+            x = mpmath.mp.mpf(x)
+            lmbda = mpmath.mp.mpf(lmbda)
+            if lmbda == 0:
+                return mpmath.mp.log(x)
+            else:
+                return mpmath.mp.powm1(x, lmbda) / lmbda
+
+        assert_mpmath_equal(
+            sc.boxcox,
+            exception_to_nan(mp_boxcox),
+            [Arg(a=0, inclusive_a=False), Arg()],
+            n=200,
+            dps=60,
+            rtol=1e-13,
+        )
+
+    def test_boxcox1p(self):
+
+        def mp_boxcox1p(x, lmbda):
+            x = mpmath.mp.mpf(x)
+            lmbda = mpmath.mp.mpf(lmbda)
+            one = mpmath.mp.mpf(1)
+            if lmbda == 0:
+                return mpmath.mp.log(one + x)
+            else:
+                return mpmath.mp.powm1(one + x, lmbda) / lmbda
+
+        assert_mpmath_equal(
+            sc.boxcox1p,
+            exception_to_nan(mp_boxcox1p),
+            [Arg(a=-1, inclusive_a=False), Arg()],
+            n=200,
+            dps=60,
+            rtol=1e-13,
+        )
+
+    def test_spherical_jn(self):
+        def mp_spherical_jn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_jn(int(n), z),
+            exception_to_nan(mp_spherical_jn),
+            [IntArg(0, 200), Arg(-1e8, 1e8)],
+            dps=300,
+            # underflow of `spherical_jn` is a bit premature; see gh-21629
+            param_filter=(None, lambda z: np.abs(z) > 1e-20),
+        )
+
+    def test_spherical_jn_complex(self):
+        def mp_spherical_jn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_jn(int(n.real), z),
+            exception_to_nan(mp_spherical_jn),
+            [IntArg(0, 200), ComplexArg()]
+        )
+
+    def test_spherical_yn(self):
+        def mp_spherical_yn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_yn(int(n), z),
+            exception_to_nan(mp_spherical_yn),
+            [IntArg(0, 200), Arg(-1e10, 1e10)],
+            dps=100,
+        )
+
+    def test_spherical_yn_complex(self):
+        def mp_spherical_yn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_yn(int(n.real), z),
+            exception_to_nan(mp_spherical_yn),
+            [IntArg(0, 200), ComplexArg()],
+        )
+
+    def test_spherical_in(self):
+        def mp_spherical_in(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_in(int(n), z),
+            exception_to_nan(mp_spherical_in),
+            [IntArg(0, 200), Arg()],
+            dps=200,
+            atol=10**(-278),
+        )
+
+    def test_spherical_in_complex(self):
+        def mp_spherical_in(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_in(int(n.real), z),
+            exception_to_nan(mp_spherical_in),
+            [IntArg(0, 200), ComplexArg()],
+        )
+
+    def test_spherical_kn(self):
+        def mp_spherical_kn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if mpmath.mpmathify(z).imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_kn(int(n), z),
+            exception_to_nan(mp_spherical_kn),
+            [IntArg(0, 150), Arg()],
+            dps=100,
+        )
+
+    @pytest.mark.xfail(run=False,
+                       reason="Accuracy issues near z = -1 inherited from kv.")
+    def test_spherical_kn_complex(self):
+        def mp_spherical_kn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_kn(int(n.real), z),
+            exception_to_nan(mp_spherical_kn),
+            [IntArg(0, 200), ComplexArg()],
+            dps=200,
+        )
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3e574da056bc9ba7d472567caf992d6638c20a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py
@@ -0,0 +1,65 @@
+"""Test how the ufuncs in special handle nan inputs.
+
+"""
+from typing import Callable
+
+import numpy as np
+from numpy.testing import assert_array_equal, assert_, suppress_warnings
+import pytest
+import scipy.special as sc
+
+
+KNOWNFAILURES: dict[str, Callable] = {}
+
+POSTPROCESSING: dict[str, Callable] = {}
+
+
+def _get_ufuncs():
+    ufuncs = []
+    ufunc_names = []
+    for name in sorted(sc.__dict__):
+        obj = sc.__dict__[name]
+        if not isinstance(obj, np.ufunc):
+            continue
+        msg = KNOWNFAILURES.get(obj)
+        if msg is None:
+            ufuncs.append(obj)
+            ufunc_names.append(name)
+        else:
+            fail = pytest.mark.xfail(run=False, reason=msg)
+            ufuncs.append(pytest.param(obj, marks=fail))
+            ufunc_names.append(name)
+    return ufuncs, ufunc_names
+
+
+UFUNCS, UFUNC_NAMES = _get_ufuncs()
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize("func", UFUNCS, ids=UFUNC_NAMES)
+def test_nan_inputs(func):
+    args = (np.nan,)*func.nin
+    with suppress_warnings() as sup:
+        # Ignore warnings about unsafe casts from legacy wrappers
+        sup.filter(RuntimeWarning,
+                   "floating point number truncated to an integer")
+        try:
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning)
+                res = func(*args)
+        except TypeError:
+            # One of the arguments doesn't take real inputs
+            return
+    if func in POSTPROCESSING:
+        res = POSTPROCESSING[func](*res)
+
+    msg = f"got {res} instead of nan"
+    assert_array_equal(np.isnan(res), True, err_msg=msg)
+
+
+def test_legacy_cast():
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning,
+                   "floating point number truncated to an integer")
+        res = sc.bdtrc(np.nan, 1, 0.5)
+        assert_(np.isnan(res))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba9b689b34384585cc65204000febcb99c910d55
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py
@@ -0,0 +1,77 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+import scipy.special as sc
+
+
+def test_ndtr():
+    assert_equal(sc.ndtr(0), 0.5)
+    assert_allclose(sc.ndtr(1), 0.8413447460685429)
+
+
+class TestNdtri:
+
+    def test_zero(self):
+        assert sc.ndtri(0.5) == 0.0
+
+    def test_asymptotes(self):
+        assert_equal(sc.ndtri([0.0, 1.0]), [-np.inf, np.inf])
+
+    def test_outside_of_domain(self):
+        assert all(np.isnan(sc.ndtri([-1.5, 1.5])))
+
+
+class TestLogNdtr:
+
+    # The expected values in these tests were computed with mpmath:
+    #
+    #   def log_ndtr_mp(x):
+    #       return mpmath.log(mpmath.ncdf(x))
+    #
+
+    def test_log_ndtr_moderate_le8(self):
+        x = np.array([-0.75, -0.25, 0, 0.5, 1.5, 2.5, 3, 4, 5, 7, 8])
+        expected = np.array([-1.4844482299196562,
+                             -0.9130617648111351,
+                             -0.6931471805599453,
+                             -0.3689464152886564,
+                             -0.06914345561223398,
+                             -0.006229025485860002,
+                             -0.0013508099647481938,
+                             -3.167174337748927e-05,
+                             -2.866516129637636e-07,
+                             -1.279812543886654e-12,
+                             -6.220960574271786e-16])
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=1e-14)
+
+    def test_log_ndtr_values_8_16(self):
+        x = np.array([8.001, 8.06, 8.15, 8.5, 10, 12, 14, 16])
+        expected = [-6.170639424817055e-16,
+                    -3.814722443652823e-16,
+                    -1.819621363526629e-16,
+                    -9.479534822203318e-18,
+                    -7.619853024160525e-24,
+                    -1.776482112077679e-33,
+                    -7.7935368191928e-45,
+                    -6.388754400538087e-58]
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=5e-14)
+
+    def test_log_ndtr_values_16_31(self):
+        x = np.array([16.15, 20.3, 21.4, 26.2, 30.9])
+        expected = [-5.678084565148492e-59,
+                    -6.429244467698346e-92,
+                    -6.680402412553295e-102,
+                    -1.328698078458869e-151,
+                    -5.972288641838264e-210]
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=2e-13)
+
+    def test_log_ndtr_values_gt31(self):
+        x = np.array([31.6, 32.8, 34.9, 37.1])
+        expected = [-1.846036234858162e-219,
+                    -2.9440539964066835e-236,
+                    -3.71721649450857e-267,
+                    -1.4047119663106221e-301]
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=3e-13)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a9fbd3bcda117770e00018facda3f56630a6bc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py
@@ -0,0 +1,94 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy.special import log_ndtr, ndtri_exp
+from scipy.special._testutils import assert_func_equal
+
+
+def log_ndtr_ndtri_exp(y):
+    return log_ndtr(ndtri_exp(y))
+
+
+@pytest.fixture(scope="class")
+def uniform_random_points():
+    random_state = np.random.RandomState(1234)
+    points = random_state.random_sample(1000)
+    return points
+
+
+class TestNdtriExp:
+    """Tests that ndtri_exp is sufficiently close to an inverse of log_ndtr.
+
+    We have separate tests for the five intervals (-inf, -10),
+    [-10, -2), [-2, -0.14542), [-0.14542, -1e-6), and [-1e-6, 0).
+    ndtri_exp(y) is computed in three different ways depending on if y
+    is in (-inf, -2), [-2, log(1 - exp(-2))], or [log(1 - exp(-2), 0).
+    Each of these intervals is given its own test with two additional tests
+    for handling very small values and values very close to zero.
+    """
+
+    @pytest.mark.parametrize(
+        "test_input", [-1e1, -1e2, -1e10, -1e20, -np.finfo(float).max]
+    )
+    def test_very_small_arg(self, test_input, uniform_random_points):
+        scale = test_input
+        points = scale * (0.5 * uniform_random_points + 0.5)
+        assert_func_equal(
+            log_ndtr_ndtri_exp,
+            lambda y: y, points,
+            rtol=1e-14,
+            nan_ok=True
+        )
+
+    @pytest.mark.parametrize(
+        "interval,expected_rtol",
+        [
+            ((-10, -2), 1e-14),
+            ((-2, -0.14542), 1e-12),
+            ((-0.14542, -1e-6), 1e-10),
+            ((-1e-6, 0), 1e-6),
+        ],
+    )
+    def test_in_interval(self, interval, expected_rtol, uniform_random_points):
+        left, right = interval
+        points = (right - left) * uniform_random_points + left
+        assert_func_equal(
+            log_ndtr_ndtri_exp,
+            lambda y: y, points,
+            rtol=expected_rtol,
+            nan_ok=True
+        )
+
+    def test_extreme(self):
+        # bigneg is not quite the largest negative double precision value.
+        # Here's why:
+        # The round-trip calculation
+        #    y = ndtri_exp(bigneg)
+        #    bigneg2 = log_ndtr(y)
+        # where bigneg is a very large negative value, would--with infinite
+        # precision--result in bigneg2 == bigneg.  When bigneg is large enough,
+        # y is effectively equal to -sqrt(2)*sqrt(-bigneg), and log_ndtr(y) is
+        # effectively -(y/sqrt(2))**2.  If we use bigneg = np.finfo(float).min,
+        # then by construction, the theoretical value is the most negative
+        # finite value that can be represented with 64 bit float point.  This
+        # means tiny changes in how the computation proceeds can result in the
+        # return value being -inf.  (E.g. changing the constant representation
+        # of 1/sqrt(2) from 0.7071067811865475--which is the value returned by
+        # 1/np.sqrt(2)--to 0.7071067811865476--which is the most accurate 64
+        # bit floating point representation of 1/sqrt(2)--results in the
+        # round-trip that starts with np.finfo(float).min returning -inf.  So
+        # we'll move the bigneg value a few ULPs towards 0 to avoid this
+        # sensitivity.
+        # Use the reduce method to apply nextafter four times.
+        bigneg = np.nextafter.reduce([np.finfo(float).min, 0, 0, 0, 0])
+        # tinyneg is approx. -2.225e-308.
+        tinyneg = -np.finfo(float).tiny
+        x = np.array([tinyneg, bigneg])
+        result = log_ndtr_ndtri_exp(x)
+        assert_allclose(result, x, rtol=1e-12)
+
+    def test_asymptotes(self):
+        assert_equal(ndtri_exp([-np.inf, 0.0]), [-np.inf, np.inf])
+
+    def test_outside_domain(self):
+        assert np.isnan(ndtri_exp(1.0))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..47831c18ab6fa48925cae576f6c664767df99d05
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py
@@ -0,0 +1,822 @@
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import array, sqrt
+from numpy.testing import (assert_array_almost_equal, assert_equal,
+                           assert_almost_equal, assert_allclose)
+
+from scipy import integrate
+import scipy.special as sc
+from scipy.special import gamma
+import scipy.special._orthogonal as orth
+
+
+class TestCheby:
+    def test_chebyc(self):
+        C0 = orth.chebyc(0)
+        C1 = orth.chebyc(1)
+        with np.errstate(all='ignore'):
+            C2 = orth.chebyc(2)
+            C3 = orth.chebyc(3)
+            C4 = orth.chebyc(4)
+            C5 = orth.chebyc(5)
+
+        assert_array_almost_equal(C0.c,[2],13)
+        assert_array_almost_equal(C1.c,[1,0],13)
+        assert_array_almost_equal(C2.c,[1,0,-2],13)
+        assert_array_almost_equal(C3.c,[1,0,-3,0],13)
+        assert_array_almost_equal(C4.c,[1,0,-4,0,2],13)
+        assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13)
+
+    def test_chebys(self):
+        S0 = orth.chebys(0)
+        S1 = orth.chebys(1)
+        S2 = orth.chebys(2)
+        S3 = orth.chebys(3)
+        S4 = orth.chebys(4)
+        S5 = orth.chebys(5)
+        assert_array_almost_equal(S0.c,[1],13)
+        assert_array_almost_equal(S1.c,[1,0],13)
+        assert_array_almost_equal(S2.c,[1,0,-1],13)
+        assert_array_almost_equal(S3.c,[1,0,-2,0],13)
+        assert_array_almost_equal(S4.c,[1,0,-3,0,1],13)
+        assert_array_almost_equal(S5.c,[1,0,-4,0,3,0],13)
+
+    def test_chebyt(self):
+        T0 = orth.chebyt(0)
+        T1 = orth.chebyt(1)
+        T2 = orth.chebyt(2)
+        T3 = orth.chebyt(3)
+        T4 = orth.chebyt(4)
+        T5 = orth.chebyt(5)
+        assert_array_almost_equal(T0.c,[1],13)
+        assert_array_almost_equal(T1.c,[1,0],13)
+        assert_array_almost_equal(T2.c,[2,0,-1],13)
+        assert_array_almost_equal(T3.c,[4,0,-3,0],13)
+        assert_array_almost_equal(T4.c,[8,0,-8,0,1],13)
+        assert_array_almost_equal(T5.c,[16,0,-20,0,5,0],13)
+
+    def test_chebyu(self):
+        U0 = orth.chebyu(0)
+        U1 = orth.chebyu(1)
+        U2 = orth.chebyu(2)
+        U3 = orth.chebyu(3)
+        U4 = orth.chebyu(4)
+        U5 = orth.chebyu(5)
+        assert_array_almost_equal(U0.c,[1],13)
+        assert_array_almost_equal(U1.c,[2,0],13)
+        assert_array_almost_equal(U2.c,[4,0,-1],13)
+        assert_array_almost_equal(U3.c,[8,0,-4,0],13)
+        assert_array_almost_equal(U4.c,[16,0,-12,0,1],13)
+        assert_array_almost_equal(U5.c,[32,0,-32,0,6,0],13)
+
+
+class TestGegenbauer:
+
+    def test_gegenbauer(self):
+        a = 5*np.random.random() - 0.5
+        if np.any(a == 0):
+            a = -0.2
+        Ca0 = orth.gegenbauer(0,a)
+        Ca1 = orth.gegenbauer(1,a)
+        Ca2 = orth.gegenbauer(2,a)
+        Ca3 = orth.gegenbauer(3,a)
+        Ca4 = orth.gegenbauer(4,a)
+        Ca5 = orth.gegenbauer(5,a)
+
+        assert_array_almost_equal(Ca0.c,array([1]),13)
+        assert_array_almost_equal(Ca1.c,array([2*a,0]),13)
+        assert_array_almost_equal(Ca2.c,array([2*a*(a+1),0,-a]),13)
+        assert_array_almost_equal(Ca3.c,array([4*sc.poch(a,3),0,-6*a*(a+1),
+                                               0])/3.0,11)
+        assert_array_almost_equal(Ca4.c,array([4*sc.poch(a,4),0,-12*sc.poch(a,3),
+                                               0,3*a*(a+1)])/6.0,11)
+        assert_array_almost_equal(Ca5.c,array([4*sc.poch(a,5),0,-20*sc.poch(a,4),
+                                               0,15*sc.poch(a,3),0])/15.0,11)
+
+    @pytest.mark.parametrize('a', [0, 1])
+    def test_n_zero_gh8888(self, a):
+        # gh-8888 reported that gegenbauer(0, 0) returns NaN polynomial
+        Cn0 = orth.gegenbauer(0, a)
+        assert_equal(Cn0.c, np.asarray([1.]))
+
+    def test_valid_alpha(self):
+        # Check input validation of `alpha`
+        message = '`alpha` must be a finite number greater...'
+        with pytest.raises(ValueError, match=message):
+            orth.gegenbauer(0, np.nan)
+        with pytest.raises(ValueError, match=message):
+            orth.gegenbauer(1, -0.5)
+        with pytest.raises(ValueError, match=message):
+            orth.gegenbauer(2, -np.inf)
+
+
+class TestHermite:
+    def test_hermite(self):
+        H0 = orth.hermite(0)
+        H1 = orth.hermite(1)
+        H2 = orth.hermite(2)
+        H3 = orth.hermite(3)
+        H4 = orth.hermite(4)
+        H5 = orth.hermite(5)
+        assert_array_almost_equal(H0.c,[1],13)
+        assert_array_almost_equal(H1.c,[2,0],13)
+        assert_array_almost_equal(H2.c,[4,0,-2],13)
+        assert_array_almost_equal(H3.c,[8,0,-12,0],13)
+        assert_array_almost_equal(H4.c,[16,0,-48,0,12],12)
+        assert_array_almost_equal(H5.c,[32,0,-160,0,120,0],12)
+
+    def test_hermitenorm(self):
+        # He_n(x) = 2**(-n/2) H_n(x/sqrt(2))
+        psub = np.poly1d([1.0/sqrt(2),0])
+        H0 = orth.hermitenorm(0)
+        H1 = orth.hermitenorm(1)
+        H2 = orth.hermitenorm(2)
+        H3 = orth.hermitenorm(3)
+        H4 = orth.hermitenorm(4)
+        H5 = orth.hermitenorm(5)
+        he0 = orth.hermite(0)(psub)
+        he1 = orth.hermite(1)(psub) / sqrt(2)
+        he2 = orth.hermite(2)(psub) / 2.0
+        he3 = orth.hermite(3)(psub) / (2*sqrt(2))
+        he4 = orth.hermite(4)(psub) / 4.0
+        he5 = orth.hermite(5)(psub) / (4.0*sqrt(2))
+
+        assert_array_almost_equal(H0.c,he0.c,13)
+        assert_array_almost_equal(H1.c,he1.c,13)
+        assert_array_almost_equal(H2.c,he2.c,13)
+        assert_array_almost_equal(H3.c,he3.c,13)
+        assert_array_almost_equal(H4.c,he4.c,13)
+        assert_array_almost_equal(H5.c,he5.c,13)
+
+
+class TestShLegendre:
+    def test_sh_legendre(self):
+        # P*_n(x) = P_n(2x-1)
+        psub = np.poly1d([2,-1])
+        Ps0 = orth.sh_legendre(0)
+        Ps1 = orth.sh_legendre(1)
+        Ps2 = orth.sh_legendre(2)
+        Ps3 = orth.sh_legendre(3)
+        Ps4 = orth.sh_legendre(4)
+        Ps5 = orth.sh_legendre(5)
+        pse0 = orth.legendre(0)(psub)
+        pse1 = orth.legendre(1)(psub)
+        pse2 = orth.legendre(2)(psub)
+        pse3 = orth.legendre(3)(psub)
+        pse4 = orth.legendre(4)(psub)
+        pse5 = orth.legendre(5)(psub)
+        assert_array_almost_equal(Ps0.c,pse0.c,13)
+        assert_array_almost_equal(Ps1.c,pse1.c,13)
+        assert_array_almost_equal(Ps2.c,pse2.c,13)
+        assert_array_almost_equal(Ps3.c,pse3.c,13)
+        assert_array_almost_equal(Ps4.c,pse4.c,12)
+        assert_array_almost_equal(Ps5.c,pse5.c,12)
+
+
+class TestShChebyt:
+    def test_sh_chebyt(self):
+        # T*_n(x) = T_n(2x-1)
+        psub = np.poly1d([2,-1])
+        Ts0 = orth.sh_chebyt(0)
+        Ts1 = orth.sh_chebyt(1)
+        Ts2 = orth.sh_chebyt(2)
+        Ts3 = orth.sh_chebyt(3)
+        Ts4 = orth.sh_chebyt(4)
+        Ts5 = orth.sh_chebyt(5)
+        tse0 = orth.chebyt(0)(psub)
+        tse1 = orth.chebyt(1)(psub)
+        tse2 = orth.chebyt(2)(psub)
+        tse3 = orth.chebyt(3)(psub)
+        tse4 = orth.chebyt(4)(psub)
+        tse5 = orth.chebyt(5)(psub)
+        assert_array_almost_equal(Ts0.c,tse0.c,13)
+        assert_array_almost_equal(Ts1.c,tse1.c,13)
+        assert_array_almost_equal(Ts2.c,tse2.c,13)
+        assert_array_almost_equal(Ts3.c,tse3.c,13)
+        assert_array_almost_equal(Ts4.c,tse4.c,12)
+        assert_array_almost_equal(Ts5.c,tse5.c,12)
+
+
+class TestShChebyu:
+    def test_sh_chebyu(self):
+        # U*_n(x) = U_n(2x-1)
+        psub = np.poly1d([2,-1])
+        Us0 = orth.sh_chebyu(0)
+        Us1 = orth.sh_chebyu(1)
+        Us2 = orth.sh_chebyu(2)
+        Us3 = orth.sh_chebyu(3)
+        Us4 = orth.sh_chebyu(4)
+        Us5 = orth.sh_chebyu(5)
+        use0 = orth.chebyu(0)(psub)
+        use1 = orth.chebyu(1)(psub)
+        use2 = orth.chebyu(2)(psub)
+        use3 = orth.chebyu(3)(psub)
+        use4 = orth.chebyu(4)(psub)
+        use5 = orth.chebyu(5)(psub)
+        assert_array_almost_equal(Us0.c,use0.c,13)
+        assert_array_almost_equal(Us1.c,use1.c,13)
+        assert_array_almost_equal(Us2.c,use2.c,13)
+        assert_array_almost_equal(Us3.c,use3.c,13)
+        assert_array_almost_equal(Us4.c,use4.c,12)
+        assert_array_almost_equal(Us5.c,use5.c,11)
+
+
+class TestShJacobi:
+    def test_sh_jacobi(self):
+        # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1)
+        def conv(n, p):
+            return gamma(n + 1) * gamma(n + p) / gamma(2 * n + p)
+        psub = np.poly1d([2,-1])
+        q = 4 * np.random.random()
+        p = q-1 + 2*np.random.random()
+        # print("shifted jacobi p,q = ", p, q)
+        G0 = orth.sh_jacobi(0,p,q)
+        G1 = orth.sh_jacobi(1,p,q)
+        G2 = orth.sh_jacobi(2,p,q)
+        G3 = orth.sh_jacobi(3,p,q)
+        G4 = orth.sh_jacobi(4,p,q)
+        G5 = orth.sh_jacobi(5,p,q)
+        ge0 = orth.jacobi(0,p-q,q-1)(psub) * conv(0,p)
+        ge1 = orth.jacobi(1,p-q,q-1)(psub) * conv(1,p)
+        ge2 = orth.jacobi(2,p-q,q-1)(psub) * conv(2,p)
+        ge3 = orth.jacobi(3,p-q,q-1)(psub) * conv(3,p)
+        ge4 = orth.jacobi(4,p-q,q-1)(psub) * conv(4,p)
+        ge5 = orth.jacobi(5,p-q,q-1)(psub) * conv(5,p)
+
+        assert_array_almost_equal(G0.c,ge0.c,13)
+        assert_array_almost_equal(G1.c,ge1.c,13)
+        assert_array_almost_equal(G2.c,ge2.c,13)
+        assert_array_almost_equal(G3.c,ge3.c,13)
+        assert_array_almost_equal(G4.c,ge4.c,13)
+        assert_array_almost_equal(G5.c,ge5.c,13)
+
+
+class TestCall:
+    def test_call(self):
+        poly = []
+        for n in range(5):
+            poly.extend([x.strip() for x in
+                ("""
+                orth.jacobi(%(n)d,0.3,0.9)
+                orth.sh_jacobi(%(n)d,0.3,0.9)
+                orth.genlaguerre(%(n)d,0.3)
+                orth.laguerre(%(n)d)
+                orth.hermite(%(n)d)
+                orth.hermitenorm(%(n)d)
+                orth.gegenbauer(%(n)d,0.3)
+                orth.chebyt(%(n)d)
+                orth.chebyu(%(n)d)
+                orth.chebyc(%(n)d)
+                orth.chebys(%(n)d)
+                orth.sh_chebyt(%(n)d)
+                orth.sh_chebyu(%(n)d)
+                orth.legendre(%(n)d)
+                orth.sh_legendre(%(n)d)
+                """ % dict(n=n)).split()
+            ])
+        with np.errstate(all='ignore'):
+            for pstr in poly:
+                p = eval(pstr)
+                assert_almost_equal(p(0.315), np.poly1d(p.coef)(0.315),
+                                    err_msg=pstr)
+
+
+class TestGenlaguerre:
+    def test_regression(self):
+        assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.)
+        assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.)
+        assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2]))
+        assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1, -2]))
+
+
+def verify_gauss_quad(root_func, eval_func, weight_func, a, b, N,
+                      rtol=1e-15, atol=5e-14):
+    # this test is copied from numpy's TestGauss in test_hermite.py
+    x, w, mu = root_func(N, True)
+
+    n = np.arange(N, dtype=np.dtype("long"))
+    v = eval_func(n[:,np.newaxis], x)
+    vv = np.dot(v*w, v.T)
+    vd = 1 / np.sqrt(vv.diagonal())
+    vv = vd[:, np.newaxis] * vv * vd
+    assert_allclose(vv, np.eye(N), rtol, atol)
+
+    # check that the integral of 1 is correct
+    assert_allclose(w.sum(), mu, rtol, atol)
+
+    # compare the results of integrating a function with quad.
+    def f(x):
+        return x ** 3 - 3 * x ** 2 + x - 2
+    resI = integrate.quad(lambda x: f(x)*weight_func(x), a, b)
+    resG = np.vdot(f(x), w)
+    rtol = 1e-6 if 1e-6 < resI[1] else resI[1] * 10
+    assert_allclose(resI[0], resG, rtol=rtol)
+
+def test_roots_jacobi():
+    def rf(a, b):
+        return lambda n, mu: sc.roots_jacobi(n, a, b, mu)
+    def ef(a, b):
+        return lambda n, x: sc.eval_jacobi(n, a, b, x)
+    def wf(a, b):
+        return lambda x: (1 - x) ** a * (1 + x) ** b
+
+    vgq = verify_gauss_quad
+    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., 5)
+    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1.,
+        25, atol=1e-12)
+    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1.,
+        100, atol=1e-11)
+
+    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 5)
+    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 25, atol=1.5e-13)
+    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 100, atol=2e-12)
+
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 5, atol=2e-13)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 25, atol=2e-13)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 100, atol=1e-12)
+
+    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 5)
+    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 25, atol=1e-13)
+    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 100, atol=3e-13)
+
+    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 5)
+    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 25,
+        atol=1.1e-14)
+    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1.,
+        100, atol=1e-13)
+
+    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 5, atol=1e-13)
+    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 25, atol=2e-13)
+    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1.,
+        100, atol=1e-11)
+
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 5, atol=2e-13)
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 25, atol=1e-12)
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 100, atol=1e-11)
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 250, atol=1e-11)
+
+    vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 5,
+        atol=1e-12)
+    vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 25,
+        atol=1e-11)
+    vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 100,
+        atol=1e-10)
+
+    vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 5,
+        atol=1e-12)
+    vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 25,
+        atol=1e-11)
+    vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 100,
+        atol=1e-10)
+
+    vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 5,
+        atol=1e-12)
+    vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 25,
+        atol=1e-11)
+    vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 100,
+        atol=1e-10)
+
+    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 5)
+    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 25,
+        atol=1e-13)
+    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 100,
+        atol=1e-13)
+
+    # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
+    xj, wj = sc.roots_jacobi(6, 0.0, 0.0)
+    xl, wl = sc.roots_legendre(6)
+    assert_allclose(xj, xl, 1e-14, 1e-14)
+    assert_allclose(wj, wl, 1e-14, 1e-14)
+
+    # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
+    xj, wj = sc.roots_jacobi(6, 4.0, 4.0)
+    xc, wc = sc.roots_gegenbauer(6, 4.5)
+    assert_allclose(xj, xc, 1e-14, 1e-14)
+    assert_allclose(wj, wc, 1e-14, 1e-14)
+
+    x, w = sc.roots_jacobi(5, 2, 3, False)
+    y, v, m = sc.roots_jacobi(5, 2, 3, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(wf(2,3), -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_jacobi, 0, 1, 1)
+    assert_raises(ValueError, sc.roots_jacobi, 3.3, 1, 1)
+    assert_raises(ValueError, sc.roots_jacobi, 3, -2, 1)
+    assert_raises(ValueError, sc.roots_jacobi, 3, 1, -2)
+    assert_raises(ValueError, sc.roots_jacobi, 3, -2, -2)
+
+def test_roots_sh_jacobi():
+    def rf(a, b):
+        return lambda n, mu: sc.roots_sh_jacobi(n, a, b, mu)
+    def ef(a, b):
+        return lambda n, x: sc.eval_sh_jacobi(n, a, b, x)
+    def wf(a, b):
+        return lambda x: (1.0 - x) ** (a - b) * x ** (b - 1.0)
+
+    vgq = verify_gauss_quad
+    vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., 5)
+    vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1.,
+        25, atol=1e-12)
+    vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1.,
+        100, atol=1e-11)
+
+    vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 5)
+    vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 25, atol=1e-13)
+    vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 100, atol=1e-12)
+
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 5)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 25, atol=1.5e-13)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 100, atol=2e-12)
+
+    vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 5)
+    vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 25, atol=1e-13)
+    vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 100, atol=1e-12)
+
+    vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 5)
+    vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 25)
+    vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1.,
+        100, atol=1e-13)
+
+    vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 5, atol=1e-12)
+    vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 25, atol=1e-11)
+    vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 100, atol=1e-10)
+
+    vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 5, atol=3.5e-14)
+    vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 25, atol=2e-13)
+    vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1.,
+        100, atol=1e-12)
+
+    x, w = sc.roots_sh_jacobi(5, 3, 2, False)
+    y, v, m = sc.roots_sh_jacobi(5, 3, 2, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(wf(3,2), 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_jacobi, 0, 1, 1)
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3.3, 1, 1)
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3, 1, 2)    # p - q <= -1
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3, 2, -1)   # q <= 0
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3, -2, -1)  # both
+
+def test_roots_hermite():
+    rootf = sc.roots_hermite
+    evalf = sc.eval_hermite
+    weightf = orth.hermite(5).weight_func
+
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)
+
+    # Golub-Welsch branch
+    x, w = sc.roots_hermite(5, False)
+    y, v, m = sc.roots_hermite(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    # Asymptotic branch (switch over at n >= 150)
+    x, w = sc.roots_hermite(200, False)
+    y, v, m = sc.roots_hermite(200, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+    assert_allclose(sum(v), m, 1e-14, 1e-14)
+
+    assert_raises(ValueError, sc.roots_hermite, 0)
+    assert_raises(ValueError, sc.roots_hermite, 3.3)
+
+def test_roots_hermite_asy():
+    # Recursion for Hermite functions
+    def hermite_recursion(n, nodes):
+        H = np.zeros((n, nodes.size))
+        H[0,:] = np.pi**(-0.25) * np.exp(-0.5*nodes**2)
+        if n > 1:
+            H[1,:] = sqrt(2.0) * nodes * H[0,:]
+            for k in range(2, n):
+                H[k,:] = sqrt(2.0/k) * nodes * H[k-1,:] - sqrt((k-1.0)/k) * H[k-2,:]
+        return H
+
+    # This tests only the nodes
+    def test(N, rtol=1e-15, atol=1e-14):
+        x, w = orth._roots_hermite_asy(N)
+        H = hermite_recursion(N+1, x)
+        assert_allclose(H[-1,:], np.zeros(N), rtol, atol)
+        assert_allclose(sum(w), sqrt(np.pi), rtol, atol)
+
+    test(150, atol=1e-12)
+    test(151, atol=1e-12)
+    test(300, atol=1e-12)
+    test(301, atol=1e-12)
+    test(500, atol=1e-12)
+    test(501, atol=1e-12)
+    test(999, atol=1e-12)
+    test(1000, atol=1e-12)
+    test(2000, atol=1e-12)
+    test(5000, atol=1e-12)
+
+def test_roots_hermitenorm():
+    rootf = sc.roots_hermitenorm
+    evalf = sc.eval_hermitenorm
+    weightf = orth.hermitenorm(5).weight_func
+
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)
+
+    x, w = sc.roots_hermitenorm(5, False)
+    y, v, m = sc.roots_hermitenorm(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_hermitenorm, 0)
+    assert_raises(ValueError, sc.roots_hermitenorm, 3.3)
+
+def test_roots_gegenbauer():
+    def rootf(a):
+        return lambda n, mu: sc.roots_gegenbauer(n, a, mu)
+    def evalf(a):
+        return lambda n, x: sc.eval_gegenbauer(n, a, x)
+    def weightf(a):
+        return lambda x: (1 - x ** 2) ** (a - 0.5)
+
+    vgq = verify_gauss_quad
+    vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 5)
+    vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 25, atol=1e-12)
+    vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 100, atol=1e-11)
+
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 5)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 25, atol=1e-13)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 100, atol=1e-12)
+
+    vgq(rootf(1), evalf(1), weightf(1), -1., 1., 5)
+    vgq(rootf(1), evalf(1), weightf(1), -1., 1., 25, atol=1e-13)
+    vgq(rootf(1), evalf(1), weightf(1), -1., 1., 100, atol=1e-12)
+
+    vgq(rootf(10), evalf(10), weightf(10), -1., 1., 5)
+    vgq(rootf(10), evalf(10), weightf(10), -1., 1., 25, atol=1e-13)
+    vgq(rootf(10), evalf(10), weightf(10), -1., 1., 100, atol=1e-12)
+
+    vgq(rootf(50), evalf(50), weightf(50), -1., 1., 5, atol=1e-13)
+    vgq(rootf(50), evalf(50), weightf(50), -1., 1., 25, atol=1e-12)
+    vgq(rootf(50), evalf(50), weightf(50), -1., 1., 100, atol=1e-11)
+
+    # Alpha=170 is where the approximation used in roots_gegenbauer changes
+    vgq(rootf(170), evalf(170), weightf(170), -1., 1., 5, atol=1e-13)
+    vgq(rootf(170), evalf(170), weightf(170), -1., 1., 25, atol=1e-12)
+    vgq(rootf(170), evalf(170), weightf(170), -1., 1., 100, atol=1e-11)
+    vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 5, atol=1.25e-13)
+    vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 25, atol=1e-12)
+    vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 100, atol=1e-11)
+
+    # Test for failures, e.g. overflows, resulting from large alphas
+    vgq(rootf(238), evalf(238), weightf(238), -1., 1., 5, atol=1e-13)
+    vgq(rootf(238), evalf(238), weightf(238), -1., 1., 25, atol=1e-12)
+    vgq(rootf(238), evalf(238), weightf(238), -1., 1., 100, atol=1e-11)
+    vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 5, atol=1e-12)
+    vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 25, atol=1e-11)
+    vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 100, atol=1e-10)
+
+    # this is a special case that the old code supported.
+    # when alpha = 0, the gegenbauer polynomial is uniformly 0. but it goes
+    # to a scaled down copy of T_n(x) there.
+    vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 5)
+    vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 25)
+    vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 100, atol=1e-12)
+
+    x, w = sc.roots_gegenbauer(5, 2, False)
+    y, v, m = sc.roots_gegenbauer(5, 2, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf(2), -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_gegenbauer, 0, 2)
+    assert_raises(ValueError, sc.roots_gegenbauer, 3.3, 2)
+    assert_raises(ValueError, sc.roots_gegenbauer, 3, -.75)
+
+def test_roots_chebyt():
+    weightf = orth.chebyt(5).weight_func
+    verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 5)
+    verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 25)
+    verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 100,
+                      atol=1e-12)
+
+    x, w = sc.roots_chebyt(5, False)
+    y, v, m = sc.roots_chebyt(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebyt, 0)
+    assert_raises(ValueError, sc.roots_chebyt, 3.3)
+
+def test_chebyt_symmetry():
+    x, w = sc.roots_chebyt(21)
+    pos, neg = x[:10], x[11:]
+    assert_equal(neg, -pos[::-1])
+    assert_equal(x[10], 0)
+
+def test_roots_chebyu():
+    weightf = orth.chebyu(5).weight_func
+    verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 5)
+    verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 25)
+    verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 100)
+
+    x, w = sc.roots_chebyu(5, False)
+    y, v, m = sc.roots_chebyu(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebyu, 0)
+    assert_raises(ValueError, sc.roots_chebyu, 3.3)
+
+def test_roots_chebyc():
+    weightf = orth.chebyc(5).weight_func
+    verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 5)
+    verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 25)
+    verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 100,
+                      atol=1e-12)
+
+    x, w = sc.roots_chebyc(5, False)
+    y, v, m = sc.roots_chebyc(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -2, 2)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebyc, 0)
+    assert_raises(ValueError, sc.roots_chebyc, 3.3)
+
+def test_roots_chebys():
+    weightf = orth.chebys(5).weight_func
+    verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 5)
+    verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 25)
+    verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 100)
+
+    x, w = sc.roots_chebys(5, False)
+    y, v, m = sc.roots_chebys(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -2, 2)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebys, 0)
+    assert_raises(ValueError, sc.roots_chebys, 3.3)
+
+def test_roots_sh_chebyt():
+    weightf = orth.sh_chebyt(5).weight_func
+    verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 5)
+    verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 25)
+    verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1.,
+                      100, atol=1e-13)
+
+    x, w = sc.roots_sh_chebyt(5, False)
+    y, v, m = sc.roots_sh_chebyt(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_chebyt, 0)
+    assert_raises(ValueError, sc.roots_sh_chebyt, 3.3)
+
+def test_roots_sh_chebyu():
+    weightf = orth.sh_chebyu(5).weight_func
+    verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 5)
+    verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 25)
+    verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1.,
+                      100, atol=1e-13)
+
+    x, w = sc.roots_sh_chebyu(5, False)
+    y, v, m = sc.roots_sh_chebyu(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_chebyu, 0)
+    assert_raises(ValueError, sc.roots_sh_chebyu, 3.3)
+
+def test_roots_legendre():
+    weightf = orth.legendre(5).weight_func
+    verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., 5)
+    verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1.,
+                      25, atol=1e-13)
+    verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1.,
+                      100, atol=1e-12)
+
+    x, w = sc.roots_legendre(5, False)
+    y, v, m = sc.roots_legendre(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_legendre, 0)
+    assert_raises(ValueError, sc.roots_legendre, 3.3)
+
+def test_roots_sh_legendre():
+    weightf = orth.sh_legendre(5).weight_func
+    verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., 5)
+    verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1.,
+                      25, atol=1e-13)
+    verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1.,
+                      100, atol=1e-12)
+
+    x, w = sc.roots_sh_legendre(5, False)
+    y, v, m = sc.roots_sh_legendre(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_legendre, 0)
+    assert_raises(ValueError, sc.roots_sh_legendre, 3.3)
+
+def test_roots_laguerre():
+    weightf = orth.laguerre(5).weight_func
+    verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, 5)
+    verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf,
+                      25, atol=1e-13)
+    verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf,
+                      100, atol=1e-12)
+
+    x, w = sc.roots_laguerre(5, False)
+    y, v, m = sc.roots_laguerre(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_laguerre, 0)
+    assert_raises(ValueError, sc.roots_laguerre, 3.3)
+
+def test_roots_genlaguerre():
+    def rootf(a):
+        return lambda n, mu: sc.roots_genlaguerre(n, a, mu)
+    def evalf(a):
+        return lambda n, x: sc.eval_genlaguerre(n, a, x)
+    def weightf(a):
+        return lambda x: x ** a * np.exp(-x)
+
+    vgq = verify_gauss_quad
+    vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 5)
+    vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 100, atol=1e-12)
+
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 5)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 100, atol=1.6e-13)
+
+    vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 5)
+    vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 100, atol=1.03e-13)
+
+    vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 5)
+    vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 100, atol=1e-12)
+
+    vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 5)
+    vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 100, rtol=1e-14, atol=2e-13)
+
+    x, w = sc.roots_genlaguerre(5, 2, False)
+    y, v, m = sc.roots_genlaguerre(5, 2, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf(2.), 0., np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_genlaguerre, 0, 2)
+    assert_raises(ValueError, sc.roots_genlaguerre, 3.3, 2)
+    assert_raises(ValueError, sc.roots_genlaguerre, 3, -1.1)
+
+
+def test_gh_6721():
+    # Regression test for gh_6721. This should not raise.
+    sc.chebyt(65)(0.2)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4f379effdc9c3aa18bd2948fbd9f716b1f8d57
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py
@@ -0,0 +1,275 @@
+import numpy as np
+from numpy.testing import assert_, assert_allclose
+import pytest
+
+from scipy.special import _ufuncs
+import scipy.special._orthogonal as orth
+from scipy.special._testutils import FuncData
+
+
+def test_eval_chebyt():
+    n = np.arange(0, 10000, 7, dtype=np.dtype("long"))
+    x = 2*np.random.rand() - 1
+    v1 = np.cos(n*np.arccos(x))
+    v2 = _ufuncs.eval_chebyt(n, x)
+    assert_(np.allclose(v1, v2, rtol=1e-15))
+
+
+def test_eval_chebyt_gh20129():
+    # https://github.com/scipy/scipy/issues/20129
+    assert _ufuncs.eval_chebyt(7, 2 + 0j) == 5042.0
+
+
+def test_eval_genlaguerre_restriction():
+    # check it returns nan for alpha <= -1
+    assert_(np.isnan(_ufuncs.eval_genlaguerre(0, -1, 0)))
+    assert_(np.isnan(_ufuncs.eval_genlaguerre(0.1, -1, 0)))
+
+
+def test_warnings():
+    # ticket 1334
+    with np.errstate(all='raise'):
+        # these should raise no fp warnings
+        _ufuncs.eval_legendre(1, 0)
+        _ufuncs.eval_laguerre(1, 1)
+        _ufuncs.eval_gegenbauer(1, 1, 0)
+
+
+class TestPolys:
+    """
+    Check that the eval_* functions agree with the constructed polynomials
+
+    """
+
+    def check_poly(self, func, cls, param_ranges=(), x_range=(), nn=10,
+                   nparam=10, nx=10, rtol=1e-8):
+        rng = np.random.RandomState(1234)
+
+        dataset = []
+        for n in np.arange(nn):
+            params = [a + (b-a)*rng.rand(nparam) for a,b in param_ranges]
+            params = np.asarray(params).T
+            if not param_ranges:
+                params = [0]
+            for p in params:
+                if param_ranges:
+                    p = (n,) + tuple(p)
+                else:
+                    p = (n,)
+                x = x_range[0] + (x_range[1] - x_range[0])*rng.rand(nx)
+                x[0] = x_range[0]  # always include domain start point
+                x[1] = x_range[1]  # always include domain end point
+                poly = np.poly1d(cls(*p).coef)
+                z = np.c_[np.tile(p, (nx,1)), x, poly(x)]
+                dataset.append(z)
+
+        dataset = np.concatenate(dataset, axis=0)
+
+        def polyfunc(*p):
+            p = (p[0].astype(np.dtype("long")),) + p[1:]
+            return func(*p)
+
+        with np.errstate(all='raise'):
+            ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1,
+                          rtol=rtol)
+            ds.check()
+
+    def test_jacobi(self):
+        self.check_poly(_ufuncs.eval_jacobi, orth.jacobi,
+                        param_ranges=[(-0.99, 10), (-0.99, 10)],
+                        x_range=[-1, 1], rtol=1e-5)
+
+    def test_sh_jacobi(self):
+        self.check_poly(_ufuncs.eval_sh_jacobi, orth.sh_jacobi,
+                        param_ranges=[(1, 10), (0, 1)], x_range=[0, 1],
+                        rtol=1e-5)
+
+    def test_gegenbauer(self):
+        self.check_poly(_ufuncs.eval_gegenbauer, orth.gegenbauer,
+                        param_ranges=[(-0.499, 10)], x_range=[-1, 1],
+                        rtol=1e-7)
+
+    def test_chebyt(self):
+        self.check_poly(_ufuncs.eval_chebyt, orth.chebyt,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebyu(self):
+        self.check_poly(_ufuncs.eval_chebyu, orth.chebyu,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebys(self):
+        self.check_poly(_ufuncs.eval_chebys, orth.chebys,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_chebyc(self):
+        self.check_poly(_ufuncs.eval_chebyc, orth.chebyc,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_sh_chebyt(self):
+        with np.errstate(all='ignore'):
+            self.check_poly(_ufuncs.eval_sh_chebyt, orth.sh_chebyt,
+                            param_ranges=[], x_range=[0, 1])
+
+    def test_sh_chebyu(self):
+        self.check_poly(_ufuncs.eval_sh_chebyu, orth.sh_chebyu,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_legendre(self):
+        self.check_poly(_ufuncs.eval_legendre, orth.legendre,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_sh_legendre(self):
+        with np.errstate(all='ignore'):
+            self.check_poly(_ufuncs.eval_sh_legendre, orth.sh_legendre,
+                            param_ranges=[], x_range=[0, 1])
+
+    def test_genlaguerre(self):
+        self.check_poly(_ufuncs.eval_genlaguerre, orth.genlaguerre,
+                        param_ranges=[(-0.99, 10)], x_range=[0, 100])
+
+    def test_laguerre(self):
+        self.check_poly(_ufuncs.eval_laguerre, orth.laguerre,
+                        param_ranges=[], x_range=[0, 100])
+
+    def test_hermite(self):
+        self.check_poly(_ufuncs.eval_hermite, orth.hermite,
+                        param_ranges=[], x_range=[-100, 100])
+
+    def test_hermitenorm(self):
+        self.check_poly(_ufuncs.eval_hermitenorm, orth.hermitenorm,
+                        param_ranges=[], x_range=[-100, 100])
+
+
+class TestRecurrence:
+    """
+    Check that the eval_* functions sig='ld->d' and 'dd->d' agree.
+
+    """
+
+    def check_poly(self, func, param_ranges=(), x_range=(), nn=10,
+                   nparam=10, nx=10, rtol=1e-8):
+        np.random.seed(1234)
+
+        dataset = []
+        for n in np.arange(nn):
+            params = [a + (b-a)*np.random.rand(nparam) for a,b in param_ranges]
+            params = np.asarray(params).T
+            if not param_ranges:
+                params = [0]
+            for p in params:
+                if param_ranges:
+                    p = (n,) + tuple(p)
+                else:
+                    p = (n,)
+                x = x_range[0] + (x_range[1] - x_range[0])*np.random.rand(nx)
+                x[0] = x_range[0]  # always include domain start point
+                x[1] = x_range[1]  # always include domain end point
+                kw = dict(sig=(len(p)+1)*'d'+'->d')
+                z = np.c_[np.tile(p, (nx,1)), x, func(*(p + (x,)), **kw)]
+                dataset.append(z)
+
+        dataset = np.concatenate(dataset, axis=0)
+
+        def polyfunc(*p):
+            p0 = p[0].astype(np.intp)
+            p = (p0,) + p[1:]
+            p0_type_char = p0.dtype.char
+            kw = dict(sig=p0_type_char + (len(p)-1)*'d' + '->d')
+            return func(*p, **kw)
+
+        with np.errstate(all='raise'):
+            ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1,
+                          rtol=rtol)
+            ds.check()
+
+    def test_jacobi(self):
+        self.check_poly(_ufuncs.eval_jacobi,
+                        param_ranges=[(-0.99, 10), (-0.99, 10)],
+                        x_range=[-1, 1])
+
+    def test_sh_jacobi(self):
+        self.check_poly(_ufuncs.eval_sh_jacobi,
+                        param_ranges=[(1, 10), (0, 1)], x_range=[0, 1])
+
+    def test_gegenbauer(self):
+        self.check_poly(_ufuncs.eval_gegenbauer,
+                        param_ranges=[(-0.499, 10)], x_range=[-1, 1])
+
+    def test_chebyt(self):
+        self.check_poly(_ufuncs.eval_chebyt,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebyu(self):
+        self.check_poly(_ufuncs.eval_chebyu,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebys(self):
+        self.check_poly(_ufuncs.eval_chebys,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_chebyc(self):
+        self.check_poly(_ufuncs.eval_chebyc,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_sh_chebyt(self):
+        self.check_poly(_ufuncs.eval_sh_chebyt,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_sh_chebyu(self):
+        self.check_poly(_ufuncs.eval_sh_chebyu,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_legendre(self):
+        self.check_poly(_ufuncs.eval_legendre,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_sh_legendre(self):
+        self.check_poly(_ufuncs.eval_sh_legendre,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_genlaguerre(self):
+        self.check_poly(_ufuncs.eval_genlaguerre,
+                        param_ranges=[(-0.99, 10)], x_range=[0, 100])
+
+    def test_laguerre(self):
+        self.check_poly(_ufuncs.eval_laguerre,
+                        param_ranges=[], x_range=[0, 100])
+
+    def test_hermite(self):
+        v = _ufuncs.eval_hermite(70, 1.0)
+        a = -1.457076485701412e60
+        assert_allclose(v, a)
+
+
+def test_hermite_domain():
+    # Regression test for gh-11091.
+    assert np.isnan(_ufuncs.eval_hermite(-1, 1.0))
+    assert np.isnan(_ufuncs.eval_hermitenorm(-1, 1.0))
+
+
+@pytest.mark.parametrize("n", [0, 1, 2])
+@pytest.mark.parametrize("x", [0, 1, np.nan])
+def test_hermite_nan(n, x):
+    # Regression test for gh-11369.
+    assert np.isnan(_ufuncs.eval_hermite(n, x)) == np.any(np.isnan([n, x]))
+    assert np.isnan(_ufuncs.eval_hermitenorm(n, x)) == np.any(np.isnan([n, x]))
+
+
+@pytest.mark.parametrize('n', [0, 1, 2, 3.2])
+@pytest.mark.parametrize('alpha', [1, np.nan])
+@pytest.mark.parametrize('x', [2, np.nan])
+def test_genlaguerre_nan(n, alpha, x):
+    # Regression test for gh-11361.
+    nan_laguerre = np.isnan(_ufuncs.eval_genlaguerre(n, alpha, x))
+    nan_arg = np.any(np.isnan([n, alpha, x]))
+    assert nan_laguerre == nan_arg
+
+
+@pytest.mark.parametrize('n', [0, 1, 2, 3.2])
+@pytest.mark.parametrize('alpha', [0.0, 1, np.nan])
+@pytest.mark.parametrize('x', [1e-6, 2, np.nan])
+def test_gegenbauer_nan(n, alpha, x):
+    # Regression test for gh-11370.
+    nan_gegenbauer = np.isnan(_ufuncs.eval_gegenbauer(n, alpha, x))
+    nan_arg = np.any(np.isnan([n, alpha, x]))
+    assert nan_gegenbauer == nan_arg
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d15aead25302023c5f07d8392c0931995764ced
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py
@@ -0,0 +1,53 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+import scipy.special as sc
+
+
+def test_symmetries():
+    np.random.seed(1234)
+    a, h = np.random.rand(100), np.random.rand(100)
+    assert_equal(sc.owens_t(h, a), sc.owens_t(-h, a))
+    assert_equal(sc.owens_t(h, a), -sc.owens_t(h, -a))
+
+
+def test_special_cases():
+    assert_equal(sc.owens_t(5, 0), 0)
+    assert_allclose(sc.owens_t(0, 5), 0.5*np.arctan(5)/np.pi,
+                    rtol=5e-14)
+    # Target value is 0.5*Phi(5)*(1 - Phi(5)) for Phi the CDF of the
+    # standard normal distribution
+    assert_allclose(sc.owens_t(5, 1), 1.4332574485503512543e-07,
+                    rtol=5e-14)
+
+
+def test_nans():
+    assert_equal(sc.owens_t(20, np.nan), np.nan)
+    assert_equal(sc.owens_t(np.nan, 20), np.nan)
+    assert_equal(sc.owens_t(np.nan, np.nan), np.nan)
+
+
+def test_infs():
+    h, a = 0, np.inf
+    # T(0, a) = 1/2π * arctan(a)
+    res = 1/(2*np.pi) * np.arctan(a)
+    assert_allclose(sc.owens_t(h, a), res, rtol=5e-14)
+    assert_allclose(sc.owens_t(h, -a), -res, rtol=5e-14)
+
+    h = 1
+    # Refer Owens T function definition in Wikipedia
+    # https://en.wikipedia.org/wiki/Owen%27s_T_function
+    # Value approximated through Numerical Integration
+    # using scipy.integrate.quad
+    # quad(lambda x: 1/(2*pi)*(exp(-0.5*(1*1)*(1+x*x))/(1+x*x)), 0, inf)
+    res = 0.07932762696572854
+    assert_allclose(sc.owens_t(h, np.inf), res, rtol=5e-14)
+    assert_allclose(sc.owens_t(h, -np.inf), -res, rtol=5e-14)
+
+    assert_equal(sc.owens_t(np.inf, 1), 0)
+    assert_equal(sc.owens_t(-np.inf, 1), 0)
+
+    assert_equal(sc.owens_t(np.inf, np.inf), 0)
+    assert_equal(sc.owens_t(-np.inf, np.inf), 0)
+    assert_equal(sc.owens_t(np.inf, -np.inf), -0.0)
+    assert_equal(sc.owens_t(-np.inf, -np.inf), -0.0)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8c42aa688081fb58f79ad2c8ea932d03b33523b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py
@@ -0,0 +1,24 @@
+"""Tests for parabolic cylinder functions.
+
+"""
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import scipy.special as sc
+
+
+def test_pbwa_segfault():
+    # Regression test for https://github.com/scipy/scipy/issues/6208.
+    #
+    # Data generated by mpmath.
+    #
+    w = 1.02276567211316867161
+    wp = -0.48887053372346189882
+    assert_allclose(sc.pbwa(0, 0), (w, wp), rtol=1e-13, atol=0)
+
+
+def test_pbwa_nan():
+    # Check that NaN's are returned outside of the range in which the
+    # implementation is accurate.
+    pts = [(-6, -6), (-6, 6), (6, -6), (6, 6)]
+    for p in pts:
+        assert_equal(sc.pbwa(*p), (np.nan, np.nan))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..122e6009bd71e77ae39f55da5cf056500ff526a9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py
@@ -0,0 +1,48 @@
+import numpy as np
+import scipy.special as sc
+from numpy.testing import assert_almost_equal, assert_array_equal
+
+
+class TestPdtr:
+    def test(self):
+        val = sc.pdtr(0, 1)
+        assert_almost_equal(val, np.exp(-1))
+
+    def test_m_zero(self):
+        val = sc.pdtr([0, 1, 2], 0)
+        assert_array_equal(val, [1, 1, 1])
+
+    def test_rounding(self):
+        double_val = sc.pdtr([0.1, 1.1, 2.1], 1.0)
+        int_val = sc.pdtr([0, 1, 2], 1.0)
+        assert_array_equal(double_val, int_val)
+
+    def test_inf(self):
+        val = sc.pdtr(np.inf, 1.0)
+        assert_almost_equal(val, 1.0)
+
+    def test_domain(self):
+        val = sc.pdtr(-1.1, 1.0)
+        assert np.isnan(val)
+
+class TestPdtrc:
+    def test_value(self):
+        val = sc.pdtrc(0, 1)
+        assert_almost_equal(val, 1 - np.exp(-1))
+
+    def test_m_zero(self):
+        val = sc.pdtrc([0, 1, 2], 0.0)
+        assert_array_equal(val, [0, 0, 0])
+
+    def test_rounding(self):
+        double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0)
+        int_val = sc.pdtrc([0, 1, 2], 1.0)
+        assert_array_equal(double_val, int_val)
+
+    def test_inf(self):
+        val = sc.pdtrc(np.inf, 1.0)
+        assert_almost_equal(val, 0.0)
+
+    def test_domain(self):
+        val = sc.pdtrc(-1.1, 1.0)
+        assert np.isnan(val)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d809963f64ddaedf6b59de80dcd5f7ca8fa18a9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py
@@ -0,0 +1,65 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy.special import powm1
+
+
+# Expected values were computed with mpmath, e.g.
+#
+#   >>> import mpmath
+#   >>> mpmath.np.dps = 200
+#   >>> print(float(mpmath.powm1(2.0, 1e-7))
+#   6.931472045825965e-08
+#
+powm1_test_cases = [
+    (1.25, 0.75, 0.18217701125396976, 1e-15),
+    (2.0, 1e-7, 6.931472045825965e-08, 1e-15),
+    (25.0, 5e-11, 1.6094379125636148e-10, 1e-15),
+    (0.99996, 0.75, -3.0000150002530058e-05, 1e-15),
+    (0.9999999999990905, 20, -1.81898940353014e-11, 1e-15),
+    (-1.25, 751.0, -6.017550852453444e+72, 2e-15)
+]
+
+
+@pytest.mark.parametrize('x, y, expected, rtol', powm1_test_cases)
+def test_powm1(x, y, expected, rtol):
+    p = powm1(x, y)
+    assert_allclose(p, expected, rtol=rtol)
+
+
+@pytest.mark.parametrize('x, y, expected',
+                         [(0.0, 0.0, 0.0),
+                          (0.0, -1.5, np.inf),
+                          (0.0, 1.75, -1.0),
+                          (-1.5, 2.0, 1.25),
+                          (-1.5, 3.0, -4.375),
+                          (np.nan, 0.0, 0.0),
+                          (1.0, np.nan, 0.0),
+                          (1.0, np.inf, 0.0),
+                          (1.0, -np.inf, 0.0),
+                          (np.inf, 7.5, np.inf),
+                          (np.inf, -7.5, -1.0),
+                          (3.25, np.inf, np.inf),
+                          (np.inf, np.inf, np.inf),
+                          (np.inf, -np.inf, -1.0),
+                          (np.inf, 0.0, 0.0),
+                          (-np.inf, 0.0, 0.0),
+                          (-np.inf, 2.0, np.inf),
+                          (-np.inf, 3.0, -np.inf),
+                          (-1.0, float(2**53 - 1), -2.0)])
+def test_powm1_exact_cases(x, y, expected):
+    # Test cases where we have an exact expected value.
+    p = powm1(x, y)
+    assert p == expected
+
+
+@pytest.mark.parametrize('x, y',
+                         [(-1.25, 751.03),
+                          (-1.25, np.inf),
+                          (np.nan, np.nan),
+                          (-np.inf, -np.inf),
+                          (-np.inf, 2.5)])
+def test_powm1_return_nan(x, y):
+    # Test cases where the expected return value is nan.
+    p = powm1(x, y)
+    assert np.isnan(p)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b6c6cba21d5c1d5fdfab879153ba8f125e98d5f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py
@@ -0,0 +1,24 @@
+from numpy.testing import assert_equal
+
+from scipy.special._testutils import check_version, MissingModule
+from scipy.special._precompute.expn_asy import generate_A
+
+try:
+    import sympy
+    from sympy import Poly
+except ImportError:
+    sympy = MissingModule("sympy")
+
+
+@check_version(sympy, "1.0")
+def test_generate_A():
+    # Data from DLMF 8.20.5
+    x = sympy.symbols('x')
+    Astd = [Poly(1, x),
+            Poly(1, x),
+            Poly(1 - 2*x),
+            Poly(1 - 8*x + 6*x**2)]
+    Ares = generate_A(len(Astd))
+
+    for p, q in zip(Astd, Ares):
+        assert_equal(p, q)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0c46b456d0a1b545b29e0b8b81b39dafb6b0610
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py
@@ -0,0 +1,108 @@
+import pytest
+
+from scipy.special._testutils import MissingModule, check_version
+from scipy.special._mptestutils import (
+    Arg, IntArg, mp_assert_allclose, assert_mpmath_equal)
+from scipy.special._precompute.gammainc_asy import (
+    compute_g, compute_alpha, compute_d)
+from scipy.special._precompute.gammainc_data import gammainc, gammaincc
+
+try:
+    import sympy
+except ImportError:
+    sympy = MissingModule('sympy')
+
+try:
+    import mpmath as mp
+except ImportError:
+    mp = MissingModule('mpmath')
+
+
+@check_version(mp, '0.19')
+def test_g():
+    # Test data for the g_k. See DLMF 5.11.4.
+    with mp.workdps(30):
+        g = [mp.mpf(1), mp.mpf(1)/12, mp.mpf(1)/288,
+             -mp.mpf(139)/51840, -mp.mpf(571)/2488320,
+             mp.mpf(163879)/209018880, mp.mpf(5246819)/75246796800]
+        mp_assert_allclose(compute_g(7), g)
+
+
+@pytest.mark.slow
+@check_version(mp, '0.19')
+@check_version(sympy, '0.7')
+@pytest.mark.xfail_on_32bit("rtol only 2e-11, see gh-6938")
+def test_alpha():
+    # Test data for the alpha_k. See DLMF 8.12.14.
+    with mp.workdps(30):
+        alpha = [mp.mpf(0), mp.mpf(1), mp.mpf(1)/3, mp.mpf(1)/36,
+                 -mp.mpf(1)/270, mp.mpf(1)/4320, mp.mpf(1)/17010,
+                 -mp.mpf(139)/5443200, mp.mpf(1)/204120]
+        mp_assert_allclose(compute_alpha(9), alpha)
+
+
+@pytest.mark.xslow
+@check_version(mp, '0.19')
+@check_version(sympy, '0.7')
+def test_d():
+    # Compare the d_{k, n} to the results in appendix F of [1].
+    #
+    # Sources
+    # -------
+    # [1] DiDonato and Morris, Computation of the Incomplete Gamma
+    #     Function Ratios and their Inverse, ACM Transactions on
+    #     Mathematical Software, 1986.
+
+    with mp.workdps(50):
+        dataset = [(0, 0, -mp.mpf('0.333333333333333333333333333333')),
+                   (0, 12, mp.mpf('0.102618097842403080425739573227e-7')),
+                   (1, 0, -mp.mpf('0.185185185185185185185185185185e-2')),
+                   (1, 12, mp.mpf('0.119516285997781473243076536700e-7')),
+                   (2, 0, mp.mpf('0.413359788359788359788359788360e-2')),
+                   (2, 12, -mp.mpf('0.140925299108675210532930244154e-7')),
+                   (3, 0, mp.mpf('0.649434156378600823045267489712e-3')),
+                   (3, 12, -mp.mpf('0.191111684859736540606728140873e-7')),
+                   (4, 0, -mp.mpf('0.861888290916711698604702719929e-3')),
+                   (4, 12, mp.mpf('0.288658297427087836297341274604e-7')),
+                   (5, 0, -mp.mpf('0.336798553366358150308767592718e-3')),
+                   (5, 12, mp.mpf('0.482409670378941807563762631739e-7')),
+                   (6, 0, mp.mpf('0.531307936463992223165748542978e-3')),
+                   (6, 12, -mp.mpf('0.882860074633048352505085243179e-7')),
+                   (7, 0, mp.mpf('0.344367606892377671254279625109e-3')),
+                   (7, 12, -mp.mpf('0.175629733590604619378669693914e-6')),
+                   (8, 0, -mp.mpf('0.652623918595309418922034919727e-3')),
+                   (8, 12, mp.mpf('0.377358774161109793380344937299e-6')),
+                   (9, 0, -mp.mpf('0.596761290192746250124390067179e-3')),
+                   (9, 12, mp.mpf('0.870823417786464116761231237189e-6'))]
+        d = compute_d(10, 13)
+        res = [d[k][n] for k, n, std in dataset]
+        std = [x[2] for x in dataset]
+        mp_assert_allclose(res, std)
+
+
+@check_version(mp, '0.19')
+def test_gammainc():
+    # Quick check that the gammainc in
+    # special._precompute.gammainc_data agrees with mpmath's
+    # gammainc.
+    assert_mpmath_equal(gammainc,
+                        lambda a, x: mp.gammainc(a, b=x, regularized=True),
+                        [Arg(0, 100, inclusive_a=False), Arg(0, 100)],
+                        nan_ok=False, rtol=1e-17, n=50, dps=50)
+
+
+@pytest.mark.xslow
+@check_version(mp, '0.19')
+def test_gammaincc():
+    # Check that the gammaincc in special._precompute.gammainc_data
+    # agrees with mpmath's gammainc.
+    assert_mpmath_equal(lambda a, x: gammaincc(a, x, dps=1000),
+                        lambda a, x: mp.gammainc(a, a=x, regularized=True),
+                        [Arg(20, 100), Arg(20, 100)],
+                        nan_ok=False, rtol=1e-17, n=50, dps=1000)
+
+    # Test the fast integer path
+    assert_mpmath_equal(gammaincc,
+                        lambda a, x: mp.gammainc(a, a=x, regularized=True),
+                        [IntArg(1, 100), Arg(0, 100)],
+                        nan_ok=False, rtol=1e-17, n=50, dps=50)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..89616b92329691ca76039fe11a7e08f7f3db1150
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py
@@ -0,0 +1,36 @@
+import pytest
+
+from scipy.special._testutils import MissingModule, check_version
+from scipy.special._mptestutils import mp_assert_allclose
+from scipy.special._precompute.utils import lagrange_inversion
+
+try:
+    import sympy
+except ImportError:
+    sympy = MissingModule('sympy')
+
+try:
+    import mpmath as mp
+except ImportError:
+    mp = MissingModule('mpmath')
+
+
+@pytest.mark.slow
+@check_version(sympy, '0.7')
+@check_version(mp, '0.19')
+class TestInversion:
+    @pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938")
+    def test_log(self):
+        with mp.workdps(30):
+            logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10)
+            expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10)
+            invlogcoeffs = lagrange_inversion(logcoeffs)
+            mp_assert_allclose(invlogcoeffs, expcoeffs)
+
+    @pytest.mark.xfail_on_32bit("rtol only 1e-15, see gh-6938")
+    def test_sin(self):
+        with mp.workdps(30):
+            sincoeffs = mp.taylor(mp.sin, 0, 10)
+            asincoeffs = mp.taylor(mp.asin, 0, 10)
+            invsincoeffs = lagrange_inversion(sincoeffs)
+            mp_assert_allclose(invsincoeffs, asincoeffs, atol=1e-30)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba28b7c1cff95327df0ed69086dd92b93399c3c4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py
@@ -0,0 +1,18 @@
+import numpy as np
+import pytest
+
+from scipy.special import _test_internal
+
+
+@pytest.mark.fail_slow(20)
+@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()")
+def test_add_round_up():
+    rng = np.random.RandomState(1234)
+    _test_internal.test_add_round(10**5, 'up', rng)
+
+
+@pytest.mark.fail_slow(20)
+@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()")
+def test_add_round_down():
+    rng = np.random.RandomState(1234)
+    _test_internal.test_add_round(10**5, 'down', rng)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dfe8287ee4f53a51a5654edc975c5c521a7d747
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py
@@ -0,0 +1,145 @@
+import sys
+import warnings
+
+import numpy as np
+from numpy.testing import assert_, assert_equal, IS_PYPY
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.special as sc
+from scipy.special._ufuncs import _sf_error_test_function
+
+_sf_error_code_map = {
+    # skip 'ok'
+    'singular': 1,
+    'underflow': 2,
+    'overflow': 3,
+    'slow': 4,
+    'loss': 5,
+    'no_result': 6,
+    'domain': 7,
+    'arg': 8,
+    'other': 9,
+    'memory': 10,
+}
+
+_sf_error_actions = [
+    'ignore',
+    'warn',
+    'raise'
+]
+
+
+def _check_action(fun, args, action):
+    # TODO: special expert should correct
+    # the coercion at the true location?
+    args = np.asarray(args, dtype=np.dtype("long"))
+    if action == 'warn':
+        with pytest.warns(sc.SpecialFunctionWarning):
+            fun(*args)
+    elif action == 'raise':
+        with assert_raises(sc.SpecialFunctionError):
+            fun(*args)
+    else:
+        # action == 'ignore', make sure there are no warnings/exceptions
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            fun(*args)
+
+
+def test_geterr():
+    err = sc.geterr()
+    for key, value in err.items():
+        assert_(key in _sf_error_code_map)
+        assert_(value in _sf_error_actions)
+
+
+@pytest.mark.thread_unsafe
+def test_seterr():
+    entry_err = sc.geterr()
+    try:
+        for category, error_code in _sf_error_code_map.items():
+            for action in _sf_error_actions:
+                geterr_olderr = sc.geterr()
+                seterr_olderr = sc.seterr(**{category: action})
+                assert_(geterr_olderr == seterr_olderr)
+                newerr = sc.geterr()
+                assert_(newerr[category] == action)
+                geterr_olderr.pop(category)
+                newerr.pop(category)
+                assert_(geterr_olderr == newerr)
+                _check_action(_sf_error_test_function, (error_code,), action)
+    finally:
+        sc.seterr(**entry_err)
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_sf_error_special_refcount():
+    # Regression test for gh-16233.
+    # Check that the reference count of scipy.special is not increased
+    # when a SpecialFunctionError is raised.
+    refcount_before = sys.getrefcount(sc)
+    with sc.errstate(all='raise'):
+        with pytest.raises(sc.SpecialFunctionError, match='domain error'):
+            sc.ndtri(2.0)
+    refcount_after = sys.getrefcount(sc)
+    assert refcount_after == refcount_before
+
+
+def test_errstate_pyx_basic():
+    olderr = sc.geterr()
+    with sc.errstate(singular='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.loggamma(0)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_c_basic():
+    olderr = sc.geterr()
+    with sc.errstate(domain='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.spence(-1)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_cpp_basic():
+    olderr = sc.geterr()
+    with sc.errstate(underflow='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.wrightomega(-1000)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_cpp_scipy_special():
+    olderr = sc.geterr()
+    with sc.errstate(singular='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.lambertw(0, 1)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_cpp_alt_ufunc_machinery():
+    olderr = sc.geterr()
+    with sc.errstate(singular='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.gammaln(0)
+    assert_equal(olderr, sc.geterr())
+
+
+@pytest.mark.thread_unsafe
+def test_errstate():
+    for category, error_code in _sf_error_code_map.items():
+        for action in _sf_error_actions:
+            olderr = sc.geterr()
+            with sc.errstate(**{category: action}):
+                _check_action(_sf_error_test_function, (error_code,), action)
+            assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_all_but_one():
+    olderr = sc.geterr()
+    with sc.errstate(all='raise', singular='ignore'):
+        sc.gammaln(0)
+        with assert_raises(sc.SpecialFunctionError):
+            sc.spence(-1.0)
+    assert_equal(olderr, sc.geterr())
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py
new file mode 100644
index 0000000000000000000000000000000000000000..d33c1795641ba74f777fcfdcffe80d86463477e3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py
@@ -0,0 +1,36 @@
+import numpy as np
+
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+def test_sici_consistency():
+    # Make sure the implementation of sici for real arguments agrees
+    # with the implementation of sici for complex arguments.
+
+    # On the negative real axis Cephes drops the imaginary part in ci
+    def sici(x):
+        si, ci = sc.sici(x + 0j)
+        return si.real, ci.real
+    
+    x = np.r_[-np.logspace(8, -30, 200), 0, np.logspace(-30, 8, 200)]
+    si, ci = sc.sici(x)
+    dataset = np.column_stack((x, si, ci))
+    FuncData(sici, dataset, 0, (1, 2), rtol=1e-12).check()
+
+
+def test_shichi_consistency():
+    # Make sure the implementation of shichi for real arguments agrees
+    # with the implementation of shichi for complex arguments.
+
+    # On the negative real axis Cephes drops the imaginary part in chi
+    def shichi(x):
+        shi, chi = sc.shichi(x + 0j)
+        return shi.real, chi.real
+
+    # Overflow happens quickly, so limit range
+    x = np.r_[-np.logspace(np.log10(700), -30, 200), 0,
+              np.logspace(-30, np.log10(700), 200)]
+    shi, chi = sc.shichi(x)
+    dataset = np.column_stack((x, shi, chi))
+    FuncData(shichi, dataset, 0, (1, 2), rtol=1e-14).check()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py
new file mode 100644
index 0000000000000000000000000000000000000000..f36fd2915be8c8d14138493c34dfd5733a2a1e6d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py
@@ -0,0 +1,48 @@
+"""
+Various made-up tests to hit different branches of the code in specfun.c
+"""
+
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy import special
+
+
+def test_cva2_cv0_branches():
+    res, resp = special.mathieu_cem([40, 129], [13, 14], [30, 45])
+    assert_allclose(res, np.array([-0.3741211, 0.74441928]))
+    assert_allclose(resp, np.array([-37.02872758, -86.13549877]))
+
+    res, resp = special.mathieu_sem([40, 129], [13, 14], [30, 45])
+    assert_allclose(res, np.array([0.92955551, 0.66771207]))
+    assert_allclose(resp, np.array([-14.91073448, 96.02954185]))
+
+
+def test_chgm_branches():
+    res = special.eval_genlaguerre(-3.2, 3, 2.5)
+    assert_allclose(res, -0.7077721935779854)
+
+
+def test_hygfz_branches():
+    """(z == 1.0) && (c-a-b > 0.0)"""
+    res = special.hyp2f1(1.5, 2.5, 4.5, 1.+0.j)
+    assert_allclose(res, 10.30835089459151+0j)
+    """(cabs(z+1) < eps) && (fabs(c-a+b - 1.0) < eps)"""
+    res = special.hyp2f1(5+5e-16, 2, 2, -1.0 + 5e-16j)
+    assert_allclose(res, 0.031249999999999986+3.9062499999999994e-17j)
+
+
+def test_pro_rad1():
+    # https://github.com/scipy/scipy/issues/21058
+    # Reference values taken from WolframAlpha
+    # SpheroidalS1(1, 1, 30, 1.1)
+    # SpheroidalS1Prime(1, 1, 30, 1.1)
+    res = special.pro_rad1(1, 1, 30, 1.1)
+    assert_allclose(res, (0.009657872296166435, 3.253369651472877), rtol=2e-5)
+
+def test_pro_rad2():
+    # https://github.com/scipy/scipy/issues/21461
+    # Reference values taken from WolframAlpha
+    # SpheroidalS2(0, 0, 3, 1.02)
+    # SpheroidalS2Prime(0, 0, 3, 1.02)
+    res = special.pro_rad2(0, 0, 3, 1.02)
+    assert_allclose(res, (-0.35089596858528077, 13.652764213480872), rtol=10e-10)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbb26ac281dff81ea71b30318731065fe5a78f94
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py
@@ -0,0 +1,32 @@
+import numpy as np
+from numpy import sqrt, log, pi
+from scipy.special._testutils import FuncData
+from scipy.special import spence
+
+
+def test_consistency():
+    # Make sure the implementation of spence for real arguments
+    # agrees with the implementation of spence for imaginary arguments.
+
+    x = np.logspace(-30, 300, 200)
+    dataset = np.vstack((x + 0j, spence(x))).T
+    FuncData(spence, dataset, 0, 1, rtol=1e-14).check()
+
+
+def test_special_points():
+    # Check against known values of Spence's function.
+
+    phi = (1 + sqrt(5))/2
+    dataset = [(1, 0),
+               (2, -pi**2/12),
+               (0.5, pi**2/12 - log(2)**2/2),
+               (0, pi**2/6),
+               (-1, pi**2/4 - 1j*pi*log(2)),
+               ((-1 + sqrt(5))/2, pi**2/15 - log(phi)**2),
+               ((3 - sqrt(5))/2, pi**2/10 - log(phi)**2),
+               (phi, -pi**2/15 + log(phi)**2/2),
+               # Corrected from Zagier, "The Dilogarithm Function"
+               ((3 + sqrt(5))/2, -pi**2/10 - log(phi)**2)]
+
+    dataset = np.asarray(dataset)
+    FuncData(spence, dataset, 0, 1, rtol=1e-14).check()
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a047c78fb8542bd0abbb75a4815d777e1414b0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py
@@ -0,0 +1,61 @@
+import numpy as np
+from numpy.testing import (assert_array_equal,
+        assert_array_almost_equal_nulp, assert_almost_equal)
+from pytest import raises as assert_raises
+
+from scipy.special import gammaln, multigammaln
+
+
+class TestMultiGammaLn:
+
+    def test1(self):
+        # A test of the identity
+        #     Gamma_1(a) = Gamma(a)
+        np.random.seed(1234)
+        a = np.abs(np.random.randn())
+        assert_array_equal(multigammaln(a, 1), gammaln(a))
+
+    def test2(self):
+        # A test of the identity
+        #     Gamma_2(a) = sqrt(pi) * Gamma(a) * Gamma(a - 0.5)
+        a = np.array([2.5, 10.0])
+        result = multigammaln(a, 2)
+        expected = np.log(np.sqrt(np.pi)) + gammaln(a) + gammaln(a - 0.5)
+        assert_almost_equal(result, expected)
+
+    def test_bararg(self):
+        assert_raises(ValueError, multigammaln, 0.5, 1.2)
+
+
+def _check_multigammaln_array_result(a, d):
+    # Test that the shape of the array returned by multigammaln
+    # matches the input shape, and that all the values match
+    # the value computed when multigammaln is called with a scalar.
+    result = multigammaln(a, d)
+    assert_array_equal(a.shape, result.shape)
+    a1 = a.ravel()
+    result1 = result.ravel()
+    for i in range(a.size):
+        assert_array_almost_equal_nulp(result1[i], multigammaln(a1[i], d))
+
+
+def test_multigammaln_array_arg():
+    # Check that the array returned by multigammaln has the correct
+    # shape and contains the correct values.  The cases have arrays
+    # with several different shapes.
+    # The cases include a regression test for ticket #1849
+    # (a = np.array([2.0]), an array with a single element).
+    np.random.seed(1234)
+
+    cases = [
+        # a, d
+        (np.abs(np.random.randn(3, 2)) + 5, 5),
+        (np.abs(np.random.randn(1, 2)) + 5, 5),
+        (np.arange(10.0, 18.0).reshape(2, 2, 2), 3),
+        (np.array([2.0]), 3),
+        (np.float64(2.0), 3),
+    ]
+
+    for a, d in cases:
+        _check_multigammaln_array_result(a, d)
+
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..310bda00b4d8b715cddcd94f5aa7142a0bdae6fa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py
@@ -0,0 +1,86 @@
+import numpy as np
+import pytest
+
+from numpy.testing import assert_allclose, suppress_warnings
+import scipy.special as sc
+
+class TestSphHarm:
+    @pytest.mark.slow
+    def test_p(self):
+        m_max = 20
+        n_max = 10
+
+        theta = np.linspace(0, np.pi)
+        phi = np.linspace(0, 2*np.pi)
+        theta, phi = np.meshgrid(theta, phi)
+
+        y, y_jac, y_hess = sc.sph_harm_y_all(n_max, m_max, theta, phi, diff_n=2)
+        p, p_jac, p_hess = sc.sph_legendre_p_all(n_max, m_max, theta, diff_n=2)
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis=(0,)+tuple(range(2,theta.ndim+2)))
+
+        assert_allclose(y, p * np.exp(1j * m * phi))
+
+        assert_allclose(y_jac[..., 0], p_jac * np.exp(1j * m * phi))
+        assert_allclose(y_jac[..., 1], 1j * m * p * np.exp(1j * m * phi))
+
+        assert_allclose(y_hess[..., 0, 0], p_hess * np.exp(1j * m * phi))
+        assert_allclose(y_hess[..., 0, 1], 1j * m * p_jac * np.exp(1j * m * phi))
+        assert_allclose(y_hess[..., 1, 0], y_hess[..., 0, 1])
+        assert_allclose(y_hess[..., 1, 1], -m * m * p * np.exp(1j * m * phi))
+
+    @pytest.mark.parametrize("n_max", [7, 10, 50])
+    @pytest.mark.parametrize("m_max", [1, 4, 5, 9, 14])
+    def test_all(self, n_max, m_max):
+        theta = np.linspace(0, np.pi)
+        phi = np.linspace(0, 2 * np.pi)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis=tuple(range(1,theta.ndim+2)))
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis=(0,)+tuple(range(2,theta.ndim+2)))
+
+        y_actual = sc.sph_harm_y_all(n_max, m_max, theta, phi)
+        y_desired = sc.sph_harm_y(n, m, theta, phi)
+
+        np.testing.assert_allclose(y_actual, y_desired, rtol=1e-05)
+
+def test_first_harmonics():
+    # Test against explicit representations of the first four
+    # spherical harmonics which use `theta` as the azimuthal angle,
+    # `phi` as the polar angle, and include the Condon-Shortley
+    # phase.
+
+    # sph_harm is deprecated and is implemented as a shim around sph_harm_y.
+    # This test is maintained to verify the correctness of the shim.
+
+    # Notation is Ymn
+    def Y00(theta, phi):
+        return 0.5*np.sqrt(1/np.pi)
+
+    def Yn11(theta, phi):
+        return 0.5*np.sqrt(3/(2*np.pi))*np.exp(-1j*theta)*np.sin(phi)
+
+    def Y01(theta, phi):
+        return 0.5*np.sqrt(3/np.pi)*np.cos(phi)
+
+    def Y11(theta, phi):
+        return -0.5*np.sqrt(3/(2*np.pi))*np.exp(1j*theta)*np.sin(phi)
+
+    harms = [Y00, Yn11, Y01, Y11]
+    m = [0, -1, 0, 1]
+    n = [0, 1, 1, 1]
+
+    theta = np.linspace(0, 2*np.pi)
+    phi = np.linspace(0, np.pi)
+    theta, phi = np.meshgrid(theta, phi)
+
+    for harm, m, n in zip(harms, m, n):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            assert_allclose(sc.sph_harm(m, n, theta, phi),
+                            harm(theta, phi),
+                            rtol=1e-15, atol=1e-15,
+                            err_msg=f"Y^{m}_{n} incorrect")
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a0173152c25eca57670b7ee6eadb57cd965266c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py
@@ -0,0 +1,400 @@
+#
+# Tests of spherical Bessel functions.
+#
+import numpy as np
+from numpy.testing import (assert_almost_equal, assert_allclose,
+                           assert_array_almost_equal, suppress_warnings)
+import pytest
+from numpy import sin, cos, sinh, cosh, exp, inf, nan, r_, pi
+
+from scipy.special import spherical_jn, spherical_yn, spherical_in, spherical_kn
+from scipy.integrate import quad
+
+
+class TestSphericalJn:
+    def test_spherical_jn_exact(self):
+        # https://dlmf.nist.gov/10.49.E3
+        # Note: exact expression is numerically stable only for small
+        # n or z >> n.
+        x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5])
+        assert_allclose(spherical_jn(2, x),
+                        (-1/x + 3/x**3)*sin(x) - 3/x**2*cos(x))
+
+    def test_spherical_jn_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1, x),
+                        (2*n + 1)/x*spherical_jn(n, x))
+
+    def test_spherical_jn_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1,x),
+                        (2*n + 1)/x*spherical_jn(n, x))
+
+    def test_spherical_jn_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 6
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_jn(n, x), np.array([0, 0]))
+
+    def test_spherical_jn_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert_allclose(spherical_jn(n, x), np.array([0, 0, inf*(1+1j)]))
+
+    def test_spherical_jn_large_arg_1(self):
+        # https://github.com/scipy/scipy/issues/2165
+        # Reference value computed using mpmath, via
+        # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
+        assert_allclose(spherical_jn(2, 3350.507), -0.00029846226538040747)
+
+    def test_spherical_jn_large_arg_2(self):
+        # https://github.com/scipy/scipy/issues/1641
+        # Reference value computed using mpmath, via
+        # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
+        assert_allclose(spherical_jn(2, 10000), 3.0590002633029811e-05)
+
+    def test_spherical_jn_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E1
+        # But note that n = 0 is a special case: j0 = sin(x)/x -> 1
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_jn(n, x), np.array([1, 0, 0, 0, 0, 0]))
+
+
+class TestSphericalYn:
+    def test_spherical_yn_exact(self):
+        # https://dlmf.nist.gov/10.49.E5
+        # Note: exact expression is numerically stable only for small
+        # n or z >> n.
+        x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5])
+        assert_allclose(spherical_yn(2, x),
+                        (1/x - 3/x**3)*cos(x) - 3/x**2*sin(x))
+
+    def test_spherical_yn_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1,x),
+                        (2*n + 1)/x*spherical_yn(n, x))
+
+    def test_spherical_yn_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1, x),
+                        (2*n + 1)/x*spherical_yn(n, x))
+
+    def test_spherical_yn_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 6
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_yn(n, x), np.array([0, 0]))
+
+    def test_spherical_yn_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert_allclose(spherical_yn(n, x), np.array([0, 0, inf*(1+1j)]))
+
+    def test_spherical_yn_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E2
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_yn(n, x), np.full(n.shape, -inf))
+
+    def test_spherical_yn_at_zero_complex(self):
+        # Consistently with numpy:
+        # >>> -np.cos(0)/0
+        # -inf
+        # >>> -np.cos(0+0j)/(0+0j)
+        # (-inf + nan*j)
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0 + 0j
+        assert_allclose(spherical_yn(n, x), np.full(n.shape, nan))
+
+
+class TestSphericalJnYnCrossProduct:
+    def test_spherical_jn_yn_cross_product_1(self):
+        # https://dlmf.nist.gov/10.50.E3
+        n = np.array([1, 5, 8])
+        x = np.array([0.1, 1, 10])
+        left = (spherical_jn(n + 1, x) * spherical_yn(n, x) -
+                spherical_jn(n, x) * spherical_yn(n + 1, x))
+        right = 1/x**2
+        assert_allclose(left, right)
+
+    def test_spherical_jn_yn_cross_product_2(self):
+        # https://dlmf.nist.gov/10.50.E3
+        n = np.array([1, 5, 8])
+        x = np.array([0.1, 1, 10])
+        left = (spherical_jn(n + 2, x) * spherical_yn(n, x) -
+                spherical_jn(n, x) * spherical_yn(n + 2, x))
+        right = (2*n + 3)/x**3
+        assert_allclose(left, right)
+
+
+class TestSphericalIn:
+    def test_spherical_in_exact(self):
+        # https://dlmf.nist.gov/10.49.E9
+        x = np.array([0.12, 1.23, 12.34, 123.45])
+        assert_allclose(spherical_in(2, x),
+                        (1/x + 3/x**3)*sinh(x) - 3/x**2*cosh(x))
+
+    def test_spherical_in_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E4
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x),
+                        (2*n + 1)/x*spherical_in(n, x))
+
+    def test_spherical_in_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x),
+                        (2*n + 1)/x*spherical_in(n, x))
+
+    def test_spherical_in_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 5
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_in(n, x), np.array([-inf, inf]))
+
+    def test_spherical_in_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E5
+        # Ideally, i1n(n, 1j*inf) = 0 and i1n(n, (1+1j)*inf) = (1+1j)*inf, but
+        # this appears impossible to achieve because C99 regards any complex
+        # value with at least one infinite  part as a complex infinity, so
+        # 1j*inf cannot be distinguished from (1+1j)*inf.  Therefore, nan is
+        # the correct return value.
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        assert_allclose(spherical_in(n, x), np.array([-inf, inf, nan]))
+
+    def test_spherical_in_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E1
+        # But note that n = 0 is a special case: i0 = sinh(x)/x -> 1
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_in(n, x), np.array([1, 0, 0, 0, 0, 0]))
+
+
+class TestSphericalKn:
+    def test_spherical_kn_exact(self):
+        # https://dlmf.nist.gov/10.49.E13
+        x = np.array([0.12, 1.23, 12.34, 123.45])
+        assert_allclose(spherical_kn(2, x),
+                        pi/2*exp(-x)*(1/x + 3/x**2 + 3/x**3))
+
+    def test_spherical_kn_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E4
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(
+            (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x),
+            (-1)**n*(2*n + 1)/x*spherical_kn(n, x)
+        )
+
+    def test_spherical_kn_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E4
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(
+            (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x),
+            (-1)**n*(2*n + 1)/x*spherical_kn(n, x)
+        )
+
+    def test_spherical_kn_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E6
+        n = 5
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_kn(n, x), np.array([-inf, 0]))
+
+    def test_spherical_kn_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E6
+        # The behavior at complex infinity depends on the sign of the real
+        # part: if Re(z) >= 0, then the limit is 0; if Re(z) < 0, then it's
+        # z*inf.  This distinction cannot be captured, so we return nan.
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        assert_allclose(spherical_kn(n, x), np.array([-inf, 0, nan]))
+
+    def test_spherical_kn_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E2
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_kn(n, x), np.full(n.shape, inf))
+
+    def test_spherical_kn_at_zero_complex(self):
+        # https://dlmf.nist.gov/10.52.E2
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0 + 0j
+        assert_allclose(spherical_kn(n, x), np.full(n.shape, nan))
+
+
+class SphericalDerivativesTestCase:
+    def fundamental_theorem(self, n, a, b):
+        integral, tolerance = quad(lambda z: self.df(n, z), a, b)
+        assert_allclose(integral,
+                        self.f(n, b) - self.f(n, a),
+                        atol=tolerance)
+
+    @pytest.mark.slow
+    def test_fundamental_theorem_0(self):
+        self.fundamental_theorem(0, 3.0, 15.0)
+
+    @pytest.mark.slow
+    def test_fundamental_theorem_7(self):
+        self.fundamental_theorem(7, 0.5, 1.2)
+
+
+class TestSphericalJnDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_jn(n, z)
+
+    def df(self, n, z):
+        return spherical_jn(n, z, derivative=True)
+
+    def test_spherical_jn_d_zero(self):
+        n = np.array([0, 1, 2, 3, 7, 15])
+        assert_allclose(spherical_jn(n, 0, derivative=True),
+                        np.array([0, 1/3, 0, 0, 0, 0]))
+
+
+class TestSphericalYnDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_yn(n, z)
+
+    def df(self, n, z):
+        return spherical_yn(n, z, derivative=True)
+
+
+class TestSphericalInDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_in(n, z)
+
+    def df(self, n, z):
+        return spherical_in(n, z, derivative=True)
+
+    def test_spherical_in_d_zero(self):
+        n = np.array([0, 1, 2, 3, 7, 15])
+        spherical_in(n, 0, derivative=False)
+        assert_allclose(spherical_in(n, 0, derivative=True),
+                        np.array([0, 1/3, 0, 0, 0, 0]))
+
+
+class TestSphericalKnDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_kn(n, z)
+
+    def df(self, n, z):
+        return spherical_kn(n, z, derivative=True)
+
+
+class TestSphericalOld:
+    # These are tests from the TestSpherical class of test_basic.py,
+    # rewritten to use spherical_* instead of sph_* but otherwise unchanged.
+
+    def test_sph_in(self):
+        # This test reproduces test_basic.TestSpherical.test_sph_in.
+        i1n = np.empty((2,2))
+        x = 0.2
+
+        i1n[0][0] = spherical_in(0, x)
+        i1n[0][1] = spherical_in(1, x)
+        i1n[1][0] = spherical_in(0, x, derivative=True)
+        i1n[1][1] = spherical_in(1, x, derivative=True)
+
+        inp0 = (i1n[0][1])
+        inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1])
+        assert_array_almost_equal(i1n[0],np.array([1.0066800127054699381,
+                                                0.066933714568029540839]),12)
+        assert_array_almost_equal(i1n[1],[inp0,inp1],12)
+
+    def test_sph_in_kn_order0(self):
+        x = 1.
+        sph_i0 = np.empty((2,))
+        sph_i0[0] = spherical_in(0, x)
+        sph_i0[1] = spherical_in(0, x, derivative=True)
+        sph_i0_expected = np.array([np.sinh(x)/x,
+                                    np.cosh(x)/x-np.sinh(x)/x**2])
+        assert_array_almost_equal(r_[sph_i0], sph_i0_expected)
+
+        sph_k0 = np.empty((2,))
+        sph_k0[0] = spherical_kn(0, x)
+        sph_k0[1] = spherical_kn(0, x, derivative=True)
+        sph_k0_expected = np.array([0.5*pi*exp(-x)/x,
+                                    -0.5*pi*exp(-x)*(1/x+1/x**2)])
+        assert_array_almost_equal(r_[sph_k0], sph_k0_expected)
+
+    def test_sph_jn(self):
+        s1 = np.empty((2,3))
+        x = 0.2
+
+        s1[0][0] = spherical_jn(0, x)
+        s1[0][1] = spherical_jn(1, x)
+        s1[0][2] = spherical_jn(2, x)
+        s1[1][0] = spherical_jn(0, x, derivative=True)
+        s1[1][1] = spherical_jn(1, x, derivative=True)
+        s1[1][2] = spherical_jn(2, x, derivative=True)
+
+        s10 = -s1[0][1]
+        s11 = s1[0][0]-2.0/0.2*s1[0][1]
+        s12 = s1[0][1]-3.0/0.2*s1[0][2]
+        assert_array_almost_equal(s1[0],[0.99334665397530607731,
+                                      0.066400380670322230863,
+                                      0.0026590560795273856680],12)
+        assert_array_almost_equal(s1[1],[s10,s11,s12],12)
+
+    def test_sph_kn(self):
+        kn = np.empty((2,3))
+        x = 0.2
+
+        kn[0][0] = spherical_kn(0, x)
+        kn[0][1] = spherical_kn(1, x)
+        kn[0][2] = spherical_kn(2, x)
+        kn[1][0] = spherical_kn(0, x, derivative=True)
+        kn[1][1] = spherical_kn(1, x, derivative=True)
+        kn[1][2] = spherical_kn(2, x, derivative=True)
+
+        kn0 = -kn[0][1]
+        kn1 = -kn[0][0]-2.0/0.2*kn[0][1]
+        kn2 = -kn[0][1]-3.0/0.2*kn[0][2]
+        assert_array_almost_equal(kn[0],[6.4302962978445670140,
+                                         38.581777787067402086,
+                                         585.15696310385559829],12)
+        assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9)
+
+    def test_sph_yn(self):
+        sy1 = spherical_yn(2, 0.2)
+        sy2 = spherical_yn(0, 0.2)
+        assert_almost_equal(sy1,-377.52483,5)  # previous values in the system
+        assert_almost_equal(sy2,-4.9003329,5)
+        sphpy = (spherical_yn(0, 0.2) - 2*spherical_yn(2, 0.2))/3
+        sy3 = spherical_yn(1, 0.2, derivative=True)
+        # compare correct derivative val. (correct =-system val).
+        assert_almost_equal(sy3,sphpy,4)
+
+
+@pytest.mark.parametrize('derivative', [False, True])
+@pytest.mark.parametrize('fun', [spherical_jn, spherical_in,
+                                 spherical_yn, spherical_kn])
+def test_negative_real_gh14582(derivative, fun):
+    # gh-14582 reported that the spherical Bessel functions did not work
+    # with negative real argument `z`. Check that this is resolved.
+    rng = np.random.default_rng(3598435982345987234)
+    size = 25
+    n = rng.integers(0, 10, size=size)
+    z = rng.standard_normal(size=size)
+    res = fun(n, z, derivative=derivative)
+    ref = fun(n, z+0j, derivative=derivative)
+    np.testing.assert_allclose(res, ref.real)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..48cfe5bfb64c15486f4b0b2d911846b96e29f3df
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py
@@ -0,0 +1,113 @@
+import pytest
+
+from scipy.special._support_alternative_backends import (get_array_special_func,
+                                                         array_special_func_map)
+from scipy.conftest import array_api_compatible
+from scipy import special
+from scipy._lib._array_api_no_0d import xp_assert_close
+from scipy._lib._array_api import is_jax, is_torch, SCIPY_DEVICE
+from scipy._lib.array_api_compat import numpy as np
+
+try:
+    import array_api_strict
+    HAVE_ARRAY_API_STRICT = True
+except ImportError:
+    HAVE_ARRAY_API_STRICT = False
+
+
+@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT,
+                    reason="`array_api_strict` not installed")
+def test_dispatch_to_unrecognize_library():
+    xp = array_api_strict
+    f = get_array_special_func('ndtr', xp=xp, n_array_args=1)
+    x = [1, 2, 3]
+    res = f(xp.asarray(x))
+    ref = xp.asarray(special.ndtr(np.asarray(x)))
+    xp_assert_close(res, ref, xp=xp)
+
+
+@pytest.mark.parametrize('dtype', ['float32', 'float64', 'int64'])
+@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT,
+                    reason="`array_api_strict` not installed")
+def test_rel_entr_generic(dtype):
+    xp = array_api_strict
+    f = get_array_special_func('rel_entr', xp=xp, n_array_args=2)
+    dtype_np = getattr(np, dtype)
+    dtype_xp = getattr(xp, dtype)
+    x, y = [-1, 0, 0, 1], [1, 0, 2, 3]
+
+    x_xp, y_xp = xp.asarray(x, dtype=dtype_xp), xp.asarray(y, dtype=dtype_xp)
+    res = f(x_xp, y_xp)
+
+    x_np, y_np = np.asarray(x, dtype=dtype_np), np.asarray(y, dtype=dtype_np)
+    ref = special.rel_entr(x_np[-1], y_np[-1])
+    ref = np.asarray([np.inf, 0, 0, ref], dtype=ref.dtype)
+
+    xp_assert_close(res, xp.asarray(ref), xp=xp)
+
+
+@pytest.mark.fail_slow(5)
+@array_api_compatible
+# @pytest.mark.skip_xp_backends('numpy', reason='skip while debugging')
+# @pytest.mark.usefixtures("skip_xp_backends")
+# `reversed` is for developer convenience: test new function first = less waiting
+@pytest.mark.parametrize('f_name_n_args', reversed(array_special_func_map.items()))
+@pytest.mark.parametrize('dtype', ['float32', 'float64'])
+@pytest.mark.parametrize('shapes', [[(0,)]*4, [tuple()]*4, [(10,)]*4,
+                                    [(10,), (11, 1), (12, 1, 1), (13, 1, 1, 1)]])
+def test_support_alternative_backends(xp, f_name_n_args, dtype, shapes):
+    f_name, n_args = f_name_n_args
+
+    if (SCIPY_DEVICE != 'cpu'
+        and is_torch(xp)
+        and f_name in {'stdtr', 'betaincc', 'betainc'}
+    ):
+        pytest.skip(f"`{f_name}` does not have an array-agnostic implementation "
+                    f"and cannot delegate to PyTorch.")
+
+    shapes = shapes[:n_args]
+    f = getattr(special, f_name)
+
+    dtype_np = getattr(np, dtype)
+    dtype_xp = getattr(xp, dtype)
+
+    # # To test the robustness of the alternative backend's implementation,
+    # # use Hypothesis to generate arguments
+    # from hypothesis import given, strategies, reproduce_failure, assume
+    # import hypothesis.extra.numpy as npst
+    # @given(data=strategies.data())
+    # mbs = npst.mutually_broadcastable_shapes(num_shapes=n_args)
+    # shapes, final_shape = data.draw(mbs)
+    # elements = dict(allow_subnormal=False)  # consider min_value, max_value
+    # args_np = [np.asarray(data.draw(npst.arrays(dtype_np, shape, elements=elements)),
+    #                       dtype=dtype_np)
+    #            for shape in shapes]
+
+    # For CI, be a little more forgiving; just generate normally distributed arguments
+    rng = np.random.default_rng(984254252920492019)
+    args_np = [rng.standard_normal(size=shape, dtype=dtype_np) for shape in shapes]
+
+    if (is_jax(xp) and f_name == 'gammaincc'  # google/jax#20699
+            or f_name == 'chdtrc'):  # gh-20972
+        args_np[0] = np.abs(args_np[0])
+        args_np[1] = np.abs(args_np[1])
+
+    args_xp = [xp.asarray(arg[()], dtype=dtype_xp) for arg in args_np]
+
+    res = f(*args_xp)
+    ref = xp.asarray(f(*args_np), dtype=dtype_xp)
+
+    eps = np.finfo(dtype_np).eps
+    xp_assert_close(res, ref, atol=10*eps)
+
+
+@array_api_compatible
+def test_chdtr_gh21311(xp):
+    # the edge case behavior of generic chdtr was not right; see gh-21311
+    # be sure to test at least these cases
+    # should add `np.nan` into the mix when gh-21317 is resolved
+    x = np.asarray([-np.inf, -1., 0., 1., np.inf])
+    v = x.reshape(-1, 1)
+    ref = special.chdtr(v, x)
+    res = special.chdtr(xp.asarray(v), xp.asarray(x))
+    xp_assert_close(res, xp.asarray(ref))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py
new file mode 100644
index 0000000000000000000000000000000000000000..578dfbd5e95e6c44b1828716a74c93d645efcb1e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py
@@ -0,0 +1,72 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose, suppress_warnings
+
+from scipy.special._ufuncs import _sinpi as sinpi
+from scipy.special._ufuncs import _cospi as cospi
+
+
+def test_integer_real_part():
+    x = np.arange(-100, 101)
+    y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10)))
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    # In the following we should be *exactly* right
+    res = sinpi(z)
+    assert_equal(res.real, 0.0)
+    res = cospi(z)
+    assert_equal(res.imag, 0.0)
+
+
+def test_half_integer_real_part():
+    x = np.arange(-100, 101) + 0.5
+    y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10)))
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    # In the following we should be *exactly* right
+    res = sinpi(z)
+    assert_equal(res.imag, 0.0)
+    res = cospi(z)
+    assert_equal(res.real, 0.0)
+
+
+@pytest.mark.skip("Temporary skip while gh-19526 is being resolved")
+def test_intermediate_overlow():
+    # Make sure we avoid overflow in situations where cosh/sinh would
+    # overflow but the product with sin/cos would not
+    sinpi_pts = [complex(1 + 1e-14, 227),
+                 complex(1e-35, 250),
+                 complex(1e-301, 445)]
+    # Data generated with mpmath
+    sinpi_std = [complex(-8.113438309924894e+295, -np.inf),
+                 complex(1.9507801934611995e+306, np.inf),
+                 complex(2.205958493464539e+306, np.inf)]
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+        for p, std in zip(sinpi_pts, sinpi_std):
+            res = sinpi(p)
+            assert_allclose(res.real, std.real)
+            assert_allclose(res.imag, std.imag)
+
+    # Test for cosine, less interesting because cos(0) = 1.
+    p = complex(0.5 + 1e-14, 227)
+    std = complex(-8.113438309924894e+295, -np.inf)
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+        res = cospi(p)
+        assert_allclose(res.real, std.real)
+        assert_allclose(res.imag, std.imag)
+
+
+def test_zero_sign():
+    y = sinpi(-0.0)
+    assert y == 0.0
+    assert np.signbit(y)
+
+    y = sinpi(0.0)
+    assert y == 0.0
+    assert not np.signbit(y)
+
+    y = cospi(0.5)
+    assert y == 0.0
+    assert not np.signbit(y)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bc3ffae15ab4620c4e752df166721825cb7449c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py
@@ -0,0 +1,46 @@
+"""Test that all ufuncs have float32-preserving signatures.
+
+This was once guaranteed through the code generation script for
+generating ufuncs, `scipy/special/_generate_pyx.py`. Starting with
+gh-20260, SciPy developers have begun moving to generate ufuncs
+through direct use of the NumPy C API (through C++). Existence of
+float32 preserving signatures must now be tested since it is no
+longer guaranteed.
+"""
+
+import numpy as np
+import pytest
+import scipy.special._ufuncs
+import scipy.special._gufuncs
+
+_ufuncs = []
+for funcname in dir(scipy.special._ufuncs):
+    _ufuncs.append(getattr(scipy.special._ufuncs, funcname))
+for funcname in dir(scipy.special._gufuncs):
+    _ufuncs.append(getattr(scipy.special._gufuncs, funcname))
+
+# Not all module members are actually ufuncs
+_ufuncs = [func for func in _ufuncs if isinstance(func, np.ufunc)]
+
+@pytest.mark.parametrize("ufunc", _ufuncs)
+def test_ufunc_signatures(ufunc):
+
+    # From _generate_pyx.py
+    # "Don't add float32 versions of ufuncs with integer arguments, as this
+    # can lead to incorrect dtype selection if the integer arguments are
+    # arrays, but float arguments are scalars.
+    # For instance sph_harm(0,[0],0,0).dtype == complex64
+    # This may be a NumPy bug, but we need to work around it.
+    # cf. gh-4895, https://github.com/numpy/numpy/issues/5895"
+    types = set(sig for sig in ufunc.types
+                if not ("l" in sig or "i" in sig or "q" in sig or "p" in sig))
+
+    # Generate the full expanded set of signatures which should exist. There
+    # should be matching float and double versions of any existing signature.
+    expanded_types = set()
+    for sig in types:
+        expanded_types.update(
+            [sig.replace("d", "f").replace("D", "F"),
+             sig.replace("f", "d").replace("F", "D")]
+        )
+    assert types == expanded_types
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef30163f55c90850fe32ca600eb47547e4fa5e03
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py
@@ -0,0 +1,205 @@
+# Reference MPMATH implementation:
+#
+# import mpmath
+# from mpmath import nsum
+#
+# def Wright_Series_MPMATH(a, b, z, dps=50, method='r+s+e', steps=[1000]):
+#    """Compute Wright' generalized Bessel function as Series.
+#
+#    This uses mpmath for arbitrary precision.
+#    """
+#    with mpmath.workdps(dps):
+#        res = nsum(lambda k: z**k/mpmath.fac(k) * mpmath.rgamma(a*k+b),
+#                          [0, mpmath.inf],
+#                          tol=dps, method=method, steps=steps
+#                          )
+#
+#    return res
+
+from itertools import product
+
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+import scipy.special as sc
+from scipy.special import log_wright_bessel, loggamma, rgamma, wright_bessel
+
+
+@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10])
+@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10])
+def test_wright_bessel_zero(a, b):
+    """Test at x = 0."""
+    assert_equal(wright_bessel(a, b, 0.), rgamma(b))
+    assert_allclose(log_wright_bessel(a, b, 0.), -loggamma(b))
+
+
+@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10])
+@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1])
+def test_wright_bessel_iv(b, x):
+    """Test relation of wright_bessel and modified bessel function iv.
+
+    iv(z) = (1/2*z)**v * Phi(1, v+1; 1/4*z**2).
+    See https://dlmf.nist.gov/10.46.E2
+    """
+    if x != 0:
+        v = b - 1
+        wb = wright_bessel(1, v + 1, x**2 / 4.)
+        # Note: iv(v, x) has precision of less than 1e-12 for some cases
+        # e.g v=1-1e-6 and x=1e-06)
+        assert_allclose(np.power(x / 2., v) * wb,
+                        sc.iv(v, x),
+                        rtol=1e-11, atol=1e-11)
+
+
+@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10])
+@pytest.mark.parametrize('b', [1, 1 + 1e-3, 2, 5, 10])
+@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1, 5, 10, 100])
+def test_wright_functional(a, b, x):
+    """Test functional relation of wright_bessel.
+
+    Phi(a, b-1, z) = a*z*Phi(a, b+a, z) + (b-1)*Phi(a, b, z)
+
+    Note that d/dx Phi(a, b, x) = Phi(a, b-1, x)
+    See Eq. (22) of
+    B. Stankovic, On the Function of E. M. Wright,
+    Publ. de l' Institut Mathematique, Beograd,
+    Nouvelle S`er. 10 (1970), 113-124.
+    """
+    assert_allclose(wright_bessel(a, b - 1, x),
+                    a * x * wright_bessel(a, b + a, x)
+                    + (b - 1) * wright_bessel(a, b, x),
+                    rtol=1e-8, atol=1e-8)
+
+
+# grid of rows [a, b, x, value, accuracy] that do not reach 1e-11 accuracy
+# see output of:
+# cd scipy/scipy/_precompute
+# python wright_bessel_data.py
+grid_a_b_x_value_acc = np.array([
+    [0.1, 100.0, 709.7827128933841, 8.026353022981087e+34, 2e-8],
+    [0.5, 10.0, 709.7827128933841, 2.680788404494657e+48, 9e-8],
+    [0.5, 10.0, 1000.0, 2.005901980702872e+64, 1e-8],
+    [0.5, 100.0, 1000.0, 3.4112367580445246e-117, 6e-8],
+    [1.0, 20.0, 100000.0, 1.7717158630699857e+225, 3e-11],
+    [1.0, 100.0, 100000.0, 1.0269334596230763e+22, np.nan],
+    [1.0000000000000222, 20.0, 100000.0, 1.7717158630001672e+225, 3e-11],
+    [1.0000000000000222, 100.0, 100000.0, 1.0269334595866202e+22, np.nan],
+    [1.5, 0.0, 500.0, 15648961196.432373, 3e-11],
+    [1.5, 2.220446049250313e-14, 500.0, 15648961196.431465, 3e-11],
+    [1.5, 1e-10, 500.0, 15648961192.344728, 3e-11],
+    [1.5, 1e-05, 500.0, 15648552437.334162, 3e-11],
+    [1.5, 0.1, 500.0, 12049870581.10317, 2e-11],
+    [1.5, 20.0, 100000.0, 7.81930438331405e+43, 3e-9],
+    [1.5, 100.0, 100000.0, 9.653370857459075e-130, np.nan],
+    ])
+
+
+@pytest.mark.xfail
+@pytest.mark.parametrize(
+    'a, b, x, phi',
+    grid_a_b_x_value_acc[:, :4].tolist())
+def test_wright_data_grid_failures(a, b, x, phi):
+    """Test cases of test_data that do not reach relative accuracy of 1e-11"""
+    assert_allclose(wright_bessel(a, b, x), phi, rtol=1e-11)
+
+
+@pytest.mark.parametrize(
+    'a, b, x, phi, accuracy',
+    grid_a_b_x_value_acc.tolist())
+def test_wright_data_grid_less_accurate(a, b, x, phi, accuracy):
+    """Test cases of test_data that do not reach relative accuracy of 1e-11
+
+    Here we test for reduced accuracy or even nan.
+    """
+    if np.isnan(accuracy):
+        assert np.isnan(wright_bessel(a, b, x))
+    else:
+        assert_allclose(wright_bessel(a, b, x), phi, rtol=accuracy)
+
+
+@pytest.mark.parametrize(
+    'a, b, x',
+    list(
+        product([0, 0.1, 0.5, 1.5, 5, 10], [1, 2], [1e-3, 1, 1.5, 5, 10])
+    )
+)
+def test_log_wright_bessel_same_as_wright_bessel(a, b, x):
+    """Test that log_wright_bessel equals log of wright_bessel."""
+    assert_allclose(
+        log_wright_bessel(a, b, x),
+        np.log(wright_bessel(a, b, x)),
+        rtol=1e-8,
+    )
+
+
+# Computed with, see also mp_wright_bessel from wright_bessel_data.py:
+#
+# from functools import lru_cache
+# import mpmath as mp
+#
+# @lru_cache(maxsize=1_000_000)
+# def rgamma_cached(x, dps):
+#     with mp.workdps(dps):
+#         return mp.rgamma(x)
+#
+# def mp_log_wright_bessel(a, b, x, dps=100, maxterms=10_000, method="d"):
+#     """Compute log of Wright's generalized Bessel function as Series with mpmath."""
+#     with mp.workdps(dps):
+#         a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
+#         res = mp.nsum(lambda k: x**k / mp.fac(k)
+#                       * rgamma_cached(a * k + b, dps=dps),
+#                       [0, mp.inf],
+#                       tol=dps, method=method, steps=[maxterms]
+#                       )
+#         return mp.log(res)
+#
+# Sometimes, one needs to set maxterms as high as 1_00_000 to get accurate results for
+# phi.
+# At the end of the day, we can only hope that results are correct for very large x,
+# e.g. by the asymptotic series, as there is no way to produce those in "exact"
+# arithmetic.
+# Note: accuracy = np.nan means log_wright_bessel returns nan.
+@pytest.mark.parametrize(
+    'a, b, x, phi, accuracy',
+    [
+        (0, 0, 0, -np.inf, 1e-11),
+        (0, 0, 1, -np.inf, 1e-11),
+        (0, 1, 1.23, 1.23, 1e-11),
+        (0, 1, 1e50, 1e50, 1e-11),
+        (1e-5, 0, 700, 695.0421608273609, 1e-11),
+        (1e-5, 0, 1e3, 995.40052566540066, 1e-11),
+        (1e-5, 100, 1e3, 640.8197935670078, 1e-11),
+        (1e-3, 0, 1e4, 9987.2229532297262, 1e-11),
+        (1e-3, 0, 1e5, 99641.920687169507, 1e-11),
+        (1e-3, 0, 1e6, 994118.55560054416, 1e-11),  # maxterms=1_000_000
+        (1e-3, 10, 1e5, 99595.47710802537, 1e-11),
+        (1e-3, 50, 1e5, 99401.240922855647, 1e-3),
+        (1e-3, 100, 1e5, 99143.465191656527, np.nan),
+        (0.5, 0, 1e5, 4074.1112442197941, 1e-11),
+        (0.5, 0, 1e7, 87724.552120038896, 1e-11),
+        (0.5, 100, 1e5, 3350.3928746306163, np.nan),
+        (0.5, 100, 1e7, 86696.109975301719, 1e-11),
+        (1, 0, 1e5, 634.06765787997266, 1e-11),
+        (1, 0, 1e8, 20003.339639312035, 1e-11),
+        (1.5, 0, 1e5, 197.01777556071194, 1e-11),
+        (1.5, 0, 1e8, 3108.987414395706, 1e-11),
+        (1.5, 100, 1e8, 2354.8915946283275, np.nan),
+        (5, 0, 1e5, 9.8980480013203547, 1e-11),
+        (5, 0, 1e8, 33.642337258687465, 1e-11),
+        (5, 0, 1e12, 157.53704288117429, 1e-11),
+        (5, 100, 1e5, -359.13419630792148, 1e-11),
+        (5, 100, 1e12, -337.07722086995229, 1e-4),
+        (5, 100, 1e20, 2588.2471229986845, 2e-6),
+        (100, 0, 1e5, -347.62127990460517, 1e-11),
+        (100, 0, 1e20, -313.08250350969449, 1e-11),
+        (100, 100, 1e5, -359.1342053695754, 1e-11),
+        (100, 100, 1e20, -359.1342053695754, 1e-11),
+    ]
+)
+def test_log_wright_bessel(a, b, x, phi, accuracy):
+    """Test for log_wright_bessel, in particular for large x."""
+    if np.isnan(accuracy):
+        assert np.isnan(log_wright_bessel(a, b, x))
+    else:
+        assert_allclose(log_wright_bessel(a, b, x), phi, rtol=accuracy)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1a93ca007e42fea3a0dec634c51b37f03effa9e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py
@@ -0,0 +1,117 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_, assert_equal, assert_allclose
+
+import scipy.special as sc
+from scipy.special._testutils import assert_func_equal
+
+
+def test_wrightomega_nan():
+    pts = [complex(np.nan, 0),
+           complex(0, np.nan),
+           complex(np.nan, np.nan),
+           complex(np.nan, 1),
+           complex(1, np.nan)]
+    for p in pts:
+        res = sc.wrightomega(p)
+        assert_(np.isnan(res.real))
+        assert_(np.isnan(res.imag))
+
+
+def test_wrightomega_inf_branch():
+    pts = [complex(-np.inf, np.pi/4),
+           complex(-np.inf, -np.pi/4),
+           complex(-np.inf, 3*np.pi/4),
+           complex(-np.inf, -3*np.pi/4)]
+    expected_results = [complex(0.0, 0.0),
+                        complex(0.0, -0.0),
+                        complex(-0.0, 0.0),
+                        complex(-0.0, -0.0)]
+    for p, expected in zip(pts, expected_results):
+        res = sc.wrightomega(p)
+        # We can't use assert_equal(res, expected) because in older versions of
+        # numpy, assert_equal doesn't check the sign of the real and imaginary
+        # parts when comparing complex zeros. It does check the sign when the
+        # arguments are *real* scalars.
+        assert_equal(res.real, expected.real)
+        assert_equal(res.imag, expected.imag)
+
+
+def test_wrightomega_inf():
+    pts = [complex(np.inf, 10),
+           complex(-np.inf, 10),
+           complex(10, np.inf),
+           complex(10, -np.inf)]
+    for p in pts:
+        assert_equal(sc.wrightomega(p), p)
+
+
+def test_wrightomega_singular():
+    pts = [complex(-1.0, np.pi),
+           complex(-1.0, -np.pi)]
+    for p in pts:
+        res = sc.wrightomega(p)
+        assert_equal(res, -1.0)
+        assert_(np.signbit(res.imag) == np.bool_(False))
+
+
+@pytest.mark.parametrize('x, desired', [
+    (-np.inf, 0),
+    (np.inf, np.inf),
+])
+def test_wrightomega_real_infinities(x, desired):
+    assert sc.wrightomega(x) == desired
+
+
+def test_wrightomega_real_nan():
+    assert np.isnan(sc.wrightomega(np.nan))
+
+
+def test_wrightomega_real_series_crossover():
+    desired_error = 2 * np.finfo(float).eps
+    crossover = 1e20
+    x_before_crossover = np.nextafter(crossover, -np.inf)
+    x_after_crossover = np.nextafter(crossover, np.inf)
+    # Computed using Mpmath
+    desired_before_crossover = 99999999999999983569.948
+    desired_after_crossover = 100000000000000016337.948
+    assert_allclose(
+        sc.wrightomega(x_before_crossover),
+        desired_before_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+    assert_allclose(
+        sc.wrightomega(x_after_crossover),
+        desired_after_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+
+
+def test_wrightomega_exp_approximation_crossover():
+    desired_error = 2 * np.finfo(float).eps
+    crossover = -50
+    x_before_crossover = np.nextafter(crossover, np.inf)
+    x_after_crossover = np.nextafter(crossover, -np.inf)
+    # Computed using Mpmath
+    desired_before_crossover = 1.9287498479639314876e-22
+    desired_after_crossover = 1.9287498479639040784e-22
+    assert_allclose(
+        sc.wrightomega(x_before_crossover),
+        desired_before_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+    assert_allclose(
+        sc.wrightomega(x_after_crossover),
+        desired_after_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+
+
+def test_wrightomega_real_versus_complex():
+    x = np.linspace(-500, 500, 1001)
+    results = sc.wrightomega(x + 0j).real
+    assert_func_equal(sc.wrightomega, results, x, atol=0, rtol=1e-14)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc39c2eeaf43196d4bf25964a0c2aefec2c8c0b4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py
@@ -0,0 +1,114 @@
+import os
+import pytest
+import scipy.special as sc
+import shutil
+import tempfile
+
+from uuid import uuid4
+
+from scipy.special._testutils import check_version
+from scipy.special._testutils import MissingModule
+
+try:
+    import cupy  # type: ignore
+except (ImportError, AttributeError):
+    cupy = MissingModule('cupy')
+
+
+def get_test_cases():
+    cases_source = [
+        (sc.beta, "cephes/beta.h", "out0 = xsf::cephes::beta(in0, in1)"),
+        (sc.binom, "binom.h", "out0 = xsf::binom(in0, in1)"),
+        (sc.digamma, "digamma.h", "xsf::digamma(in0)"),
+        (sc.expn, "cephes/expn.h", "out0 = xsf::cephes::expn(in0, in1)"),
+        (sc.hyp2f1, "hyp2f1.h", "out0 = xsf::hyp2f1(in0, in1, in2, in3)"),
+        (sc._ufuncs._lambertw, "lambertw.h", "out0 = xsf::lambertw(in0, in1, in2)"),
+        (sc.ellipkinc, "cephes/ellik.h", "out0 = xsf::cephes::ellik(in0, in1)"),
+        (sc.ellipeinc, "cephes/ellie.h", "out0 = xsf::cephes::ellie(in0, in1)"),
+        (sc.gdtrib, "cdflib.h", "out0 = xsf::gdtrib(in0, in1, in2)"),
+        (sc.sici, "sici.h", "xsf::sici(in0, &out0, &out1)"),
+        (sc.shichi, "sici.h", "xsf::shichi(in0, &out0, &out1)"),
+    ]
+
+    cases = []
+    for ufunc, header, routine in cases_source:
+        preamble = f"#include "
+        for signature in ufunc.types:
+            cases.append((signature, preamble, routine))
+    return cases
+
+
+dtype_map = {
+    "f": "float32",
+    "d": "float64",
+    "F": "complex64",
+    "D": "complex128",
+    "i": "int32",
+    "l": "int64",
+}
+
+
+def get_params(signature):
+    in_, out = signature.split("->")
+    in_params = []
+    out_params = []
+    for i, typecode in enumerate(in_):
+        in_params.append(f"{dtype_map[typecode]} in{i}")
+    for i, typecode in enumerate(out):
+        out_params.append(f"{dtype_map[typecode]} out{i}")
+    in_params = ", ".join(in_params)
+    out_params = ", ".join(out_params)
+    return in_params, out_params
+
+
+def get_sample_input(signature, xp):
+    dtype_map = {
+        "f": xp.float32,
+        "d": xp.float64,
+        "F": xp.complex64,
+        "D": xp.complex128,
+        "i": xp.int32,
+        "l": xp.int64,
+    }
+
+    in_, _ = signature.split("->")
+    args = []
+    for typecode in in_:
+        args.append(xp.zeros(2, dtype=dtype_map[typecode]))
+    return args
+
+
+@pytest.fixture(scope="module", autouse=True)
+def manage_cupy_cache():
+    # Temporarily change cupy kernel cache location so kernel cache will not be polluted
+    # by these tests. Remove temporary cache in teardown.
+    temp_cache_dir = tempfile.mkdtemp()
+    original_cache_dir = os.environ.get('CUPY_CACHE_DIR', None)
+    os.environ['CUPY_CACHE_DIR'] = temp_cache_dir
+
+    yield
+
+    if original_cache_dir is not None:
+        os.environ['CUPY_CACHE_DIR'] = original_cache_dir
+    else:
+        del os.environ['CUPY_CACHE_DIR']
+    shutil.rmtree(temp_cache_dir)
+
+
+@check_version(cupy, "13.0.0")
+@pytest.mark.parametrize("signature,preamble,routine", get_test_cases())
+@pytest.mark.xslow
+def test_compiles_in_cupy(signature, preamble, routine, manage_cupy_cache):
+    name = f"x{uuid4().hex}"
+    in_params, out_params = get_params(signature)
+
+    func = cupy.ElementwiseKernel(
+        in_params,
+        out_params,
+        routine,
+        name,
+        preamble=preamble,
+        options=(f"--include-path={sc._get_include()}", "-std=c++17")
+    )
+
+    _ = func(*get_sample_input(signature, cupy))
diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py
new file mode 100644
index 0000000000000000000000000000000000000000..988f9a716196fb8f65a92a0a2e894038c2474cfa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py
@@ -0,0 +1,301 @@
+import scipy
+import scipy.special as sc
+import sys
+import numpy as np
+import pytest
+
+from numpy.testing import assert_equal, assert_allclose
+
+
+def test_zeta():
+    assert_allclose(sc.zeta(2,2), np.pi**2/6 - 1, rtol=1e-12)
+
+
+def test_zetac():
+    # Expected values in the following were computed using Wolfram
+    # Alpha's `Zeta[x] - 1`
+    x = [-2.1, 0.8, 0.9999, 9, 50, 75]
+    desired = [
+        -0.9972705002153750,
+        -5.437538415895550,
+        -10000.42279161673,
+        0.002008392826082214,
+        8.881784210930816e-16,
+        2.646977960169853e-23,
+    ]
+    assert_allclose(sc.zetac(x), desired, rtol=1e-12)
+
+
+def test_zetac_special_cases():
+    assert sc.zetac(np.inf) == 0
+    assert np.isnan(sc.zetac(-np.inf))
+    assert sc.zetac(0) == -1.5
+    assert sc.zetac(1.0) == np.inf
+
+    assert_equal(sc.zetac([-2, -50, -100]), -1)
+
+
+def test_riemann_zeta_special_cases():
+    assert np.isnan(sc.zeta(np.nan))
+    assert sc.zeta(np.inf) == 1
+    assert sc.zeta(0) == -0.5
+
+    # Riemann zeta is zero add negative even integers.
+    assert_equal(sc.zeta([-2, -4, -6, -8, -10]), 0)
+
+    assert_allclose(sc.zeta(2), np.pi**2/6, rtol=1e-12)
+    assert_allclose(sc.zeta(4), np.pi**4/90, rtol=1e-12)
+
+
+def test_riemann_zeta_avoid_overflow():
+    s = -260.00000000001
+    desired = -5.6966307844402683127e+297  # Computed with Mpmath
+    assert_allclose(sc.zeta(s), desired, atol=0, rtol=5e-14)
+
+
+@pytest.mark.parametrize(
+    "z, desired, rtol",
+    [
+        ## Test cases taken from mpmath with the script:
+
+        # import numpy as np
+        # import scipy.stats as stats
+
+        # from mpmath import mp
+
+        # # seed = np.random.SeedSequence().entropy
+        # seed = 154689806791763421822480125722191067828
+        # rng = np.random.default_rng(seed)
+        # default_rtol = 1e-13
+
+        # # A small point in each quadrant outside of the critical strip
+        # cases = []
+        # for x_sign, y_sign in [1, 1], [1, -1], [-1, 1], [-1, -1]:
+        #     x = x_sign * rng.uniform(2, 8)
+        #     y = y_sign * rng.uniform(2, 8)
+        #     z = x + y*1j
+        #     reference = complex(mp.zeta(z))
+        #     cases.append((z, reference, default_rtol))
+
+        # # Moderately large imaginary part in each quadrant outside of critical strip
+        # for x_sign, y_sign in [1, 1], [1, -1], [-1, 1], [-1, -1]:
+        #     x = x_sign * rng.uniform(2, 8)
+        #     y = y_sign * rng.uniform(50, 80)
+        #     z = x + y*1j
+        #     reference = complex(mp.zeta(z))
+        #     cases.append((z, reference, default_rtol))
+
+        # # points in critical strip
+        # x = rng.uniform(0.0, 1.0, size=5)
+        # y = np.exp(rng.uniform(0, 5, size=5))
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+        # z = x - y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+
+        # # Near small trivial zeros
+        # x = np.array([-2, -4, -6, -8])
+        # y = np.array([1e-15, -1e-15])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, 1e-7))
+
+        # # Some other points near real axis
+        # x = np.array([-0.5, 0, 0.2, 0.75])
+        # y = np.array([1e-15, -1e-15])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, 1e-7))
+
+        # # Moderately large real part
+        # x = np.array([49.33915930750887, 50.55805244181687])
+        # y = rng.uniform(20, 100, size=3)
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+
+        # # Very large imaginary part
+        # x = np.array([0.5, 34.812847097948854, 50.55805244181687])
+        # y = np.array([1e6, -1e6])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     rtol = 1e-7 if t.real == 0.5 else default_rtol
+        #     cases.append((complex(t), reference, rtol))
+        #
+        # # Naive implementation of reflection formula suffers internal overflow
+        # x = -rng.uniform(200, 300, 3)
+        # y = np.array([rng.uniform(10, 30), -rng.uniform(10, 30)])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+        #
+        # A small point in each quadrant outside of the critical strip
+        ((3.12838509346655+7.111085974836645j),
+         (1.0192654793474945+0.08795174413289127j),
+         1e-13),
+        ((7.06791362314716-7.219497492626728j),
+         (1.0020740683598117-0.006752725913243711j),
+         1e-13),
+        ((-6.806227077655519+2.724411451005281j),
+         (0.06312488213559667-0.061641496333765956j),
+         1e-13),
+        ((-3.0170751511621026-6.3686522550665945j),
+         (-0.10330747857150148-1.214541994832571j),
+         1e-13),
+        # Moderately large imaginary part in each quadrant outside of critical strip
+        ((6.133994402212294+60.03091448000761j),
+         (0.9885701843417336+0.009636925981078128j),
+         1e-13),
+        ((6.17268142822657-64.74883149743795j),
+         (1.0080474225840865+0.012032804974965354j),
+         1e-13),
+        ((-3.462191939791879+76.16258975567534j),
+         (18672.072070850158+2908.5104826247184j),
+         1e-13),
+        ((-6.955735216531752-74.75791554155748j),
+         (-77672258.72276545+71625206.0401107j),
+         1e-13),
+        # Points in critical strip
+        ((0.4088038289823922+1.4596830498094384j),
+         (0.3032837969400845-0.47272237994110344j),
+         1e-13),
+        ((0.9673493951209633+4.918968547259143j),
+         (0.7488756907431944+0.17281553371482428j),
+         1e-13),
+        ((0.8692482679977754+66.6142398421354j),
+         (0.5831942469552066-0.26848904799062334j),
+         1e-13),
+        ((0.42771847720003764+21.783747851715468j),
+         (0.4767032638444329+0.6898148744603123j),
+         1e-13),
+        ((0.20479494678428956+33.17656449538932j),
+         (-0.6983038977487848+0.18060923618150224j),
+         1e-13),
+        ((0.4088038289823922-1.4596830498094384j),
+         (0.3032837969400845+0.47272237994110344j),
+         1e-13),
+        ((0.9673493951209633-4.918968547259143j),
+         (0.7488756907431944-0.17281553371482428j),
+         1e-13),
+        ((0.8692482679977754-66.6142398421354j),
+         (0.5831942469552066+0.26848904799062334j),
+         1e-13),
+        ((0.42771847720003764-21.783747851715468j),
+         (0.4767032638444329-0.6898148744603123j),
+         1e-13),
+        ((0.20479494678428956-33.17656449538932j),
+         (-0.6983038977487848-0.18060923618150224j),
+         1e-13),
+        # Near small trivial zeros
+        ((-2+1e-15j), (3.288175809370978e-32-3.0448457058393275e-17j), 1e-07),
+        ((-4+1e-15j), (-2.868707923051182e-33+7.983811450268625e-18j), 1e-07),
+        ((-6+1e-15j), (-1.7064292323640116e-34-5.8997591435159376e-18j), 1e-07),
+        ((-8+1e-15j), (2.5060859548261706e-33+8.316161985602247e-18j), 1e-07),
+        ((-2-1e-15j), (3.288175809371319e-32+3.0448457058393275e-17j), 1e-07),
+        ((-4-1e-15j), (-2.8687079230520114e-33-7.983811450268625e-18j), 1e-07),
+        ((-6-1e-15j), (-1.70642923235801e-34+5.8997591435159376e-18j), 1e-07),
+        ((-8-1e-15j), (2.5060859548253293e-33-8.316161985602247e-18j), 1e-07),
+        # Some other points near real axis
+        ((-0.5+1e-15j), (-0.20788622497735457-3.608543395999408e-16j), 1e-07),
+        (1e-15j, (-0.5-9.189384239689193e-16j), 1e-07),
+        ((0.2+1e-15j), (-0.7339209248963406-1.4828001150329085e-15j), 1e-07),
+        ((0.75+1e-15j), (-3.4412853869452227-1.5924832114302393e-14j), 1e-13),
+        ((-0.5-1e-15j), (-0.20788622497735457+3.608543395999408e-16j), 1e-07),
+        (-1e-15j, (-0.5+9.189387416062746e-16j), 1e-07),
+        ((0.2-1e-15j), (-0.7339209248963406+1.4828004007675122e-15j), 1e-07),
+        ((0.75-1e-15j), (-3.4412853869452227+1.5924831974403957e-14j), 1e-13),
+        # Moderately large real part
+        ((49.33915930750887+53.213478698903955j),
+         (1.0000000000000009+1.0212452494616078e-15j),
+         1e-13),
+        ((50.55805244181687+53.213478698903955j),
+         (1.0000000000000004+4.387394180390787e-16j),
+         1e-13),
+        ((49.33915930750887+40.6366015728302j),
+         (0.9999999999999986-1.502268709924849e-16j),
+         1e-13),
+        ((50.55805244181687+40.6366015728302j),
+         (0.9999999999999994-6.453929613571651e-17j),
+         1e-13),
+        ((49.33915930750887+85.83555435273925j),
+         (0.9999999999999987-2.7014400611995846e-16j),
+         1e-13),
+        ((50.55805244181687+85.83555435273925j),
+         (0.9999999999999994-1.160571605555322e-16j),
+         1e-13),
+        # Very large imaginary part
+        ((0.5+1e6j), (0.0760890697382271+2.805102101019299j), 1e-07),
+        ((34.812847097948854+1e6j),
+         (1.0000000000102545+3.150848654056419e-11j),
+         1e-13),
+        ((50.55805244181687+1e6j),
+         (1.0000000000000002+5.736517078070873e-16j),
+         1e-13),
+        ((0.5-1e6j), (0.0760890697382271-2.805102101019299j), 1e-07),
+        ((34.812847097948854-1e6j),
+         (1.0000000000102545-3.150848654056419e-11j),
+         1e-13),
+        ((50.55805244181687-1e6j),
+         (1.0000000000000002-5.736517078070873e-16j),
+         1e-13),
+        ((-294.86605461349745+13.992648136816397j), (-np.inf+np.inf*1j), 1e-13),
+        ((-294.86605461349745-16.147667799398363j), (np.inf-np.inf*1j), 1e-13),
+    ]
+)
+def test_riemann_zeta_complex(z, desired, rtol):
+    assert_allclose(sc.zeta(z), desired, rtol=rtol)
+
+
+# Some of the test cases below fail for intel compilers
+cpp_compiler = scipy.__config__.CONFIG["Compilers"]["c++"]["name"]
+gcc_linux = cpp_compiler == "gcc" and sys.platform == "linux"
+clang_macOS = cpp_compiler == "clang" and sys.platform == "darwin"
+
+
+@pytest.mark.skipif(
+    not (gcc_linux or clang_macOS),
+    reason="Underflow may not be avoided on other platforms",
+)
+@pytest.mark.parametrize(
+    "z, desired, rtol",
+    [
+        # Test cases generated as part of same script for
+        # test_riemann_zeta_complex. These cases are split off because
+        # they fail on some platforms.
+        #
+        # Naive implementation of reflection formula suffers internal overflow
+        ((-217.40285743524163+13.992648136816397j),
+         (-6.012818500554211e+249-1.926943776932387e+250j),
+         5e-13,),
+        ((-237.71710702931668+13.992648136816397j),
+         (-8.823803086106129e+281-5.009074181335139e+281j),
+         1e-13,),
+        ((-217.40285743524163-16.147667799398363j),
+         (-5.111612904844256e+251-4.907132127666742e+250j),
+         5e-13,),
+        ((-237.71710702931668-16.147667799398363j),
+         (-1.3256112779883167e+283-2.253002003455494e+283j),
+         5e-13,),
+    ],
+)
+def test_riemann_zeta_complex_avoid_underflow(z, desired, rtol):
+    assert_allclose(sc.zeta(z), desired, rtol=rtol)
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a9b9ead9d7d458b47c5a51fd3104c9f72ff20a5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h
@@ -0,0 +1,89 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ *
+ * Original authors: Pauli Virtanen, Eric Moore
+ */
+
+// Binomial coefficient
+
+#pragma once
+
+#include "config.h"
+
+#include "cephes/beta.h"
+#include "cephes/gamma.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline double binom(double n, double k) {
+    double kx, nx, num, den, dk, sgn;
+
+    if (n < 0) {
+        nx = std::floor(n);
+        if (n == nx) {
+            // Undefined
+            return std::numeric_limits::quiet_NaN();
+        }
+    }
+
+    kx = std::floor(k);
+    if (k == kx && (std::abs(n) > 1E-8 || n == 0)) {
+        /* Integer case: use multiplication formula for less rounding
+         * error for cases where the result is an integer.
+         *
+         * This cannot be used for small nonzero n due to loss of
+         * precision. */
+        nx = std::floor(n);
+        if (nx == n && kx > nx / 2 && nx > 0) {
+            // Reduce kx by symmetry
+            kx = nx - kx;
+        }
+
+        if (kx >= 0 && kx < 20) {
+            num = 1.0;
+            den = 1.0;
+            for (int i = 1; i < 1 + static_cast(kx); i++) {
+                num *= i + n - kx;
+                den *= i;
+                if (std::abs(num) > 1E50) {
+                    num /= den;
+                    den = 1.0;
+                }
+            }
+            return num / den;
+        }
+    }
+
+    // general case
+    if (n >= 1E10 * k and k > 0) {
+        // avoid under/overflows intermediate results
+        return std::exp(-cephes::lbeta(1 + n - k, 1 + k) - std::log(n + 1));
+    }
+    if (k > 1E8 * std::abs(n)) {
+        // avoid loss of precision
+        num = cephes::Gamma(1 + n) / std::abs(k) + cephes::Gamma(1 + n) * n / (2 * k * k); // + ...
+        num /= M_PI * std::pow(std::abs(k), n);
+        if (k > 0) {
+            kx = std::floor(k);
+            if (static_cast(kx) == kx) {
+                dk = k - kx;
+                sgn = (static_cast(kx) % 2 == 0) ? 1 : -1;
+            } else {
+                dk = k;
+                sgn = 1;
+            }
+            return num * std::sin((dk - n) * M_PI) * sgn;
+        }
+        kx = std::floor(k);
+        if (static_cast(kx) == kx) {
+            return 0;
+        }
+        return num * std::sin(k * M_PI);
+    }
+    return 1 / (n + 1) / cephes::beta(1 + n - k, 1 + k);
+}
+
+XSF_HOST_DEVICE inline float binom(float n, float k) {
+    return binom(static_cast(n), static_cast(k));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ce5550efb6d2b13a45e22c0cbea7952bbd7938c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h
@@ -0,0 +1,100 @@
+
+#pragma once
+
+#include "cephes/igam.h"
+#include "config.h"
+#include "error.h"
+#include "tools.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline double gdtrib(double a, double p, double x) {
+    if (std::isnan(p) || std::isnan(a) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!((0 <= p) && (p <= 1))) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter p is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!(a > 0) || std::isinf(a)) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter a is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!(x >= 0) || std::isinf(x)) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter x is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        if (p == 0.0) {
+            set_error("gdtrib", SF_ERROR_DOMAIN, "Indeterminate result for (x, p) == (0, 0).");
+            return std::numeric_limits::quiet_NaN();
+        }
+        /* gdtrib(a, p, x) tends to 0 as x -> 0 when p > 0 */
+        return 0.0;
+    }
+    if (p == 0.0) {
+        /* gdtrib(a, p, x) tends to infinity as p -> 0 from the right when x > 0. */
+        set_error("gdtrib", SF_ERROR_SINGULAR, NULL);
+        return std::numeric_limits::infinity();
+    }
+    if (p == 1.0) {
+        /* gdtrib(a, p, x) tends to 0 as p -> 1.0 from the left when x > 0. */
+        return 0.0;
+    }
+    double q = 1.0 - p;
+    auto func = [a, p, q, x](double b) {
+	if (p <= q) {
+	    return cephes::igam(b, a * x) - p;
+	}
+	return q - cephes::igamc(b, a * x);
+    };
+    double lower_bound = std::numeric_limits::min();
+    double upper_bound = std::numeric_limits::max();
+    /* To explain the magic constants used below:
+     * 1.0 is the initial guess for the root. -0.875 is the initial step size
+     * for the leading bracket endpoint if the bracket search will proceed to the
+     * left, likewise 7.0 is the initial step size when the bracket search will
+     * proceed to the right. 0.125 is the scale factor for a left moving bracket
+     * search and 8.0 the scale factor for a right moving bracket search. These
+     * constants are chosen so that:
+     *
+     * 1. The scale factor and bracket endpoints remain powers of 2, allowing for
+     *    exact arithmetic, preventing roundoff error from causing numerical catastrophe
+     *    which could lead to unexpected results.
+     * 2. The bracket sizes remain constant in a relative sense. Each candidate bracket
+     *    will contain roughly the same number of floating point values. This means that
+     *    the number of necessary function evaluations in the worst case scenario for
+     *    Chandrupatla's algorithm will remain constant.
+     *
+     * false specifies that the function is not decreasing. 342 is equal to
+     * max(ceil(log_8(DBL_MAX)), ceil(log_(1/8)(DBL_MIN))). An upper bound for the
+     * number of iterations needed in this bracket search to check all normalized
+     * floating point values.
+     */
+    auto [xl, xr, f_xl, f_xr, bracket_status] = detail::bracket_root_for_cdf_inversion(
+        func, 1.0, lower_bound, upper_bound, -0.875, 7.0, 0.125, 8, false, 342
+    );
+    if (bracket_status == 1) {
+        set_error("gdtrib", SF_ERROR_UNDERFLOW, NULL);
+        return 0.0;
+    }
+    if (bracket_status == 2) {
+        set_error("gdtrib", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::infinity();
+    }
+    if (bracket_status >= 3) {
+        set_error("gdtrib", SF_ERROR_OTHER, "Computational Error");
+        return std::numeric_limits::quiet_NaN();
+    }
+    auto [result, root_status] = detail::find_root_chandrupatla(
+        func, xl, xr, f_xl, f_xr, std::numeric_limits::epsilon(), 1e-100, 100
+    );
+    if (root_status) {
+        /* The root finding return should only fail if there's a bug in our code. */
+        set_error("gdtrib", SF_ERROR_OTHER, "Computational Error, (%.17g, %.17g, %.17g)", a, p, x);
+        return std::numeric_limits::quiet_NaN();
+    }
+    return result;
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h
new file mode 100644
index 0000000000000000000000000000000000000000..8db31fa9b3830b1e561a27a349154fc96ab071d3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h
@@ -0,0 +1,307 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     airy.c
+ *
+ *     Airy function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, ai, aip, bi, bip;
+ * int airy();
+ *
+ * airy( x, _&ai, _&aip, _&bi, _&bip );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Solution of the differential equation
+ *
+ *     y"(x) = xy.
+ *
+ * The function returns the two independent solutions Ai, Bi
+ * and their first derivatives Ai'(x), Bi'(x).
+ *
+ * Evaluation is by power series summation for small x,
+ * by rational minimax approximations for large x.
+ *
+ *
+ *
+ * ACCURACY:
+ * Error criterion is absolute when function <= 1, relative
+ * when function > 1, except * denotes relative error criterion.
+ * For large negative x, the absolute error increases as x^1.5.
+ * For large positive x, the relative error increases as x^1.5.
+ *
+ * Arithmetic  domain   function  # trials      peak         rms
+ * IEEE        -10, 0     Ai        10000       1.6e-15     2.7e-16
+ * IEEE          0, 10    Ai        10000       2.3e-14*    1.8e-15*
+ * IEEE        -10, 0     Ai'       10000       4.6e-15     7.6e-16
+ * IEEE          0, 10    Ai'       10000       1.8e-14*    1.5e-15*
+ * IEEE        -10, 10    Bi        30000       4.2e-15     5.3e-16
+ * IEEE        -10, 10    Bi'       30000       4.9e-15     7.3e-16
+ *
+ */
+/*							airy.c */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double airy_c1 = 0.35502805388781723926;
+        constexpr double airy_c2 = 0.258819403792806798405;
+        constexpr double MAXAIRY = 103.892;
+
+        constexpr double airy_AN[8] = {
+            3.46538101525629032477E-1, 1.20075952739645805542E1, 7.62796053615234516538E1, 1.68089224934630576269E2,
+            1.59756391350164413639E2,  7.05360906840444183113E1, 1.40264691163389668864E1, 9.99999999999999995305E-1,
+        };
+
+        constexpr double airy_AD[8] = {
+            5.67594532638770212846E-1, 1.47562562584847203173E1, 8.45138970141474626562E1, 1.77318088145400459522E2,
+            1.64234692871529701831E2,  7.14778400825575695274E1, 1.40959135607834029598E1, 1.00000000000000000470E0,
+        };
+
+        constexpr double airy_APN[8] = {
+            6.13759184814035759225E-1, 1.47454670787755323881E1, 8.20584123476060982430E1, 1.71184781360976385540E2,
+            1.59317847137141783523E2,  6.99778599330103016170E1, 1.39470856980481566958E1, 1.00000000000000000550E0,
+        };
+
+        constexpr double airy_APD[8] = {
+            3.34203677749736953049E-1, 1.11810297306158156705E1, 7.11727352147859965283E1, 1.58778084372838313640E2,
+            1.53206427475809220834E2,  6.86752304592780337944E1, 1.38498634758259442477E1, 9.99999999999999994502E-1,
+        };
+
+        constexpr double airy_BN16[5] = {
+            -2.53240795869364152689E-1, 5.75285167332467384228E-1,  -3.29907036873225371650E-1,
+            6.44404068948199951727E-2,  -3.82519546641336734394E-3,
+        };
+
+        constexpr double airy_BD16[5] = {
+            /* 1.00000000000000000000E0, */
+            -7.15685095054035237902E0, 1.06039580715664694291E1,   -5.23246636471251500874E0,
+            9.57395864378383833152E-1, -5.50828147163549611107E-2,
+        };
+
+        constexpr double airy_BPPN[5] = {
+            4.65461162774651610328E-1,  -1.08992173800493920734E0, 6.38800117371827987759E-1,
+            -1.26844349553102907034E-1, 7.62487844342109852105E-3,
+        };
+
+        constexpr double airy_BPPD[5] = {
+            /* 1.00000000000000000000E0, */
+            -8.70622787633159124240E0, 1.38993162704553213172E1,   -7.14116144616431159572E0,
+            1.34008595960680518666E0,  -7.84273211323341930448E-2,
+        };
+
+        constexpr double airy_AFN[9] = {
+            -1.31696323418331795333E-1, -6.26456544431912369773E-1, -6.93158036036933542233E-1,
+            -2.79779981545119124951E-1, -4.91900132609500318020E-2, -4.06265923594885404393E-3,
+            -1.59276496239262096340E-4, -2.77649108155232920844E-6, -1.67787698489114633780E-8,
+        };
+
+        constexpr double airy_AFD[9] = {
+            /* 1.00000000000000000000E0, */
+            1.33560420706553243746E1,  3.26825032795224613948E1,  2.67367040941499554804E1,
+            9.18707402907259625840E0,  1.47529146771666414581E0,  1.15687173795188044134E-1,
+            4.40291641615211203805E-3, 7.54720348287414296618E-5, 4.51850092970580378464E-7,
+        };
+
+        constexpr double airy_AGN[11] = {
+            1.97339932091685679179E-2, 3.91103029615688277255E-1, 1.06579897599595591108E0,   9.39169229816650230044E-1,
+            3.51465656105547619242E-1, 6.33888919628925490927E-2, 5.85804113048388458567E-3,  2.82851600836737019778E-4,
+            6.98793669997260967291E-6, 8.11789239554389293311E-8, 3.41551784765923618484E-10,
+        };
+
+        constexpr double airy_AGD[10] = {
+            /*  1.00000000000000000000E0, */
+            9.30892908077441974853E0,  1.98352928718312140417E1,  1.55646628932864612953E1,  5.47686069422975497931E0,
+            9.54293611618961883998E-1, 8.64580826352392193095E-2, 4.12656523824222607191E-3, 1.01259085116509135510E-4,
+            1.17166733214413521882E-6, 4.91834570062930015649E-9,
+        };
+
+        constexpr double airy_APFN[9] = {
+            1.85365624022535566142E-1, 8.86712188052584095637E-1, 9.87391981747398547272E-1,
+            4.01241082318003734092E-1, 7.10304926289631174579E-2, 5.90618657995661810071E-3,
+            2.33051409401776799569E-4, 4.08718778289035454598E-6, 2.48379932900442457853E-8,
+        };
+
+        constexpr double airy_APFD[9] = {
+            /*  1.00000000000000000000E0, */
+            1.47345854687502542552E1,  3.75423933435489594466E1,  3.14657751203046424330E1,
+            1.09969125207298778536E1,  1.78885054766999417817E0,  1.41733275753662636873E-1,
+            5.44066067017226003627E-3, 9.39421290654511171663E-5, 5.65978713036027009243E-7,
+        };
+
+        constexpr double airy_APGN[11] = {
+            -3.55615429033082288335E-2, -6.37311518129435504426E-1,  -1.70856738884312371053E0,
+            -1.50221872117316635393E0,  -5.63606665822102676611E-1,  -1.02101031120216891789E-1,
+            -9.48396695961445269093E-3, -4.60325307486780994357E-4,  -1.14300836484517375919E-5,
+            -1.33415518685547420648E-7, -5.63803833958893494476E-10,
+        };
+
+        constexpr double airy_APGD[11] = {
+            /*  1.00000000000000000000E0, */
+            9.85865801696130355144E0,  2.16401867356585941885E1,  1.73130776389749389525E1,  6.17872175280828766327E0,
+            1.08848694396321495475E0,  9.95005543440888479402E-2, 4.78468199683886610842E-3, 1.18159633322838625562E-4,
+            1.37480673554219441465E-6, 5.79912514929147598821E-9,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline int airy(double x, double *ai, double *aip, double *bi, double *bip) {
+        double z, zz, t, f, g, uf, ug, k, zeta, theta;
+        int domflg;
+
+        domflg = 0;
+        if (x > detail::MAXAIRY) {
+            *ai = 0;
+            *aip = 0;
+            *bi = std::numeric_limits::infinity();
+            *bip = std::numeric_limits::infinity();
+            return (-1);
+        }
+
+        if (x < -2.09) {
+            domflg = 15;
+            t = std::sqrt(-x);
+            zeta = -2.0 * x * t / 3.0;
+            t = std::sqrt(t);
+            k = detail::SQRT1OPI / t;
+            z = 1.0 / zeta;
+            zz = z * z;
+            uf = 1.0 + zz * polevl(zz, detail::airy_AFN, 8) / p1evl(zz, detail::airy_AFD, 9);
+            ug = z * polevl(zz, detail::airy_AGN, 10) / p1evl(zz, detail::airy_AGD, 10);
+            theta = zeta + 0.25 * M_PI;
+            f = std::sin(theta);
+            g = std::cos(theta);
+            *ai = k * (f * uf - g * ug);
+            *bi = k * (g * uf + f * ug);
+            uf = 1.0 + zz * polevl(zz, detail::airy_APFN, 8) / p1evl(zz, detail::airy_APFD, 9);
+            ug = z * polevl(zz, detail::airy_APGN, 10) / p1evl(zz, detail::airy_APGD, 10);
+            k = detail::SQRT1OPI * t;
+            *aip = -k * (g * uf + f * ug);
+            *bip = k * (f * uf - g * ug);
+            return (0);
+        }
+
+        if (x >= 2.09) { /* cbrt(9) */
+            domflg = 5;
+            t = std::sqrt(x);
+            zeta = 2.0 * x * t / 3.0;
+            g = std::exp(zeta);
+            t = std::sqrt(t);
+            k = 2.0 * t * g;
+            z = 1.0 / zeta;
+            f = polevl(z, detail::airy_AN, 7) / polevl(z, detail::airy_AD, 7);
+            *ai = detail::SQRT1OPI * f / k;
+            k = -0.5 * detail::SQRT1OPI * t / g;
+            f = polevl(z, detail::airy_APN, 7) / polevl(z, detail::airy_APD, 7);
+            *aip = f * k;
+
+            if (x > 8.3203353) { /* zeta > 16 */
+                f = z * polevl(z, detail::airy_BN16, 4) / p1evl(z, detail::airy_BD16, 5);
+                k = detail::SQRT1OPI * g;
+                *bi = k * (1.0 + f) / t;
+                f = z * polevl(z, detail::airy_BPPN, 4) / p1evl(z, detail::airy_BPPD, 5);
+                *bip = k * t * (1.0 + f);
+                return (0);
+            }
+        }
+
+        f = 1.0;
+        g = x;
+        t = 1.0;
+        uf = 1.0;
+        ug = x;
+        k = 1.0;
+        z = x * x * x;
+        while (t > detail::MACHEP) {
+            uf *= z;
+            k += 1.0;
+            uf /= k;
+            ug *= z;
+            k += 1.0;
+            ug /= k;
+            uf /= k;
+            f += uf;
+            k += 1.0;
+            ug /= k;
+            g += ug;
+            t = std::abs(uf / f);
+        }
+        uf = detail::airy_c1 * f;
+        ug = detail::airy_c2 * g;
+        if ((domflg & 1) == 0) {
+            *ai = uf - ug;
+        }
+        if ((domflg & 2) == 0) {
+            *bi = detail::SQRT3 * (uf + ug);
+        }
+
+        /* the deriviative of ai */
+        k = 4.0;
+        uf = x * x / 2.0;
+        ug = z / 3.0;
+        f = uf;
+        g = 1.0 + ug;
+        uf /= 3.0;
+        t = 1.0;
+
+        while (t > detail::MACHEP) {
+            uf *= z;
+            ug /= k;
+            k += 1.0;
+            ug *= z;
+            uf /= k;
+            f += uf;
+            k += 1.0;
+            ug /= k;
+            uf /= k;
+            g += ug;
+            k += 1.0;
+            t = std::abs(ug / g);
+        }
+
+        uf = detail::airy_c1 * f;
+        ug = detail::airy_c2 * g;
+        if ((domflg & 4) == 0) {
+            *aip = uf - ug;
+        }
+        if ((domflg & 8) == 0) {
+            *bip = detail::SQRT3 * (uf + ug);
+        };
+        return (0);
+    }
+
+    inline int airy(float xf, float *aif, float *aipf, float *bif, float *bipf) {
+        double ai;
+        double aip;
+        double bi;
+        double bip;
+        int res = cephes::airy(xf, &ai, &aip, &bi, &bip);
+
+        *aif = ai;
+        *aipf = aip;
+        *bif = bi;
+        *bipf = bip;
+        return res;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h
new file mode 100644
index 0000000000000000000000000000000000000000..d113b8b7d0f4ae4e7ad9da2faf66d3ab7406d736
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h
@@ -0,0 +1,51 @@
+/* Translated into C++ by SciPy developers in 2024.
+ *
+ * This was not part of the original cephes library.
+ */
+#pragma once
+
+#include "../config.h"
+#include "gamma.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+
+        constexpr double besselpoly_EPS = 1.0e-17;
+    }
+
+    XSF_HOST_DEVICE inline double besselpoly(double a, double lambda, double nu) {
+
+        int m, factor = 0;
+        double Sm, relerr, Sol;
+        double sum = 0.0;
+
+        /* Special handling for a = 0.0 */
+        if (a == 0.0) {
+            if (nu == 0.0) {
+                return 1.0 / (lambda + 1);
+            } else {
+                return 0.0;
+            }
+        }
+        /* Special handling for negative and integer nu */
+        if ((nu < 0) && (std::floor(nu) == nu)) {
+            nu = -nu;
+            factor = static_cast(nu) % 2;
+        }
+        Sm = std::exp(nu * std::log(a)) / (Gamma(nu + 1) * (lambda + nu + 1));
+        m = 0;
+        do {
+            sum += Sm;
+            Sol = Sm;
+            Sm *= -a * a * (lambda + nu + 1 + 2 * m) / ((nu + m + 1) * (m + 1) * (lambda + nu + 1 + 2 * m + 2));
+            m++;
+            relerr = std::abs((Sm - Sol) / Sm);
+        } while (relerr > detail::besselpoly_EPS && m < 1000);
+        if (!factor)
+            return sum;
+        else
+            return -sum;
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h
new file mode 100644
index 0000000000000000000000000000000000000000..437262793e8f94b229671978b23a638820ff1290
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h
@@ -0,0 +1,257 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     beta.c
+ *
+ *     Beta function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, y, beta();
+ *
+ * y = beta( a, b );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *                   -     -
+ *                  | (a) | (b)
+ * beta( a, b )  =  -----------.
+ *                     -
+ *                    | (a+b)
+ *
+ * For large arguments the logarithm of the function is
+ * evaluated using lgam(), then exponentiated.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,30       30000       8.1e-14     1.1e-14
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * beta overflow    log(beta) > MAXLOG       0.0
+ *                  a or b <0 integer        0.0
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE double beta(double, double);
+    XSF_HOST_DEVICE double lbeta(double, double);
+
+    namespace detail {
+        constexpr double beta_ASYMP_FACTOR = 1e6;
+
+        /*
+         * Asymptotic expansion for  ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1).
+         */
+        XSF_HOST_DEVICE inline double lbeta_asymp(double a, double b, int *sgn) {
+            double r = lgam_sgn(b, sgn);
+            r -= b * std::log(a);
+
+            r += b * (1 - b) / (2 * a);
+            r += b * (1 - b) * (1 - 2 * b) / (12 * a * a);
+            r += -b * b * (1 - b) * (1 - b) / (12 * a * a * a);
+
+            return r;
+        }
+
+        /*
+         * Special case for a negative integer argument
+         */
+
+        XSF_HOST_DEVICE inline double beta_negint(int a, double b) {
+            int sgn;
+            if (b == static_cast(b) && 1 - a - b > 0) {
+                sgn = (static_cast(b) % 2 == 0) ? 1 : -1;
+                return sgn * xsf::cephes::beta(1 - a - b, b);
+            } else {
+                set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+
+        XSF_HOST_DEVICE inline double lbeta_negint(int a, double b) {
+            double r;
+            if (b == static_cast(b) && 1 - a - b > 0) {
+                r = xsf::cephes::lbeta(1 - a - b, b);
+                return r;
+            } else {
+                set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double beta(double a, double b) {
+        double y;
+        int sign = 1;
+
+        if (a <= 0.0) {
+            if (a == std::floor(a)) {
+                if (a == static_cast(a)) {
+                    return detail::beta_negint(static_cast(a), b);
+                } else {
+                    goto overflow;
+                }
+            }
+        }
+
+        if (b <= 0.0) {
+            if (b == std::floor(b)) {
+                if (b == static_cast(b)) {
+                    return detail::beta_negint(static_cast(b), a);
+                } else {
+                    goto overflow;
+                }
+            }
+        }
+
+        if (std::abs(a) < std::abs(b)) {
+            y = a;
+            a = b;
+            b = y;
+        }
+
+        if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
+            /* Avoid loss of precision in lgam(a + b) - lgam(a) */
+            y = detail::lbeta_asymp(a, b, &sign);
+            return sign * std::exp(y);
+        }
+
+        y = a + b;
+        if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
+            int sgngam;
+            y = detail::lgam_sgn(y, &sgngam);
+            sign *= sgngam; /* keep track of the sign */
+            y = detail::lgam_sgn(b, &sgngam) - y;
+            sign *= sgngam;
+            y = detail::lgam_sgn(a, &sgngam) + y;
+            sign *= sgngam;
+            if (y > detail::MAXLOG) {
+                goto overflow;
+            }
+            return (sign * std::exp(y));
+        }
+
+        y = rgamma(y);
+        a = Gamma(a);
+        b = Gamma(b);
+        if (std::isinf(y)) {
+            goto overflow;
+	}
+
+        if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) {
+            y = b * y;
+            y *= a;
+        } else {
+            y = a * y;
+            y *= b;
+        }
+
+        return (y);
+
+    overflow:
+        set_error("beta", SF_ERROR_OVERFLOW, NULL);
+        return (sign * std::numeric_limits::infinity());
+    }
+
+    /* Natural log of |beta|. */
+
+    XSF_HOST_DEVICE inline double lbeta(double a, double b) {
+        double y;
+        int sign;
+
+        sign = 1;
+
+        if (a <= 0.0) {
+            if (a == std::floor(a)) {
+                if (a == static_cast(a)) {
+                    return detail::lbeta_negint(static_cast(a), b);
+                } else {
+                    goto over;
+                }
+            }
+        }
+
+        if (b <= 0.0) {
+            if (b == std::floor(b)) {
+                if (b == static_cast(b)) {
+                    return detail::lbeta_negint(static_cast(b), a);
+                } else {
+                    goto over;
+                }
+            }
+        }
+
+        if (std::abs(a) < std::abs(b)) {
+            y = a;
+            a = b;
+            b = y;
+        }
+
+        if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
+            /* Avoid loss of precision in lgam(a + b) - lgam(a) */
+            y = detail::lbeta_asymp(a, b, &sign);
+            return y;
+        }
+
+        y = a + b;
+        if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
+            int sgngam;
+            y = detail::lgam_sgn(y, &sgngam);
+            sign *= sgngam; /* keep track of the sign */
+            y = detail::lgam_sgn(b, &sgngam) - y;
+            sign *= sgngam;
+            y = detail::lgam_sgn(a, &sgngam) + y;
+            sign *= sgngam;
+            return (y);
+        }
+
+        y = rgamma(y);
+        a = Gamma(a);
+        b = Gamma(b);
+        if (std::isinf(y)) {
+        over:
+            set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+            return (sign * std::numeric_limits::infinity());
+        }
+
+        if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) {
+            y = b * y;
+            y *= a;
+        } else {
+            y = a * y;
+            y *= b;
+        }
+
+        if (y < 0) {
+            y = -y;
+        }
+
+        return (std::log(y));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h
new file mode 100644
index 0000000000000000000000000000000000000000..3e9fbd4eab45b24f1caa8b509c9d1d3c536867fe
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h
@@ -0,0 +1,131 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     cbrt.c
+ *
+ *     Cube root
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cbrt();
+ *
+ * y = cbrt( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the cube root of the argument, which may be negative.
+ *
+ * Range reduction involves determining the power of 2 of
+ * the argument.  A polynomial of degree 2 applied to the
+ * mantissa, and multiplication by the cube root of 1, 2, or 4
+ * approximates the root to within about 0.1%.  Then Newton's
+ * iteration is used three times to converge to an accurate
+ * result.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,1e308     30000      1.5e-16     5.0e-17
+ *
+ */
+/*							cbrt.c  */
+
+/*
+ * Cephes Math Library Release 2.2:  January, 1991
+ * Copyright 1984, 1991 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double CBRT2 = 1.2599210498948731647672;
+        constexpr double CBRT4 = 1.5874010519681994747517;
+        constexpr double CBRT2I = 0.79370052598409973737585;
+        constexpr double CBRT4I = 0.62996052494743658238361;
+
+        XSF_HOST_DEVICE inline double cbrt(double x) {
+            int e, rem, sign;
+            double z;
+
+            if (!std::isfinite(x)) {
+                return x;
+            }
+            if (x == 0) {
+                return (x);
+            }
+            if (x > 0) {
+                sign = 1;
+            } else {
+                sign = -1;
+                x = -x;
+            }
+
+            z = x;
+            /* extract power of 2, leaving
+             * mantissa between 0.5 and 1
+             */
+            x = std::frexp(x, &e);
+
+            /* Approximate cube root of number between .5 and 1,
+             * peak relative error = 9.2e-6
+             */
+            x = (((-1.3466110473359520655053e-1 * x + 5.4664601366395524503440e-1) * x - 9.5438224771509446525043e-1) *
+                     x +
+                 1.1399983354717293273738e0) *
+                    x +
+                4.0238979564544752126924e-1;
+
+            /* exponent divided by 3 */
+            if (e >= 0) {
+                rem = e;
+                e /= 3;
+                rem -= 3 * e;
+                if (rem == 1) {
+                    x *= CBRT2;
+                } else if (rem == 2) {
+                    x *= CBRT4;
+                }
+            }
+            /* argument less than 1 */
+            else {
+                e = -e;
+                rem = e;
+                e /= 3;
+                rem -= 3 * e;
+                if (rem == 1) {
+                    x *= CBRT2I;
+                } else if (rem == 2) {
+                    x *= CBRT4I;
+                }
+                e = -e;
+            }
+
+            /* multiply by power of 2 */
+            x = std::ldexp(x, e);
+
+            /* Newton iteration */
+            x -= (x - (z / (x * x))) * 0.33333333333333333333;
+            x -= (x - (z / (x * x))) * 0.33333333333333333333;
+
+            if (sign < 0)
+                x = -x;
+            return (x);
+        }
+    } // namespace detail
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h
new file mode 100644
index 0000000000000000000000000000000000000000..caaa74fc7b81015784608cc38aed5987ca145526
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h
@@ -0,0 +1,85 @@
+/*                                                     chbevl.c
+ *
+ *     Evaluate Chebyshev series
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int N;
+ * double x, y, coef[N], chebevl();
+ *
+ * y = chbevl( x, coef, N );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the series
+ *
+ *        N-1
+ *         - '
+ *  y  =   >   coef[i] T (x/2)
+ *         -            i
+ *        i=0
+ *
+ * of Chebyshev polynomials Ti at argument x/2.
+ *
+ * Coefficients are stored in reverse order, i.e. the zero
+ * order term is last in the array.  Note N is the number of
+ * coefficients, not the order.
+ *
+ * If coefficients are for the interval a to b, x must
+ * have been transformed to x -> 2(2x - b - a)/(b-a) before
+ * entering the routine.  This maps x from (a, b) to (-1, 1),
+ * over which the Chebyshev polynomials are defined.
+ *
+ * If the coefficients are for the inverted interval, in
+ * which (a, b) is mapped to (1/b, 1/a), the transformation
+ * required is x -> 2(2ab/x - b - a)/(b-a).  If b is infinity,
+ * this becomes x -> 4a/x - 1.
+ *
+ *
+ *
+ * SPEED:
+ *
+ * Taking advantage of the recurrence properties of the
+ * Chebyshev polynomials, the routine requires one more
+ * addition per loop than evaluating a nested polynomial of
+ * the same degree.
+ *
+ */
+/*							chbevl.c	*/
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE double chbevl(double x, const double array[], int n) {
+        double b0, b1, b2;
+        const double *p;
+        int i;
+
+        p = array;
+        b0 = *p++;
+        b1 = 0.0;
+        i = n - 1;
+
+        do {
+            b2 = b1;
+            b1 = b0;
+            b0 = x * b1 - b2 + *p++;
+        } while (--i);
+
+        return (0.5 * (b0 - b2));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h
new file mode 100644
index 0000000000000000000000000000000000000000..0a97def6d00baa18eaffaca73c92d7b6dd2b5e32
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h
@@ -0,0 +1,193 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     chdtr.c
+ *
+ *     Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double df, x, y, chdtr();
+ *
+ * y = chdtr( df, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the left hand tail (from 0 to x)
+ * of the Chi square probability density function with
+ * v degrees of freedom.
+ *
+ *
+ *                                  inf.
+ *                                    -
+ *                        1          | |  v/2-1  -t/2
+ *  P( x | v )   =   -----------     |   t      e     dt
+ *                    v/2  -       | |
+ *                   2    | (v/2)   -
+ *                                   x
+ *
+ * where x is the Chi-square variable.
+ *
+ * The incomplete Gamma integral is used, according to the
+ * formula
+ *
+ *     y = chdtr( v, x ) = igam( v/2.0, x/2.0 ).
+ *
+ *
+ * The arguments must both be positive.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igam().
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtr domain   x < 0 or v < 1        0.0
+ */
+/*							chdtrc()
+ *
+ *	Complemented Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, chdtrc();
+ *
+ * y = chdtrc( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the right hand tail (from x to
+ * infinity) of the Chi square probability density function
+ * with v degrees of freedom:
+ *
+ *
+ *                                  inf.
+ *                                    -
+ *                        1          | |  v/2-1  -t/2
+ *  P( x | v )   =   -----------     |   t      e     dt
+ *                    v/2  -       | |
+ *                   2    | (v/2)   -
+ *                                   x
+ *
+ * where x is the Chi-square variable.
+ *
+ * The incomplete Gamma integral is used, according to the
+ * formula
+ *
+ *	y = chdtr( v, x ) = igamc( v/2.0, x/2.0 ).
+ *
+ *
+ * The arguments must both be positive.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igamc().
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtrc domain  x < 0 or v < 1        0.0
+ */
+/*							chdtri()
+ *
+ *	Inverse of complemented Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double df, x, y, chdtri();
+ *
+ * x = chdtri( df, y );
+ *
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Finds the Chi-square argument x such that the integral
+ * from x to infinity of the Chi-square density is equal
+ * to the given cumulative probability y.
+ *
+ * This is accomplished using the inverse Gamma integral
+ * function and the relation
+ *
+ *    x/2 = igamci( df/2, y );
+ *
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igami.c.
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtri domain   y < 0 or y > 1        0.0
+ *                     v < 1
+ *
+ */
+
+/*                                                             chdtr() */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "igam.h"
+#include "igami.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE inline double chdtrc(double df, double x) {
+
+        if (x < 0.0)
+            return 1.0; /* modified by T. Oliphant */
+        return (igamc(df / 2.0, x / 2.0));
+    }
+
+    XSF_HOST_DEVICE inline double chdtr(double df, double x) {
+
+        if ((x < 0.0)) { /* || (df < 1.0) ) */
+            set_error("chdtr", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+        return (igam(df / 2.0, x / 2.0));
+    }
+
+    XSF_HOST_DEVICE double chdtri(double df, double y) {
+        double x;
+
+        if ((y < 0.0) || (y > 1.0)) { /* || (df < 1.0) ) */
+            set_error("chdtri", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        x = igamci(0.5 * df, y);
+        return (2.0 * x);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h
new file mode 100644
index 0000000000000000000000000000000000000000..d7b162c5efc8e11f407c6108d55c117820e9e76d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h
@@ -0,0 +1,87 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ *
+ * Since we support only IEEE-754 floating point numbers, conditional logic
+ * supporting other arithmetic types has been removed.
+ */
+
+/*
+ *
+ *
+ *                                                   const.c
+ *
+ *     Globally declared constants
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * extern double nameofconstant;
+ *
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * This file contains a number of mathematical constants and
+ * also some needed size parameters of the computer arithmetic.
+ * The values are supplied as arrays of hexadecimal integers
+ * for IEEE arithmetic, and in a normal decimal scientific notation for
+ * other machines.  The particular notation used is determined
+ * by a symbol (IBMPC, or UNK) defined in the include file
+ * mconf.h.
+ *
+ * The default size parameters are as follows.
+ *
+ * For UNK mode:
+ * MACHEP =  1.38777878078144567553E-17       2**-56
+ * MAXLOG =  8.8029691931113054295988E1       log(2**127)
+ * MINLOG = -8.872283911167299960540E1        log(2**-128)
+ *
+ * For IEEE arithmetic (IBMPC):
+ * MACHEP =  1.11022302462515654042E-16       2**-53
+ * MAXLOG =  7.09782712893383996843E2         log(2**1024)
+ * MINLOG = -7.08396418532264106224E2         log(2**-1022)
+ *
+ * The global symbols for mathematical constants are
+ * SQ2OPI =  7.9788456080286535587989E-1      sqrt( 2/pi )
+ * LOGSQ2 =  3.46573590279972654709E-1        log(2)/2
+ * THPIO4 =  2.35619449019234492885           3*pi/4
+ *
+ * These lists are subject to change.
+ */
+/*                                                     const.c */
+
+/*
+ * Cephes Math Library Release 2.3:  March, 1995
+ * Copyright 1984, 1995 by Stephen L. Moshier
+ */
+#pragma once
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr std::uint64_t MAXITER = 500;
+        constexpr double MACHEP = 1.11022302462515654042E-16;    // 2**-53
+        constexpr double MAXLOG = 7.09782712893383996732E2;      // log(DBL_MAX)
+        constexpr double MINLOG = -7.451332191019412076235E2;    // log 2**-1022
+        constexpr double SQRT1OPI = 5.64189583547756286948E-1;   // sqrt( 1/pi)
+        constexpr double SQRT2OPI = 7.9788456080286535587989E-1; // sqrt( 2/pi )
+        constexpr double SQRT2PI = 0.79788456080286535587989;    // sqrt(2pi)
+        constexpr double LOGSQ2 = 3.46573590279972654709E-1;     // log(2)/2
+        constexpr double THPIO4 = 2.35619449019234492885;        // 3*pi/4
+        constexpr double SQRT3 = 1.732050807568877293527;        // sqrt(3)
+        constexpr double PI180 = 1.74532925199432957692E-2;      // pi/180
+        constexpr double SQRTPI = 2.50662827463100050242E0;      // sqrt(pi)
+        constexpr double LOGPI = 1.14472988584940017414;         // log(pi)
+        constexpr double MAXGAM = 171.624376956302725;
+        constexpr double LOGSQRT2PI = 0.9189385332046727; // log(sqrt(pi))
+
+        // Following two added by SciPy developers.
+        // Euler's constant
+        constexpr double SCIPY_EULER = 0.577215664901532860606512090082402431;
+        // e as long double
+        constexpr long double SCIPY_El = 2.718281828459045235360287471352662498L;
+    } // namespace detail
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h
new file mode 100644
index 0000000000000000000000000000000000000000..a455599b4a95b3c69d23df188669e84deac4e31c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h
@@ -0,0 +1,293 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellie.c
+ *
+ *     Incomplete elliptic integral of the second kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double phi, m, y, ellie();
+ *
+ * y = ellie( phi, m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *                 phi
+ *                  -
+ *                 | |
+ *                 |                   2
+ * E(phi_\m)  =    |    sqrt( 1 - m sin t ) dt
+ *                 |
+ *               | |
+ *                -
+ *                 0
+ *
+ * of amplitude phi and modulus m, using the arithmetic -
+ * geometric mean algorithm.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random arguments with phi in [-10, 10] and m in
+ * [0, 1].
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -10,10      150000       3.3e-15     1.4e-16
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987, 1993 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+/* Copyright 2014, Eric W. Moore */
+
+/*     Incomplete elliptic integral of second kind     */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "ellpe.h"
+#include "ellpk.h"
+#include "unity.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+
+        /* To calculate legendre's incomplete elliptical integral of the second kind for
+         * negative m, we use a power series in phi for small m*phi*phi, an asymptotic
+         * series in m for large m*phi*phi* and the relation to Carlson's symmetric
+         * integrals, R_F(x,y,z) and R_D(x,y,z).
+         *
+         * E(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0)
+         *             - m * sin(phi)^3 * R_D(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) / 3
+         *
+         *           = R_F(c-1, c-m, c) - m * R_D(c-1, c-m, c) / 3
+         *
+         * where c = csc(phi)^2. We use the second form of this for (approximately)
+         * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we
+         * use the first form, accounting for the smallness of phi.
+         *
+         * The algorithm used is described in Carlson, B. C. Numerical computation of
+         * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227
+         * Most variable names reflect Carlson's usage.
+         *
+         * In this routine, we assume m < 0 and  0 > phi > pi/2.
+         */
+        XSF_HOST_DEVICE inline double ellie_neg_m(double phi, double m) {
+            double x, y, z, x1, y1, z1, ret, Q;
+            double A0f, Af, Xf, Yf, Zf, E2f, E3f, scalef;
+            double A0d, Ad, seriesn, seriesd, Xd, Yd, Zd, E2d, E3d, E4d, E5d, scaled;
+            int n = 0;
+            double mpp = (m * phi) * phi;
+
+            if (-mpp < 1e-6 && phi < -m) {
+                return phi + (mpp * phi * phi / 30.0 - mpp * mpp / 40.0 - mpp / 6.0) * phi;
+            }
+
+            if (-mpp > 1e6) {
+                double sm = std::sqrt(-m);
+                double sp = std::sin(phi);
+                double cp = std::cos(phi);
+
+                double a = -cosm1(phi);
+                double b1 = std::log(4 * sp * sm / (1 + cp));
+                double b = -(0.5 + b1) / 2.0 / m;
+                double c = (0.75 + cp / sp / sp - b1) / 16.0 / m / m;
+                return (a + b + c) * sm;
+            }
+
+            if (phi > 1e-153 && m > -1e200) {
+                double s = std::sin(phi);
+                double csc2 = 1.0 / s / s;
+                scalef = 1.0;
+                scaled = m / 3.0;
+                x = 1.0 / std::tan(phi) / std::tan(phi);
+                y = csc2 - m;
+                z = csc2;
+            } else {
+                scalef = phi;
+                scaled = mpp * phi / 3.0;
+                x = 1.0;
+                y = 1 - mpp;
+                z = 1.0;
+            }
+
+            if (x == y && x == z) {
+                return (scalef + scaled / x) / std::sqrt(x);
+            }
+
+            A0f = (x + y + z) / 3.0;
+            Af = A0f;
+            A0d = (x + y + 3.0 * z) / 5.0;
+            Ad = A0d;
+            x1 = x;
+            y1 = y;
+            z1 = z;
+            seriesd = 0.0;
+            seriesn = 1.0;
+            /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps,
+             * it is ~338.38. */
+
+            /* N.B. This will evaluate its arguments multiple times. */
+            Q = 400.0 * std::fmax(std::abs(A0f - x), std::fmax(std::abs(A0f - y), std::abs(A0f - z)));
+
+            while (Q > std::abs(Af) && Q > std::abs(Ad) && n <= 100) {
+                double sx = std::sqrt(x1);
+                double sy = std::sqrt(y1);
+                double sz = std::sqrt(z1);
+                double lam = sx * sy + sx * sz + sy * sz;
+                seriesd += seriesn / (sz * (z1 + lam));
+                x1 = (x1 + lam) / 4.0;
+                y1 = (y1 + lam) / 4.0;
+                z1 = (z1 + lam) / 4.0;
+                Af = (x1 + y1 + z1) / 3.0;
+                Ad = (Ad + lam) / 4.0;
+                n += 1;
+                Q /= 4.0;
+                seriesn /= 4.0;
+            }
+
+            Xf = (A0f - x) / Af / (1 << 2 * n);
+            Yf = (A0f - y) / Af / (1 << 2 * n);
+            Zf = -(Xf + Yf);
+
+            E2f = Xf * Yf - Zf * Zf;
+            E3f = Xf * Yf * Zf;
+
+            ret = scalef * (1.0 - E2f / 10.0 + E3f / 14.0 + E2f * E2f / 24.0 - 3.0 * E2f * E3f / 44.0) / sqrt(Af);
+
+            Xd = (A0d - x) / Ad / (1 << 2 * n);
+            Yd = (A0d - y) / Ad / (1 << 2 * n);
+            Zd = -(Xd + Yd) / 3.0;
+
+            E2d = Xd * Yd - 6.0 * Zd * Zd;
+            E3d = (3 * Xd * Yd - 8.0 * Zd * Zd) * Zd;
+            E4d = 3.0 * (Xd * Yd - Zd * Zd) * Zd * Zd;
+            E5d = Xd * Yd * Zd * Zd * Zd;
+
+            ret -= scaled *
+                   (1.0 - 3.0 * E2d / 14.0 + E3d / 6.0 + 9.0 * E2d * E2d / 88.0 - 3.0 * E4d / 22.0 -
+                    9.0 * E2d * E3d / 52.0 + 3.0 * E5d / 26.0) /
+                   (1 << 2 * n) / Ad / sqrt(Ad);
+            ret -= 3.0 * scaled * seriesd;
+            return ret;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellie(double phi, double m) {
+        double a, b, c, e, temp;
+        double lphi, t, E, denom, npio2;
+        int d, mod, sign;
+
+        if (std::isnan(phi) || std::isnan(m))
+            return std::numeric_limits::quiet_NaN();
+        if (m > 1.0)
+            return std::numeric_limits::quiet_NaN();
+        ;
+        if (std::isinf(phi))
+            return phi;
+        if (std::isinf(m))
+            return -m;
+        if (m == 0.0)
+            return (phi);
+        lphi = phi;
+        npio2 = std::floor(lphi / M_PI_2);
+        if (std::fmod(std::abs(npio2), 2.0) == 1.0)
+            npio2 += 1;
+        lphi = lphi - npio2 * M_PI_2;
+        if (lphi < 0.0) {
+            lphi = -lphi;
+            sign = -1;
+        } else {
+            sign = 1;
+        }
+        a = 1.0 - m;
+        E = ellpe(m);
+        if (a == 0.0) {
+            temp = std::sin(lphi);
+            goto done;
+        }
+        if (a > 1.0) {
+            temp = detail::ellie_neg_m(lphi, m);
+            goto done;
+        }
+
+        if (lphi < 0.135) {
+            double m11 = (((((-7.0 / 2816.0) * m + (5.0 / 1056.0)) * m - (7.0 / 2640.0)) * m + (17.0 / 41580.0)) * m -
+                          (1.0 / 155925.0)) *
+                         m;
+            double m9 = ((((-5.0 / 1152.0) * m + (1.0 / 144.0)) * m - (1.0 / 360.0)) * m + (1.0 / 5670.0)) * m;
+            double m7 = ((-m / 112.0 + (1.0 / 84.0)) * m - (1.0 / 315.0)) * m;
+            double m5 = (-m / 40.0 + (1.0 / 30)) * m;
+            double m3 = -m / 6.0;
+            double p2 = lphi * lphi;
+
+            temp = ((((m11 * p2 + m9) * p2 + m7) * p2 + m5) * p2 + m3) * p2 * lphi + lphi;
+            goto done;
+        }
+        t = std::tan(lphi);
+        b = std::sqrt(a);
+        /* Thanks to Brian Fitzgerald 
+         * for pointing out an instability near odd multiples of pi/2.  */
+        if (std::abs(t) > 10.0) {
+            /* Transform the amplitude */
+            e = 1.0 / (b * t);
+            /* ... but avoid multiple recursions.  */
+            if (std::abs(e) < 10.0) {
+                e = std::atan(e);
+                temp = E + m * std::sin(lphi) * std::sin(e) - ellie(e, m);
+                goto done;
+            }
+        }
+        c = std::sqrt(m);
+        a = 1.0;
+        d = 1;
+        e = 0.0;
+        mod = 0;
+
+        while (std::abs(c / a) > detail::MACHEP) {
+            temp = b / a;
+            lphi = lphi + atan(t * temp) + mod * M_PI;
+            denom = 1 - temp * t * t;
+            if (std::abs(denom) > 10 * detail::MACHEP) {
+                t = t * (1.0 + temp) / denom;
+                mod = (lphi + M_PI_2) / M_PI;
+            } else {
+                t = std::tan(lphi);
+                mod = static_cast(std::floor((lphi - std::atan(t)) / M_PI));
+            }
+            c = (a - b) / 2.0;
+            temp = std::sqrt(a * b);
+            a = (a + b) / 2.0;
+            b = temp;
+            d += d;
+            e += c * std::sin(lphi);
+        }
+
+        temp = E / ellpk(1.0 - m);
+        temp *= (std::atan(t) + mod * M_PI) / (d * a);
+        temp += e;
+
+    done:
+
+        if (sign < 0)
+            temp = -temp;
+        temp += npio2 * E;
+        return (temp);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h
new file mode 100644
index 0000000000000000000000000000000000000000..c05b3ec76c2e9a3acbc947842e0a849f5ba837e0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h
@@ -0,0 +1,251 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellik.c
+ *
+ *     Incomplete elliptic integral of the first kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double phi, m, y, ellik();
+ *
+ * y = ellik( phi, m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *
+ *                phi
+ *                 -
+ *                | |
+ *                |           dt
+ * F(phi | m) =   |    ------------------
+ *                |                   2
+ *              | |    sqrt( 1 - m sin t )
+ *               -
+ *                0
+ *
+ * of amplitude phi and modulus m, using the arithmetic -
+ * geometric mean algorithm.
+ *
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random points with m in [0, 1] and phi as indicated.
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -10,10       200000      7.4e-16     1.0e-16
+ *
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+/* Copyright 2014, Eric W. Moore */
+
+/*     Incomplete elliptic integral of first kind      */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "ellpk.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* To calculate legendre's incomplete elliptical integral of the first kind for
+         * negative m, we use a power series in phi for small m*phi*phi, an asymptotic
+         * series in m for large m*phi*phi* and the relation to Carlson's symmetric
+         * integral of the first kind.
+         *
+         * F(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0)
+         *           = R_F(c-1, c-m, c)
+         *
+         * where c = csc(phi)^2. We use the second form of this for (approximately)
+         * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we
+         * use the first form, accounting for the smallness of phi.
+         *
+         * The algorithm used is described in Carlson, B. C. Numerical computation of
+         * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227
+         * Most variable names reflect Carlson's usage.
+         *
+         * In this routine, we assume m < 0 and  0 > phi > pi/2.
+         */
+        XSF_HOST_DEVICE inline double ellik_neg_m(double phi, double m) {
+            double x, y, z, x1, y1, z1, A0, A, Q, X, Y, Z, E2, E3, scale;
+            int n = 0;
+            double mpp = (m * phi) * phi;
+
+            if (-mpp < 1e-6 && phi < -m) {
+                return phi + (-mpp * phi * phi / 30.0 + 3.0 * mpp * mpp / 40.0 + mpp / 6.0) * phi;
+            }
+
+            if (-mpp > 4e7) {
+                double sm = std::sqrt(-m);
+                double sp = std::sin(phi);
+                double cp = std::cos(phi);
+
+                double a = std::log(4 * sp * sm / (1 + cp));
+                double b = -(1 + cp / sp / sp - a) / 4 / m;
+                return (a + b) / sm;
+            }
+
+            if (phi > 1e-153 && m > -1e305) {
+                double s = std::sin(phi);
+                double csc2 = 1.0 / (s * s);
+                scale = 1.0;
+                x = 1.0 / (std::tan(phi) * std::tan(phi));
+                y = csc2 - m;
+                z = csc2;
+            } else {
+                scale = phi;
+                x = 1.0;
+                y = 1 - m * scale * scale;
+                z = 1.0;
+            }
+
+            if (x == y && x == z) {
+                return scale / std::sqrt(x);
+            }
+
+            A0 = (x + y + z) / 3.0;
+            A = A0;
+            x1 = x;
+            y1 = y;
+            z1 = z;
+            /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps,
+             * it is ~338.38. */
+            Q = 400.0 * std::fmax(std::abs(A0 - x), std::fmax(std::abs(A0 - y), std::abs(A0 - z)));
+
+            while (Q > std::abs(A) && n <= 100) {
+                double sx = std::sqrt(x1);
+                double sy = std::sqrt(y1);
+                double sz = std::sqrt(z1);
+                double lam = sx * sy + sx * sz + sy * sz;
+                x1 = (x1 + lam) / 4.0;
+                y1 = (y1 + lam) / 4.0;
+                z1 = (z1 + lam) / 4.0;
+                A = (x1 + y1 + z1) / 3.0;
+                n += 1;
+                Q /= 4;
+            }
+            X = (A0 - x) / A / (1 << 2 * n);
+            Y = (A0 - y) / A / (1 << 2 * n);
+            Z = -(X + Y);
+
+            E2 = X * Y - Z * Z;
+            E3 = X * Y * Z;
+
+            return scale * (1.0 - E2 / 10.0 + E3 / 14.0 + E2 * E2 / 24.0 - 3.0 * E2 * E3 / 44.0) / sqrt(A);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellik(double phi, double m) {
+        double a, b, c, e, temp, t, K, denom, npio2;
+        int d, mod, sign;
+
+        if (std::isnan(phi) || std::isnan(m))
+            return std::numeric_limits::quiet_NaN();
+        if (m > 1.0)
+            return std::numeric_limits::quiet_NaN();
+        if (std::isinf(phi) || std::isinf(m)) {
+            if (std::isinf(m) && std::isfinite(phi))
+                return 0.0;
+            else if (std::isinf(phi) && std::isfinite(m))
+                return phi;
+            else
+                return std::numeric_limits::quiet_NaN();
+        }
+        if (m == 0.0)
+            return (phi);
+        a = 1.0 - m;
+        if (a == 0.0) {
+            if (std::abs(phi) >= (double) M_PI_2) {
+                set_error("ellik", SF_ERROR_SINGULAR, NULL);
+                return (std::numeric_limits::infinity());
+            }
+            /* DLMF 19.6.8, and 4.23.42 */
+            return std::asinh(std::tan(phi));
+        }
+        npio2 = floor(phi / M_PI_2);
+        if (std::fmod(std::abs(npio2), 2.0) == 1.0)
+            npio2 += 1;
+        if (npio2 != 0.0) {
+            K = ellpk(a);
+            phi = phi - npio2 * M_PI_2;
+        } else
+            K = 0.0;
+        if (phi < 0.0) {
+            phi = -phi;
+            sign = -1;
+        } else
+            sign = 0;
+        if (a > 1.0) {
+            temp = detail::ellik_neg_m(phi, m);
+            goto done;
+        }
+        b = std::sqrt(a);
+        t = std::tan(phi);
+        if (std::abs(t) > 10.0) {
+            /* Transform the amplitude */
+            e = 1.0 / (b * t);
+            /* ... but avoid multiple recursions.  */
+            if (std::abs(e) < 10.0) {
+                e = std::atan(e);
+                if (npio2 == 0)
+                    K = ellpk(a);
+                temp = K - ellik(e, m);
+                goto done;
+            }
+        }
+        a = 1.0;
+        c = std::sqrt(m);
+        d = 1;
+        mod = 0;
+
+        while (std::abs(c / a) > detail::MACHEP) {
+            temp = b / a;
+            phi = phi + atan(t * temp) + mod * M_PI;
+            denom = 1.0 - temp * t * t;
+            if (std::abs(denom) > 10 * detail::MACHEP) {
+                t = t * (1.0 + temp) / denom;
+                mod = (phi + M_PI_2) / M_PI;
+            } else {
+                t = std::tan(phi);
+                mod = static_cast(std::floor((phi - std::atan(t)) / M_PI));
+            }
+            c = (a - b) / 2.0;
+            temp = std::sqrt(a * b);
+            a = (a + b) / 2.0;
+            b = temp;
+            d += d;
+        }
+
+        temp = (std::atan(t) + mod * M_PI) / (d * a);
+
+    done:
+        if (sign < 0)
+            temp = -temp;
+        temp += npio2 * K;
+        return (temp);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h
new file mode 100644
index 0000000000000000000000000000000000000000..bc7c51f11acb13179aaffb301d052308722f8cfa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h
@@ -0,0 +1,107 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellpe.c
+ *
+ *     Complete elliptic integral of the second kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double m, y, ellpe();
+ *
+ * y = ellpe( m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *            pi/2
+ *             -
+ *            | |                 2
+ * E(m)  =    |    sqrt( 1 - m sin t ) dt
+ *          | |
+ *           -
+ *            0
+ *
+ * Where m = 1 - m1, using the approximation
+ *
+ *      P(x)  -  x log x Q(x).
+ *
+ * Though there are no singularities, the argument m1 is used
+ * internally rather than m for compatibility with ellpk().
+ *
+ * E(1) = 1; E(0) = pi/2.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0, 1       10000       2.1e-16     7.3e-17
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * ellpe domain      x<0, x>1            0.0
+ *
+ */
+
+/*                                                     ellpe.c         */
+
+/* Elliptic integral of second kind */
+
+/*
+ * Cephes Math Library, Release 2.1:  February, 1989
+ * Copyright 1984, 1987, 1989 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ *
+ * Feb, 2002:  altered by Travis Oliphant
+ * so that it is called with argument m
+ * (which gets immediately converted to m1 = 1-m)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ellpe_P[] = {1.53552577301013293365E-4, 2.50888492163602060990E-3, 8.68786816565889628429E-3,
+                                      1.07350949056076193403E-2, 7.77395492516787092951E-3, 7.58395289413514708519E-3,
+                                      1.15688436810574127319E-2, 2.18317996015557253103E-2, 5.68051945617860553470E-2,
+                                      4.43147180560990850618E-1, 1.00000000000000000299E0};
+
+        constexpr double ellpe_Q[] = {3.27954898576485872656E-5, 1.00962792679356715133E-3, 6.50609489976927491433E-3,
+                                      1.68862163993311317300E-2, 2.61769742454493659583E-2, 3.34833904888224918614E-2,
+                                      4.27180926518931511717E-2, 5.85936634471101055642E-2, 9.37499997197644278445E-2,
+                                      2.49999999999888314361E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellpe(double x) {
+        x = 1.0 - x;
+        if (x <= 0.0) {
+            if (x == 0.0)
+                return (1.0);
+            set_error("ellpe", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+        if (x > 1.0) {
+            return ellpe(1.0 - 1 / x) * std::sqrt(x);
+        }
+        return (polevl(x, detail::ellpe_P, 10) - std::log(x) * (x * polevl(x, detail::ellpe_Q, 9)));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h
new file mode 100644
index 0000000000000000000000000000000000000000..39ebf7e80b193d385acb45feead4b91632830642
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h
@@ -0,0 +1,117 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellpk.c
+ *
+ *     Complete elliptic integral of the first kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double m1, y, ellpk();
+ *
+ * y = ellpk( m1 );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *
+ *            pi/2
+ *             -
+ *            | |
+ *            |           dt
+ * K(m)  =    |    ------------------
+ *            |                   2
+ *          | |    sqrt( 1 - m sin t )
+ *           -
+ *            0
+ *
+ * where m = 1 - m1, using the approximation
+ *
+ *     P(x)  -  log x Q(x).
+ *
+ * The argument m1 is used internally rather than m so that the logarithmic
+ * singularity at m = 1 will be shifted to the origin; this
+ * preserves maximum accuracy.
+ *
+ * K(0) = pi/2.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,1        30000       2.5e-16     6.8e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * ellpk domain       x<0, x>1           0.0
+ *
+ */
+
+/*                                                     ellpk.c */
+
+/*
+ * Cephes Math Library, Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ellpk_P[] = {1.37982864606273237150E-4, 2.28025724005875567385E-3, 7.97404013220415179367E-3,
+                                      9.85821379021226008714E-3, 6.87489687449949877925E-3, 6.18901033637687613229E-3,
+                                      8.79078273952743772254E-3, 1.49380448916805252718E-2, 3.08851465246711995998E-2,
+                                      9.65735902811690126535E-2, 1.38629436111989062502E0};
+
+        constexpr double ellpk_Q[] = {2.94078955048598507511E-5, 9.14184723865917226571E-4, 5.94058303753167793257E-3,
+                                      1.54850516649762399335E-2, 2.39089602715924892727E-2, 3.01204715227604046988E-2,
+                                      3.73774314173823228969E-2, 4.88280347570998239232E-2, 7.03124996963957469739E-2,
+                                      1.24999999999870820058E-1, 4.99999999999999999821E-1};
+
+        constexpr double ellpk_C1 = 1.3862943611198906188E0; /* log(4) */
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellpk(double x) {
+
+        if (x < 0.0) {
+            set_error("ellpk", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        if (x > 1.0) {
+            if (std::isinf(x)) {
+                return 0.0;
+            }
+            return ellpk(1 / x) / std::sqrt(x);
+        }
+
+        if (x > detail::MACHEP) {
+            return (polevl(x, detail::ellpk_P, 10) - std::log(x) * polevl(x, detail::ellpk_Q, 10));
+        } else {
+            if (x == 0.0) {
+                set_error("ellpk", SF_ERROR_SINGULAR, NULL);
+                return (std::numeric_limits::infinity());
+            } else {
+                return (detail::ellpk_C1 - 0.5 * std::log(x));
+            }
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b0b07eab7a94fb1519566da4ef9036fb67edec6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h
@@ -0,0 +1,260 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     expn.c
+ *
+ *             Exponential integral En
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int n;
+ * double x, y, expn();
+ *
+ * y = expn( n, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the exponential integral
+ *
+ *                 inf.
+ *                   -
+ *                  | |   -xt
+ *                  |    e
+ *      E (x)  =    |    ----  dt.
+ *       n          |      n
+ *                | |     t
+ *                 -
+ *                  1
+ *
+ *
+ * Both n and x must be nonnegative.
+ *
+ * The routine employs either a power series, a continued
+ * fraction, or an asymptotic formula depending on the
+ * relative values of n and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       10000       1.7e-15     3.6e-16
+ *
+ */
+
+/*                                                     expn.c  */
+
+/* Cephes Math Library Release 1.1:  March, 1985
+ * Copyright 1985 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
+
+/* Sources
+ * [1] NIST, "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ */
+
+/* Scipy changes:
+ * - 09-10-2016: improved asymptotic expansion for large n
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "rgamma.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int expn_nA = 13;
+        constexpr double expn_A0[] = {1.00000000000000000};
+        constexpr double expn_A1[] = {1.00000000000000000};
+        constexpr double expn_A2[] = {-2.00000000000000000, 1.00000000000000000};
+        constexpr double expn_A3[] = {6.00000000000000000, -8.00000000000000000, 1.00000000000000000};
+        constexpr double expn_A4[] = {-24.0000000000000000, 58.0000000000000000, -22.0000000000000000,
+                                      1.00000000000000000};
+        constexpr double expn_A5[] = {120.000000000000000, -444.000000000000000, 328.000000000000000,
+                                      -52.0000000000000000, 1.00000000000000000};
+        constexpr double expn_A6[] = {-720.000000000000000, 3708.00000000000000,  -4400.00000000000000,
+                                      1452.00000000000000,  -114.000000000000000, 1.00000000000000000};
+        constexpr double expn_A7[] = {5040.00000000000000,  -33984.0000000000000, 58140.0000000000000,
+                                      -32120.0000000000000, 5610.00000000000000,  -240.000000000000000,
+                                      1.00000000000000000};
+        constexpr double expn_A8[] = {-40320.0000000000000, 341136.000000000000,  -785304.000000000000,
+                                      644020.000000000000,  -195800.000000000000, 19950.0000000000000,
+                                      -494.000000000000000, 1.00000000000000000};
+        constexpr double expn_A9[] = {362880.000000000000,  -3733920.00000000000, 11026296.0000000000,
+                                      -12440064.0000000000, 5765500.00000000000,  -1062500.00000000000,
+                                      67260.0000000000000,  -1004.00000000000000, 1.00000000000000000};
+        constexpr double expn_A10[] = {-3628800.00000000000, 44339040.0000000000,  -162186912.000000000,
+                                       238904904.000000000,  -155357384.000000000, 44765000.0000000000,
+                                       -5326160.00000000000, 218848.000000000000,  -2026.00000000000000,
+                                       1.00000000000000000};
+        constexpr double expn_A11[] = {39916800.0000000000,  -568356480.000000000, 2507481216.00000000,
+                                       -4642163952.00000000, 4002695088.00000000,  -1648384304.00000000,
+                                       314369720.000000000,  -25243904.0000000000, 695038.000000000000,
+                                       -4072.00000000000000, 1.00000000000000000};
+        constexpr double expn_A12[] = {-479001600.000000000, 7827719040.00000000,  -40788301824.0000000,
+                                       92199790224.0000000,  -101180433024.000000, 56041398784.0000000,
+                                       -15548960784.0000000, 2051482776.00000000,  -114876376.000000000,
+                                       2170626.00000000000,  -8166.00000000000000, 1.00000000000000000};
+        constexpr const double *expn_A[] = {expn_A0, expn_A1, expn_A2, expn_A3,  expn_A4,  expn_A5, expn_A6,
+                                            expn_A7, expn_A8, expn_A9, expn_A10, expn_A11, expn_A12};
+        constexpr int expn_Adegs[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
+
+        /* Asymptotic expansion for large n, DLMF 8.20(ii) */
+        XSF_HOST_DEVICE double expn_large_n(int n, double x) {
+            int k;
+            double p = n;
+            double lambda = x / p;
+            double multiplier = 1 / p / (lambda + 1) / (lambda + 1);
+            double fac = 1;
+            double res = 1; /* A[0] = 1 */
+            double expfac, term;
+
+            expfac = std::exp(-lambda * p) / (lambda + 1) / p;
+            if (expfac == 0) {
+                set_error("expn", SF_ERROR_UNDERFLOW, NULL);
+                return 0;
+            }
+
+            /* Do the k = 1 term outside the loop since A[1] = 1 */
+            fac *= multiplier;
+            res += fac;
+
+            for (k = 2; k < expn_nA; k++) {
+                fac *= multiplier;
+                term = fac * polevl(lambda, expn_A[k], expn_Adegs[k]);
+                res += term;
+                if (std::abs(term) < MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+
+            return expfac * res;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double expn(int n, double x) {
+        double ans, r, t, yk, xk;
+        double pk, pkm1, pkm2, qk, qkm1, qkm2;
+        double psi, z;
+        int i, k;
+        constexpr double big = 1.44115188075855872E+17;
+
+        if (std::isnan(x)) {
+            return std::numeric_limits::quiet_NaN();
+        } else if (n < 0 || x < 0) {
+            set_error("expn", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x > detail::MAXLOG) {
+            return (0.0);
+        }
+
+        if (x == 0.0) {
+            if (n < 2) {
+                set_error("expn", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            } else {
+                return (1.0 / (n - 1.0));
+            }
+        }
+
+        if (n == 0) {
+            return (std::exp(-x) / x);
+        }
+
+        /* Asymptotic expansion for large n, DLMF 8.20(ii) */
+        if (n > 50) {
+            ans = detail::expn_large_n(n, x);
+            return ans;
+        }
+
+        /* Continued fraction, DLMF 8.19.17 */
+        if (x > 1.0) {
+            k = 1;
+            pkm2 = 1.0;
+            qkm2 = x;
+            pkm1 = 1.0;
+            qkm1 = x + n;
+            ans = pkm1 / qkm1;
+
+            do {
+                k += 1;
+                if (k & 1) {
+                    yk = 1.0;
+                    xk = n + (k - 1) / 2;
+                } else {
+                    yk = x;
+                    xk = k / 2;
+                }
+                pk = pkm1 * yk + pkm2 * xk;
+                qk = qkm1 * yk + qkm2 * xk;
+                if (qk != 0) {
+                    r = pk / qk;
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else {
+                    t = 1.0;
+                }
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+                if (std::abs(pk) > big) {
+                    pkm2 /= big;
+                    pkm1 /= big;
+                    qkm2 /= big;
+                    qkm1 /= big;
+                }
+            } while (t > detail::MACHEP);
+
+            ans *= std::exp(-x);
+            return ans;
+        }
+
+        /* Power series expansion, DLMF 8.19.8 */
+        psi = -detail::SCIPY_EULER - std::log(x);
+        for (i = 1; i < n; i++) {
+            psi = psi + 1.0 / i;
+        }
+
+        z = -x;
+        xk = 0.0;
+        yk = 1.0;
+        pk = 1.0 - n;
+        if (n == 1) {
+            ans = 0.0;
+        } else {
+            ans = 1.0 / pk;
+        }
+        do {
+            xk += 1.0;
+            yk *= z / xk;
+            pk += 1.0;
+            if (pk != 0.0) {
+                ans += yk / pk;
+            }
+            if (ans != 0.0)
+                t = std::abs(yk / ans);
+            else
+                t = 1.0;
+        } while (t > detail::MACHEP);
+        k = xk;
+        t = n;
+        r = n - 1;
+        ans = (std::pow(z, r) * psi * rgamma(t)) - ans;
+        return ans;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ede1571a67ec9ce54bb6aa1afa1f17f5708f0c0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h
@@ -0,0 +1,398 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*
+ *     Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, Gamma();
+ *
+ * y = Gamma( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Gamma function of the argument.  The result is
+ * correctly signed.
+ *
+ * Arguments |x| <= 34 are reduced by recurrence and the function
+ * approximated by a rational function of degree 6/7 in the
+ * interval (2,3).  Large arguments are handled by Stirling's
+ * formula. Large negative arguments are made positive using
+ * a reflection formula.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE    -170,-33      20000       2.3e-15     3.3e-16
+ *    IEEE     -33,  33     20000       9.4e-16     2.2e-16
+ *    IEEE      33, 171.6   20000       2.3e-15     3.2e-16
+ *
+ * Error for arguments outside the test range will be larger
+ * owing to error amplification by the exponential function.
+ *
+ */
+
+/*                                                     lgam()
+ *
+ *     Natural logarithm of Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, lgam();
+ *
+ * y = lgam( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the base e (2.718...) logarithm of the absolute
+ * value of the Gamma function of the argument.
+ *
+ * For arguments greater than 13, the logarithm of the Gamma
+ * function is approximated by the logarithmic version of
+ * Stirling's formula using a polynomial approximation of
+ * degree 4. Arguments between -33 and +33 are reduced by
+ * recurrence to the interval [2,3] of a rational approximation.
+ * The cosecant reflection formula is employed for arguments
+ * less than -33.
+ *
+ * Arguments greater than MAXLGM return INFINITY and an error
+ * message.  MAXLGM = 2.556348e305 for IEEE arithmetic.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *
+ * arithmetic      domain        # trials     peak         rms
+ *    IEEE    0, 3                 28000     5.4e-16     1.1e-16
+ *    IEEE    2.718, 2.556e305     40000     3.5e-16     8.3e-17
+ * The error criterion was relative when the function magnitude
+ * was greater than one but absolute when it was less than one.
+ *
+ * The following test used the relative error criterion, though
+ * at certain points the relative error could be much higher than
+ * indicated.
+ *    IEEE    -200, -4             10000     4.8e-16     1.3e-16
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.2:  July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr double gamma_P[] = {1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2,
+                                      4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1,
+                                      9.99999999999999996796E-1};
+
+        constexpr double gamma_Q[] = {-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3,
+                                      1.18139785222060435552E-2,  3.58236398605498653373E-2, -2.34591795718243348568E-1,
+                                      7.14304917030273074085E-2,  1.00000000000000000320E0};
+
+        /* Stirling's formula for the Gamma function */
+        constexpr double gamma_STIR[5] = {
+            7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3,
+            3.47222221605458667310E-3, 8.33333333333482257126E-2,
+        };
+
+        constexpr double MAXSTIR = 143.01608;
+
+        /* Gamma function computed by Stirling's formula.
+         * The polynomial STIR is valid for 33 <= x <= 172.
+         */
+        XSF_HOST_DEVICE inline double stirf(double x) {
+            double y, w, v;
+
+            if (x >= MAXGAM) {
+                return (std::numeric_limits::infinity());
+            }
+            w = 1.0 / x;
+            w = 1.0 + w * xsf::cephes::polevl(w, gamma_STIR, 4);
+            y = std::exp(x);
+            if (x > MAXSTIR) { /* Avoid overflow in pow() */
+                v = std::pow(x, 0.5 * x - 0.25);
+                y = v * (v / y);
+            } else {
+                y = std::pow(x, x - 0.5) / y;
+            }
+            y = SQRTPI * y * w;
+            return (y);
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double Gamma(double x) {
+        double p, q, z;
+        int i;
+        int sgngam = 1;
+
+        if (!std::isfinite(x)) {
+	    if (x > 0) {
+		// gamma(+inf) = +inf
+		return x;
+	    }
+	    // gamma(NaN) and gamma(-inf) both should equal NaN.
+            return std::numeric_limits::quiet_NaN();
+        }
+
+	if (x == 0) {
+	    /* For pole at zero, value depends on sign of zero.
+	     * +inf when approaching from right, -inf when approaching
+	     * from left. */
+	    return std::copysign(std::numeric_limits::infinity(), x);
+	}
+
+        q = std::abs(x);
+
+        if (q > 33.0) {
+            if (x < 0.0) {
+                p = std::floor(q);
+                if (p == q) {
+		    // x is a negative integer. This is a pole.
+                    set_error("Gamma", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::quiet_NaN());
+                }
+                i = p;
+                if ((i & 1) == 0) {
+                    sgngam = -1;
+                }
+                z = q - p;
+                if (z > 0.5) {
+                    p += 1.0;
+                    z = q - p;
+                }
+                z = q * sinpi(z);
+                if (z == 0.0) {
+                    return (sgngam * std::numeric_limits::infinity());
+                }
+                z = std::abs(z);
+                z = M_PI / (z * detail::stirf(q));
+            } else {
+                z = detail::stirf(x);
+            }
+            return (sgngam * z);
+        }
+
+        z = 1.0;
+        while (x >= 3.0) {
+            x -= 1.0;
+            z *= x;
+        }
+
+        while (x < 0.0) {
+            if (x > -1.E-9) {
+                goto small;
+            }
+            z /= x;
+            x += 1.0;
+        }
+
+        while (x < 2.0) {
+            if (x < 1.e-9) {
+                goto small;
+            }
+            z /= x;
+            x += 1.0;
+        }
+
+        if (x == 2.0) {
+            return (z);
+        }
+
+        x -= 2.0;
+        p = polevl(x, detail::gamma_P, 6);
+        q = polevl(x, detail::gamma_Q, 7);
+        return (z * p / q);
+
+    small:
+        if (x == 0.0) {
+	    /* For this to have happened, x must have started as a negative integer. */
+	    set_error("Gamma", SF_ERROR_SINGULAR, NULL);
+	    return (std::numeric_limits::quiet_NaN());
+        } else
+            return (z / ((1.0 + 0.5772156649015329 * x) * x));
+    }
+
+    namespace detail {
+        /* A[]: Stirling's formula expansion of log Gamma
+         * B[], C[]: log Gamma function between 2 and 3
+         */
+        constexpr double gamma_A[] = {8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4,
+                                      -2.77777777730099687205E-3, 8.33333333333331927722E-2};
+
+        constexpr double gamma_B[] = {-1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5,
+                                      -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5};
+
+        constexpr double gamma_C[] = {
+            /* 1.00000000000000000000E0, */
+            -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5,
+            -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6};
+
+        /* log( sqrt( 2*pi ) ) */
+        constexpr double LS2PI = 0.91893853320467274178;
+
+        constexpr double MAXLGM = 2.556348e305;
+
+        /* Disable optimizations for this function on 32 bit systems when compiling with GCC.
+         * We've found that enabling optimizations can result in degraded precision
+         * for this asymptotic approximation in that case. */
+#if defined(__GNUC__) && defined(__i386__)
+#pragma GCC push_options
+#pragma GCC optimize("00")
+#endif
+        XSF_HOST_DEVICE inline double lgam_large_x(double x) {
+            double q = (x - 0.5) * std::log(x) - x + LS2PI;
+            if (x > 1.0e8) {
+                return (q);
+            }
+            double p = 1.0 / (x * x);
+            p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / x;
+            return q + p;
+        }
+#if defined(__GNUC__) && defined(__i386__)
+#pragma GCC pop_options
+#endif
+
+        XSF_HOST_DEVICE inline double lgam_sgn(double x, int *sign) {
+            double p, q, u, w, z;
+            int i;
+
+            *sign = 1;
+
+            if (!std::isfinite(x)) {
+                return x;
+            }
+
+            if (x < -34.0) {
+                q = -x;
+                w = lgam_sgn(q, sign);
+                p = std::floor(q);
+                if (p == q) {
+                lgsing:
+                    set_error("lgam", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::infinity());
+                }
+                i = p;
+                if ((i & 1) == 0) {
+                    *sign = -1;
+                } else {
+                    *sign = 1;
+                }
+                z = q - p;
+                if (z > 0.5) {
+                    p += 1.0;
+                    z = p - q;
+                }
+                z = q * sinpi(z);
+                if (z == 0.0) {
+                    goto lgsing;
+                }
+                /*     z = log(M_PI) - log( z ) - w; */
+                z = LOGPI - std::log(z) - w;
+                return (z);
+            }
+
+            if (x < 13.0) {
+                z = 1.0;
+                p = 0.0;
+                u = x;
+                while (u >= 3.0) {
+                    p -= 1.0;
+                    u = x + p;
+                    z *= u;
+                }
+                while (u < 2.0) {
+                    if (u == 0.0) {
+                        goto lgsing;
+                    }
+                    z /= u;
+                    p += 1.0;
+                    u = x + p;
+                }
+                if (z < 0.0) {
+                    *sign = -1;
+                    z = -z;
+                } else {
+                    *sign = 1;
+                }
+                if (u == 2.0) {
+                    return (std::log(z));
+                }
+                p -= 2.0;
+                x = x + p;
+                p = x * polevl(x, gamma_B, 5) / p1evl(x, gamma_C, 6);
+                return (std::log(z) + p);
+            }
+
+            if (x > MAXLGM) {
+                return (*sign * std::numeric_limits::infinity());
+            }
+
+            if (x >= 1000.0) {
+                return lgam_large_x(x);
+            }
+
+            q = (x - 0.5) * std::log(x) - x + LS2PI;
+            p = 1.0 / (x * x);
+            return q + polevl(p, gamma_A, 4) / x;
+        }
+    } // namespace detail
+
+    /* Logarithm of Gamma function */
+    XSF_HOST_DEVICE inline double lgam(double x) {
+        int sign;
+        return detail::lgam_sgn(x, &sign);
+    }
+
+    /* Sign of the Gamma function */
+    XSF_HOST_DEVICE inline double gammasgn(double x) {
+        double fx;
+
+        if (std::isnan(x)) {
+            return x;
+        }
+        if (x > 0) {
+            return 1.0;
+	}
+	if (x == 0) {
+	    return std::copysign(1.0, x);
+	}
+	if (std::isinf(x)) {
+	    // x > 0 case handled, so x must be negative infinity.
+	    return std::numeric_limits::quiet_NaN();
+	}
+	fx = std::floor(x);
+	if (x - fx == 0.0) {
+	    return std::numeric_limits::quiet_NaN();
+	}
+	// sign of gamma for x in (-n, -n+1) for positive integer n is (-1)^n.
+	if (static_cast(fx) % 2) {
+	    return -1.0;
+	}
+	return 1.0;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h
new file mode 100644
index 0000000000000000000000000000000000000000..f9ec54bb20326552f5748ad9360dfecfbe18d660
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h
@@ -0,0 +1,596 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                      hyp2f1.c
+ *
+ *      Gauss hypergeometric function   F
+ *                                     2 1
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, c, x, y, hyp2f1();
+ *
+ * y = hyp2f1( a, b, c, x );
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *  hyp2f1( a, b, c, x )  =   F ( a, b; c; x )
+ *                           2 1
+ *
+ *           inf.
+ *            -   a(a+1)...(a+k) b(b+1)...(b+k)   k+1
+ *   =  1 +   >   -----------------------------  x   .
+ *            -         c(c+1)...(c+k) (k+1)!
+ *          k = 0
+ *
+ *  Cases addressed are
+ *      Tests and escapes for negative integer a, b, or c
+ *      Linear transformation if c - a or c - b negative integer
+ *      Special case c = a or c = b
+ *      Linear transformation for  x near +1
+ *      Transformation for x < -0.5
+ *      Psi function expansion if x > 0.5 and c - a - b integer
+ *      Conditionally, a recurrence on c to make c-a-b > 0
+ *
+ *      x < -1  AMS 15.3.7 transformation applied (Travis Oliphant)
+ *         valid for b,a,c,(b-a) != integer and (c-a),(c-b) != negative integer
+ *
+ * x >= 1 is rejected (unless special cases are present)
+ *
+ * The parameters a, b, c are considered to be integer
+ * valued if they are within 1.0e-14 of the nearest integer
+ * (1.0e-13 for IEEE arithmetic).
+ *
+ * ACCURACY:
+ *
+ *
+ *               Relative error (-1 < x < 1):
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      -1,7        230000      1.2e-11     5.2e-14
+ *
+ * Several special cases also tested with a, b, c in
+ * the range -7 to 7.
+ *
+ * ERROR MESSAGES:
+ *
+ * A "partial loss of precision" message is printed if
+ * the internally estimated relative error exceeds 1^-12.
+ * A "singularity" message is printed on overflow or
+ * in cases not addressed (such as x < -1).
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+#include "psi.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double hyp2f1_EPS = 1.0e-13;
+
+        constexpr double hyp2f1_ETHRESH = 1.0e-12;
+        constexpr std::uint64_t hyp2f1_MAXITER = 10000;
+
+        /* hys2f1 and hyp2f1ra depend on each other, so we need this prototype */
+        XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss);
+
+        /* Defining power series expansion of Gauss hypergeometric function */
+        /* The `loss` parameter estimates loss of significance */
+        XSF_HOST_DEVICE double hys2f1(double a, double b, double c, double x, double *loss) {
+            double f, g, h, k, m, s, u, umax;
+            std::uint64_t i;
+            int ib, intflag = 0;
+
+            if (std::abs(b) > std::abs(a)) {
+                /* Ensure that |a| > |b| ... */
+                f = b;
+                b = a;
+                a = f;
+            }
+
+            ib = std::round(b);
+
+            if (std::abs(b - ib) < hyp2f1_EPS && ib <= 0 && std::abs(b) < std::abs(a)) {
+                /* .. except when `b` is a smaller negative integer */
+                f = b;
+                b = a;
+                a = f;
+                intflag = 1;
+            }
+
+            if ((std::abs(a) > std::abs(c) + 1 || intflag) && std::abs(c - a) > 2 && std::abs(a) > 2) {
+                /* |a| >> |c| implies that large cancellation error is to be expected.
+                 *
+                 * We try to reduce it with the recurrence relations
+                 */
+                return hyp2f1ra(a, b, c, x, loss);
+            }
+
+            i = 0;
+            umax = 0.0;
+            f = a;
+            g = b;
+            h = c;
+            s = 1.0;
+            u = 1.0;
+            k = 0.0;
+            do {
+                if (std::abs(h) < hyp2f1_EPS) {
+                    *loss = 1.0;
+                    return std::numeric_limits::infinity();
+                }
+                m = k + 1.0;
+                u = u * ((f + k) * (g + k) * x / ((h + k) * m));
+                s += u;
+                k = std::abs(u); /* remember largest term summed */
+                if (k > umax)
+                    umax = k;
+                k = m;
+                if (++i > hyp2f1_MAXITER) { /* should never happen */
+                    *loss = 1.0;
+                    return (s);
+                }
+            } while (s == 0 || std::abs(u / s) > MACHEP);
+
+            /* return estimated relative error */
+            *loss = (MACHEP * umax) / fabs(s) + (MACHEP * i);
+
+            return (s);
+        }
+
+        /* Apply transformations for |x| near 1 then call the power series */
+        XSF_HOST_DEVICE double hyt2f1(double a, double b, double c, double x, double *loss) {
+            double p, q, r, s, t, y, w, d, err, err1;
+            double ax, id, d1, d2, e, y1;
+            int i, aid, sign;
+
+            int ia, ib, neg_int_a = 0, neg_int_b = 0;
+
+            ia = std::round(a);
+            ib = std::round(b);
+
+            if (a <= 0 && std::abs(a - ia) < hyp2f1_EPS) { /* a is a negative integer */
+                neg_int_a = 1;
+            }
+
+            if (b <= 0 && std::abs(b - ib) < hyp2f1_EPS) { /* b is a negative integer */
+                neg_int_b = 1;
+            }
+
+            err = 0.0;
+            s = 1.0 - x;
+            if (x < -0.5 && !(neg_int_a || neg_int_b)) {
+                if (b > a)
+                    y = std::pow(s, -a) * hys2f1(a, c - b, c, -x / s, &err);
+
+                else
+                    y = std::pow(s, -b) * hys2f1(c - a, b, c, -x / s, &err);
+
+                goto done;
+            }
+
+            d = c - a - b;
+            id = std::round(d); /* nearest integer to d */
+
+            if (x > 0.9 && !(neg_int_a || neg_int_b)) {
+                if (std::abs(d - id) > MACHEP) {
+                    int sgngam;
+
+                    /* test for integer c-a-b */
+                    /* Try the power series first */
+                    y = hys2f1(a, b, c, x, &err);
+                    if (err < hyp2f1_ETHRESH) {
+                        goto done;
+                    }
+                    /* If power series fails, then apply AMS55 #15.3.6 */
+                    q = hys2f1(a, b, 1.0 - d, s, &err);
+                    sign = 1;
+                    w = lgam_sgn(d, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(c - a, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(c - b, &sgngam);
+                    sign *= sgngam;
+                    q *= sign * std::exp(w);
+                    r = std::pow(s, d) * hys2f1(c - a, c - b, d + 1.0, s, &err1);
+                    sign = 1;
+                    w = lgam_sgn(-d, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(a, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(b, &sgngam);
+                    sign *= sgngam;
+                    r *= sign * std::exp(w);
+                    y = q + r;
+
+                    q = std::abs(q); /* estimate cancellation error */
+                    r = std::abs(r);
+                    if (q > r) {
+                        r = q;
+                    }
+                    err += err1 + (MACHEP * r) / y;
+
+                    y *= xsf::cephes::Gamma(c);
+                    goto done;
+                } else {
+                    /* Psi function expansion, AMS55 #15.3.10, #15.3.11, #15.3.12
+                     *
+                     * Although AMS55 does not explicitly state it, this expansion fails
+                     * for negative integer a or b, since the psi and Gamma functions
+                     * involved have poles.
+                     */
+
+                    if (id >= 0.0) {
+                        e = d;
+                        d1 = d;
+                        d2 = 0.0;
+                        aid = id;
+                    } else {
+                        e = -d;
+                        d1 = 0.0;
+                        d2 = d;
+                        aid = -id;
+                    }
+
+                    ax = std::log(s);
+
+                    /* sum for t = 0 */
+                    y = xsf::cephes::psi(1.0) + xsf::cephes::psi(1.0 + e) - xsf::cephes::psi(a + d1) -
+                        xsf::cephes::psi(b + d1) - ax;
+                    y *= xsf::cephes::rgamma(e + 1.0);
+
+                    p = (a + d1) * (b + d1) * s * xsf::cephes::rgamma(e + 2.0); /* Poch for t=1 */
+                    t = 1.0;
+                    do {
+                        r = xsf::cephes::psi(1.0 + t) + xsf::cephes::psi(1.0 + t + e) -
+                            xsf::cephes::psi(a + t + d1) - xsf::cephes::psi(b + t + d1) - ax;
+                        q = p * r;
+                        y += q;
+                        p *= s * (a + t + d1) / (t + 1.0);
+                        p *= (b + t + d1) / (t + 1.0 + e);
+                        t += 1.0;
+                        if (t > hyp2f1_MAXITER) { /* should never happen */
+                            set_error("hyp2f1", SF_ERROR_SLOW, NULL);
+                            *loss = 1.0;
+                            return std::numeric_limits::quiet_NaN();
+                        }
+                    } while (y == 0 || std::abs(q / y) > hyp2f1_EPS);
+
+                    if (id == 0.0) {
+                        y *= xsf::cephes::Gamma(c) / (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b));
+                        goto psidon;
+                    }
+
+                    y1 = 1.0;
+
+                    if (aid == 1)
+                        goto nosum;
+
+                    t = 0.0;
+                    p = 1.0;
+                    for (i = 1; i < aid; i++) {
+                        r = 1.0 - e + t;
+                        p *= s * (a + t + d2) * (b + t + d2) / r;
+                        t += 1.0;
+                        p /= t;
+                        y1 += p;
+                    }
+                nosum:
+                    p = xsf::cephes::Gamma(c);
+                    y1 *= xsf::cephes::Gamma(e) * p *
+                          (xsf::cephes::rgamma(a + d1) * xsf::cephes::rgamma(b + d1));
+
+                    y *= p * (xsf::cephes::rgamma(a + d2) * xsf::cephes::rgamma(b + d2));
+                    if ((aid & 1) != 0)
+                        y = -y;
+
+                    q = std::pow(s, id); /* s to the id power */
+                    if (id > 0.0)
+                        y *= q;
+                    else
+                        y1 *= q;
+
+                    y += y1;
+                psidon:
+                    goto done;
+                }
+            }
+
+            /* Use defining power series if no special cases */
+            y = hys2f1(a, b, c, x, &err);
+
+        done:
+            *loss = err;
+            return (y);
+        }
+
+        /*
+          15.4.2 Abramowitz & Stegun.
+        */
+        XSF_HOST_DEVICE double hyp2f1_neg_c_equal_bc(double a, double b, double x) {
+            double k;
+            double collector = 1;
+            double sum = 1;
+            double collector_max = 1;
+
+            if (!(std::abs(b) < 1e5)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            for (k = 1; k <= -b; k++) {
+                collector *= (a + k - 1) * x / k;
+                collector_max = std::fmax(std::abs(collector), collector_max);
+                sum += collector;
+            }
+
+            if (1e-16 * (1 + collector_max / std::abs(sum)) > 1e-7) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            return sum;
+        }
+
+        /*
+         * Evaluate hypergeometric function by two-term recurrence in `a`.
+         *
+         * This avoids some of the loss of precision in the strongly alternating
+         * hypergeometric series, and can be used to reduce the `a` and `b` parameters
+         * to smaller values.
+         *
+         * AMS55 #15.2.10
+         */
+        XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss) {
+            double f2, f1, f0;
+            int n;
+            double t, err, da;
+
+            /* Don't cross c or zero */
+            if ((c < 0 && a <= c) || (c >= 0 && a >= c)) {
+                da = std::round(a - c);
+            } else {
+                da = std::round(a);
+            }
+            t = a - da;
+
+            *loss = 0;
+
+            XSF_ASSERT(da != 0);
+
+            if (std::abs(da) > hyp2f1_MAXITER) {
+                /* Too expensive to compute this value, so give up */
+                set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+                *loss = 1.0;
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            if (da < 0) {
+                /* Recurse down */
+                f2 = 0;
+                f1 = hys2f1(t, b, c, x, &err);
+                *loss += err;
+                f0 = hys2f1(t - 1, b, c, x, &err);
+                *loss += err;
+                t -= 1;
+                for (n = 1; n < -da; ++n) {
+                    f2 = f1;
+                    f1 = f0;
+                    f0 = -(2 * t - c - t * x + b * x) / (c - t) * f1 - t * (x - 1) / (c - t) * f2;
+                    t -= 1;
+                }
+            } else {
+                /* Recurse up */
+                f2 = 0;
+                f1 = hys2f1(t, b, c, x, &err);
+                *loss += err;
+                f0 = hys2f1(t + 1, b, c, x, &err);
+                *loss += err;
+                t += 1;
+                for (n = 1; n < da; ++n) {
+                    f2 = f1;
+                    f1 = f0;
+                    f0 = -((2 * t - c - t * x + b * x) * f1 + (c - t) * f2) / (t * (x - 1));
+                    t += 1;
+                }
+            }
+
+            return f0;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double hyp2f1(double a, double b, double c, double x) {
+        double d, d1, d2, e;
+        double p, q, r, s, y, ax;
+        double ia, ib, ic, id, err;
+        double t1;
+        int i, aid;
+        int neg_int_a = 0, neg_int_b = 0;
+        int neg_int_ca_or_cb = 0;
+
+        err = 0.0;
+        ax = std::abs(x);
+        s = 1.0 - x;
+        ia = std::round(a); /* nearest integer to a */
+        ib = std::round(b);
+
+        if (x == 0.0) {
+            return 1.0;
+        }
+
+        d = c - a - b;
+        id = std::round(d);
+
+        if ((a == 0 || b == 0) && c != 0) {
+            return 1.0;
+        }
+
+        if (a <= 0 && std::abs(a - ia) < detail::hyp2f1_EPS) { /* a is a negative integer */
+            neg_int_a = 1;
+        }
+
+        if (b <= 0 && std::abs(b - ib) < detail::hyp2f1_EPS) { /* b is a negative integer */
+            neg_int_b = 1;
+        }
+
+        if (d <= -1 && !(std::abs(d - id) > detail::hyp2f1_EPS && s < 0) && !(neg_int_a || neg_int_b)) {
+            return std::pow(s, d) * hyp2f1(c - a, c - b, c, x);
+        }
+        if (d <= 0 && x == 1 && !(neg_int_a || neg_int_b))
+            goto hypdiv;
+
+        if (ax < 1.0 || x == -1.0) {
+            /* 2F1(a,b;b;x) = (1-x)**(-a) */
+            if (std::abs(b - c) < detail::hyp2f1_EPS) { /* b = c */
+                if (neg_int_b) {
+                    y = detail::hyp2f1_neg_c_equal_bc(a, b, x);
+                } else {
+                    y = std::pow(s, -a); /* s to the -a power */
+                }
+                goto hypdon;
+            }
+            if (std::abs(a - c) < detail::hyp2f1_EPS) { /* a = c */
+                y = std::pow(s, -b);                    /* s to the -b power */
+                goto hypdon;
+            }
+        }
+
+        if (c <= 0.0) {
+            ic = std::round(c);                          /* nearest integer to c */
+            if (std::abs(c - ic) < detail::hyp2f1_EPS) { /* c is a negative integer */
+                /* check if termination before explosion */
+                if (neg_int_a && (ia > ic))
+                    goto hypok;
+                if (neg_int_b && (ib > ic))
+                    goto hypok;
+                goto hypdiv;
+            }
+        }
+
+        if (neg_int_a || neg_int_b) /* function is a polynomial */
+            goto hypok;
+
+        t1 = std::abs(b - a);
+        if (x < -2.0 && std::abs(t1 - round(t1)) > detail::hyp2f1_EPS) {
+            /* This transform has a pole for b-a integer, and
+             * may produce large cancellation errors for |1/x| close 1
+             */
+            p = hyp2f1(a, 1 - c + a, 1 - b + a, 1.0 / x);
+            q = hyp2f1(b, 1 - c + b, 1 - a + b, 1.0 / x);
+            p *= std::pow(-x, -a);
+            q *= std::pow(-x, -b);
+            t1 = Gamma(c);
+            s = t1 * Gamma(b - a) * (rgamma(b) * rgamma(c - a));
+            y = t1 * Gamma(a - b) * (rgamma(a) * rgamma(c - b));
+            return s * p + y * q;
+        } else if (x < -1.0) {
+            if (std::abs(a) < std::abs(b)) {
+                return std::pow(s, -a) * hyp2f1(a, c - b, c, x / (x - 1));
+            } else {
+                return std::pow(s, -b) * hyp2f1(b, c - a, c, x / (x - 1));
+            }
+        }
+
+        if (ax > 1.0) /* series diverges  */
+            goto hypdiv;
+
+        p = c - a;
+        ia = std::round(p);                                         /* nearest integer to c-a */
+        if ((ia <= 0.0) && (std::abs(p - ia) < detail::hyp2f1_EPS)) /* negative int c - a */
+            neg_int_ca_or_cb = 1;
+
+        r = c - b;
+        ib = std::round(r);                                         /* nearest integer to c-b */
+        if ((ib <= 0.0) && (std::abs(r - ib) < detail::hyp2f1_EPS)) /* negative int c - b */
+            neg_int_ca_or_cb = 1;
+
+        id = std::round(d); /* nearest integer to d */
+        q = std::abs(d - id);
+
+        /* Thanks to Christian Burger 
+         * for reporting a bug here.  */
+        if (std::abs(ax - 1.0) < detail::hyp2f1_EPS) { /* |x| == 1.0   */
+            if (x > 0.0) {
+                if (neg_int_ca_or_cb) {
+                    if (d >= 0.0)
+                        goto hypf;
+                    else
+                        goto hypdiv;
+                }
+                if (d <= 0.0)
+                    goto hypdiv;
+                y = Gamma(c) * Gamma(d) * (rgamma(p) * rgamma(r));
+                goto hypdon;
+            }
+            if (d <= -1.0)
+                goto hypdiv;
+        }
+
+        /* Conditionally make d > 0 by recurrence on c
+         * AMS55 #15.2.27
+         */
+        if (d < 0.0) {
+            /* Try the power series first */
+            y = detail::hyt2f1(a, b, c, x, &err);
+            if (err < detail::hyp2f1_ETHRESH)
+                goto hypdon;
+            /* Apply the recurrence if power series fails */
+            err = 0.0;
+            aid = 2 - id;
+            e = c + aid;
+            d2 = hyp2f1(a, b, e, x);
+            d1 = hyp2f1(a, b, e + 1.0, x);
+            q = a + b + 1.0;
+            for (i = 0; i < aid; i++) {
+                r = e - 1.0;
+                y = (e * (r - (2.0 * e - q) * x) * d2 + (e - a) * (e - b) * x * d1) / (e * r * s);
+                e = r;
+                d1 = d2;
+                d2 = y;
+            }
+            goto hypdon;
+        }
+
+        if (neg_int_ca_or_cb) {
+            goto hypf; /* negative integer c-a or c-b */
+        }
+
+    hypok:
+        y = detail::hyt2f1(a, b, c, x, &err);
+
+    hypdon:
+        if (err > detail::hyp2f1_ETHRESH) {
+            set_error("hyp2f1", SF_ERROR_LOSS, NULL);
+            /*      printf( "Estimated err = %.2e\n", err ); */
+        }
+        return (y);
+
+        /* The transformation for c-a or c-b negative integer
+         * AMS55 #15.3.3
+         */
+    hypf:
+        y = std::pow(s, d) * detail::hys2f1(c - a, c - b, c, x, &err);
+        goto hypdon;
+
+        /* The alarm exit */
+    hypdiv:
+        set_error("hyp2f1", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::infinity();
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h
new file mode 100644
index 0000000000000000000000000000000000000000..18ebcff69ba4f9d9a7d5660aa8c63f858c56c7b3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h
@@ -0,0 +1,361 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     hyperg.c
+ *
+ *     Confluent hypergeometric function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, x, y, hyperg();
+ *
+ * y = hyperg( a, b, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Computes the confluent hypergeometric function
+ *
+ *                          1           2
+ *                       a x    a(a+1) x
+ *   F ( a,b;x )  =  1 + ---- + --------- + ...
+ *  1 1                  b 1!   b(b+1) 2!
+ *
+ * Many higher transcendental functions are special cases of
+ * this power series.
+ *
+ * As is evident from the formula, b must not be a negative
+ * integer or zero unless a is an integer with 0 >= a > b.
+ *
+ * The routine attempts both a direct summation of the series
+ * and an asymptotic expansion.  In each case error due to
+ * roundoff, cancellation, and nonconvergence is estimated.
+ * The result with smaller estimated error is returned.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random points (a, b, x), all three variables
+ * ranging from 0 to 30.
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       1.8e-14     1.1e-15
+ *
+ * Larger errors can be observed when b is near a negative
+ * integer or zero.  Certain combinations of arguments yield
+ * serious cancellation error in the power series summation
+ * and also are not in the region of near convergence of the
+ * asymptotic series.  An error message is printed if the
+ * self-estimated relative error is greater than 1.0e-12.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* the `type` parameter determines what converging factor to use */
+        XSF_HOST_DEVICE inline double hyp2f0(double a, double b, double x, int type, double *err) {
+            double a0, alast, t, tlast, maxt;
+            double n, an, bn, u, sum, temp;
+
+            an = a;
+            bn = b;
+            a0 = 1.0e0;
+            alast = 1.0e0;
+            sum = 0.0;
+            n = 1.0e0;
+            t = 1.0e0;
+            tlast = 1.0e9;
+            maxt = 0.0;
+
+            do {
+                if (an == 0)
+                    goto pdone;
+                if (bn == 0)
+                    goto pdone;
+
+                u = an * (bn * x / n);
+
+                /* check for blowup */
+                temp = std::abs(u);
+                if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp)))
+                    goto error;
+
+                a0 *= u;
+                t = std::abs(a0);
+
+                /* terminating condition for asymptotic series:
+                 * the series is divergent (if a or b is not a negative integer),
+                 * but its leading part can be used as an asymptotic expansion
+                 */
+                if (t > tlast)
+                    goto ndone;
+
+                tlast = t;
+                sum += alast; /* the sum is one term behind */
+                alast = a0;
+
+                if (n > 200)
+                    goto ndone;
+
+                an += 1.0e0;
+                bn += 1.0e0;
+                n += 1.0e0;
+                if (t > maxt)
+                    maxt = t;
+            } while (t > MACHEP);
+
+        pdone: /* series converged! */
+
+            /* estimate error due to roundoff and cancellation */
+            *err = std::abs(MACHEP * (n + maxt));
+
+            alast = a0;
+            goto done;
+
+        ndone: /* series did not converge */
+
+            /* The following "Converging factors" are supposed to improve accuracy,
+             * but do not actually seem to accomplish very much. */
+
+            n -= 1.0;
+            x = 1.0 / x;
+
+            switch (type) { /* "type" given as subroutine argument */
+            case 1:
+                alast *= (0.5 + (0.125 + 0.25 * b - 0.5 * a + 0.25 * x - 0.25 * n) / x);
+                break;
+
+            case 2:
+                alast *= 2.0 / 3.0 - b + 2.0 * a + x - n;
+                break;
+
+            default:;
+            }
+
+            /* estimate error due to roundoff, cancellation, and nonconvergence */
+            *err = MACHEP * (n + maxt) + std::abs(a0);
+
+        done:
+            sum += alast;
+            return (sum);
+
+            /* series blew up: */
+        error:
+            *err = std::numeric_limits::infinity();
+            set_error("hyperg", SF_ERROR_NO_RESULT, NULL);
+            return (sum);
+        }
+
+        /* asymptotic formula for hypergeometric function:
+         *
+         *        (    -a
+         *  --    ( |z|
+         * |  (b) ( -------- 2f0( a, 1+a-b, -1/x )
+         *        (  --
+         *        ( |  (b-a)
+         *
+         *
+         *                                x    a-b                     )
+         *                               e  |x|                        )
+         *                             + -------- 2f0( b-a, 1-a, 1/x ) )
+         *                                --                           )
+         *                               |  (a)                        )
+         */
+
+        XSF_HOST_DEVICE inline double hy1f1a(double a, double b, double x, double *err) {
+            double h1, h2, t, u, temp, acanc, asum, err1, err2;
+
+            if (x == 0) {
+                acanc = 1.0;
+                asum = std::numeric_limits::infinity();
+                goto adone;
+            }
+            temp = std::log(std::abs(x));
+            t = x + temp * (a - b);
+            u = -temp * a;
+
+            if (b > 0) {
+                temp = xsf::cephes::lgam(b);
+                t += temp;
+                u += temp;
+            }
+
+            h1 = hyp2f0(a, a - b + 1, -1.0 / x, 1, &err1);
+
+            temp = std::exp(u) * xsf::cephes::rgamma(b - a);
+            h1 *= temp;
+            err1 *= temp;
+
+            h2 = hyp2f0(b - a, 1.0 - a, 1.0 / x, 2, &err2);
+
+            if (a < 0)
+                temp = std::exp(t) * xsf::cephes::rgamma(a);
+            else
+                temp = std::exp(t - xsf::cephes::lgam(a));
+
+            h2 *= temp;
+            err2 *= temp;
+
+            if (x < 0.0)
+                asum = h1;
+            else
+                asum = h2;
+
+            acanc = std::abs(err1) + std::abs(err2);
+
+            if (b < 0) {
+                temp = xsf::cephes::Gamma(b);
+                asum *= temp;
+                acanc *= std::abs(temp);
+            }
+
+            if (asum != 0.0)
+                acanc /= std::abs(asum);
+
+            if (acanc != acanc)
+                /* nan */
+                acanc = 1.0;
+
+            if (std::isinf(asum))
+                /* infinity */
+                acanc = 0;
+
+            acanc *= 30.0; /* fudge factor, since error of asymptotic formula
+                            * often seems this much larger than advertised */
+        adone:
+            *err = acanc;
+            return (asum);
+        }
+
+        /* Power series summation for confluent hypergeometric function */
+        XSF_HOST_DEVICE inline double hy1f1p(double a, double b, double x, double *err) {
+            double n, a0, sum, t, u, temp, maxn;
+            double an, bn, maxt;
+            double y, c, sumc;
+
+            /* set up for power series summation */
+            an = a;
+            bn = b;
+            a0 = 1.0;
+            sum = 1.0;
+            c = 0.0;
+            n = 1.0;
+            t = 1.0;
+            maxt = 0.0;
+            *err = 1.0;
+
+            maxn = 200.0 + 2 * fabs(a) + 2 * fabs(b);
+
+            while (t > MACHEP) {
+                if (bn == 0) { /* check bn first since if both   */
+                    sf_error("hyperg", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::infinity()); /* an and bn are zero it is     */
+                }
+                if (an == 0) /* a singularity            */
+                    return (sum);
+                if (n > maxn) {
+                    /* too many terms; take the last one as error estimate */
+                    c = std::abs(c) + std::abs(t) * 50.0;
+                    goto pdone;
+                }
+                u = x * (an / (bn * n));
+
+                /* check for blowup */
+                temp = std::abs(u);
+                if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp))) {
+                    *err = 1.0; /* blowup: estimate 100% error */
+                    return sum;
+                }
+
+                a0 *= u;
+
+                y = a0 - c;
+                sumc = sum + y;
+                c = (sumc - sum) - y;
+                sum = sumc;
+
+                t = std::abs(a0);
+
+                an += 1.0;
+                bn += 1.0;
+                n += 1.0;
+            }
+
+        pdone:
+
+            /* estimate error due to roundoff and cancellation */
+            if (sum != 0.0) {
+                *err = std::abs(c / sum);
+            } else {
+                *err = std::abs(c);
+            }
+
+            if (*err != *err) {
+                /* nan */
+                *err = 1.0;
+            }
+
+            return (sum);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double hyperg(double a, double b, double x) {
+        double asum, psum, acanc, pcanc, temp;
+
+        /* See if a Kummer transformation will help */
+        temp = b - a;
+        if (std::abs(temp) < 0.001 * std::abs(a))
+            return (exp(x) * hyperg(temp, b, -x));
+
+        /* Try power & asymptotic series, starting from the one that is likely OK */
+        if (std::abs(x) < 10 + std::abs(a) + std::abs(b)) {
+            psum = detail::hy1f1p(a, b, x, &pcanc);
+            if (pcanc < 1.0e-15)
+                goto done;
+            asum = detail::hy1f1a(a, b, x, &acanc);
+        } else {
+            psum = detail::hy1f1a(a, b, x, &pcanc);
+            if (pcanc < 1.0e-15)
+                goto done;
+            asum = detail::hy1f1p(a, b, x, &acanc);
+        }
+
+        /* Pick the result with less estimated error */
+
+        if (acanc < pcanc) {
+            pcanc = acanc;
+            psum = asum;
+        }
+
+    done:
+        if (pcanc > 1.0e-12)
+            set_error("hyperg", SF_ERROR_LOSS, NULL);
+
+        return (psum);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h
new file mode 100644
index 0000000000000000000000000000000000000000..f61e7b12fd22d92e741f53e2acee8a7f65278658
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h
@@ -0,0 +1,149 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     i0.c
+ *
+ *     Modified Bessel function of order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i0();
+ *
+ * y = i0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order zero of the
+ * argument.
+ *
+ * The function is defined as i0(x) = j0( ix ).
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       5.8e-16     1.4e-16
+ *
+ */
+/*							i0e.c
+ *
+ *	Modified Bessel function of order zero,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i0e();
+ *
+ * y = i0e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of order zero of the argument.
+ *
+ * The function is defined as i0e(x) = exp(-|x|) j0( ix ).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       5.4e-16     1.2e-16
+ * See i0().
+ *
+ */
+
+/*                                                     i0.c            */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "chbevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for exp(-x) I0(x)
+         * in the interval [0,8].
+         *
+         * lim(x->0){ exp(-x) I0(x) } = 1.
+         */
+        constexpr double i0_A[] = {
+            -4.41534164647933937950E-18, 3.33079451882223809783E-17,  -2.43127984654795469359E-16,
+            1.71539128555513303061E-15,  -1.16853328779934516808E-14, 7.67618549860493561688E-14,
+            -4.85644678311192946090E-13, 2.95505266312963983461E-12,  -1.72682629144155570723E-11,
+            9.67580903537323691224E-11,  -5.18979560163526290666E-10, 2.65982372468238665035E-9,
+            -1.30002500998624804212E-8,  6.04699502254191894932E-8,   -2.67079385394061173391E-7,
+            1.11738753912010371815E-6,   -4.41673835845875056359E-6,  1.64484480707288970893E-5,
+            -5.75419501008210370398E-5,  1.88502885095841655729E-4,   -5.76375574538582365885E-4,
+            1.63947561694133579842E-3,   -4.32430999505057594430E-3,  1.05464603945949983183E-2,
+            -2.37374148058994688156E-2,  4.93052842396707084878E-2,   -9.49010970480476444210E-2,
+            1.71620901522208775349E-1,   -3.04682672343198398683E-1,  6.76795274409476084995E-1};
+
+        /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x)
+         * in the inverted interval [8,infinity].
+         *
+         * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi).
+         */
+        constexpr double i0_B[] = {
+            -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17,
+            3.46122286769746109310E-17,  -2.82762398051658348494E-16, -3.42548561967721913462E-16,
+            1.77256013305652638360E-15,  3.81168066935262242075E-15,  -9.55484669882830764870E-15,
+            -4.15056934728722208663E-14, 1.54008621752140982691E-14,  3.85277838274214270114E-13,
+            7.18012445138366623367E-13,  -1.79417853150680611778E-12, -1.32158118404477131188E-11,
+            -3.14991652796324136454E-11, 1.18891471078464383424E-11,  4.94060238822496958910E-10,
+            3.39623202570838634515E-9,   2.26666899049817806459E-8,   2.04891858946906374183E-7,
+            2.89137052083475648297E-6,   6.88975834691682398426E-5,   3.36911647825569408990E-3,
+            8.04490411014108831608E-1};
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double i0(double x) {
+        double y;
+
+        if (x < 0)
+            x = -x;
+        if (x <= 8.0) {
+            y = (x / 2.0) - 2.0;
+            return (std::exp(x) * chbevl(y, detail::i0_A, 30));
+        }
+
+        return (std::exp(x) * chbevl(32.0 / x - 2.0, detail::i0_B, 25) / sqrt(x));
+    }
+
+    XSF_HOST_DEVICE inline double i0e(double x) {
+        double y;
+
+        if (x < 0)
+            x = -x;
+        if (x <= 8.0) {
+            y = (x / 2.0) - 2.0;
+            return (chbevl(y, detail::i0_A, 30));
+        }
+
+        return (chbevl(32.0 / x - 2.0, detail::i0_B, 25) / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h
new file mode 100644
index 0000000000000000000000000000000000000000..49e2690391cf5af19ca36c72cbd38034920c1fd2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h
@@ -0,0 +1,158 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     i1.c
+ *
+ *     Modified Bessel function of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i1();
+ *
+ * y = i1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order one of the
+ * argument.
+ *
+ * The function is defined as i1(x) = -i j1( ix ).
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.9e-15     2.1e-16
+ *
+ *
+ */
+/*							i1e.c
+ *
+ *	Modified Bessel function of order one,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i1e();
+ *
+ * y = i1e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of order one of the argument.
+ *
+ * The function is defined as i1(x) = -i exp(-|x|) j1( ix ).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       2.0e-15     2.0e-16
+ * See i1().
+ *
+ */
+
+/*                                                     i1.c 2          */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1985, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "chbevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for exp(-x) I1(x) / x
+         * in the interval [0,8].
+         *
+         * lim(x->0){ exp(-x) I1(x) / x } = 1/2.
+         */
+
+        constexpr double i1_A[] = {
+            2.77791411276104639959E-18,  -2.11142121435816608115E-17, 1.55363195773620046921E-16,
+            -1.10559694773538630805E-15, 7.60068429473540693410E-15,  -5.04218550472791168711E-14,
+            3.22379336594557470981E-13,  -1.98397439776494371520E-12, 1.17361862988909016308E-11,
+            -6.66348972350202774223E-11, 3.62559028155211703701E-10,  -1.88724975172282928790E-9,
+            9.38153738649577178388E-9,   -4.44505912879632808065E-8,  2.00329475355213526229E-7,
+            -8.56872026469545474066E-7,  3.47025130813767847674E-6,   -1.32731636560394358279E-5,
+            4.78156510755005422638E-5,   -1.61760815825896745588E-4,  5.12285956168575772895E-4,
+            -1.51357245063125314899E-3,  4.15642294431288815669E-3,   -1.05640848946261981558E-2,
+            2.47264490306265168283E-2,   -5.29459812080949914269E-2,  1.02643658689847095384E-1,
+            -1.76416518357834055153E-1,  2.52587186443633654823E-1};
+
+        /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x)
+         * in the inverted interval [8,infinity].
+         *
+         * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi).
+         */
+        constexpr double i1_B[] = {
+            7.51729631084210481353E-18,  4.41434832307170791151E-18,  -4.65030536848935832153E-17,
+            -3.20952592199342395980E-17, 2.96262899764595013876E-16,  3.30820231092092828324E-16,
+            -1.88035477551078244854E-15, -3.81440307243700780478E-15, 1.04202769841288027642E-14,
+            4.27244001671195135429E-14,  -2.10154184277266431302E-14, -4.08355111109219731823E-13,
+            -7.19855177624590851209E-13, 2.03562854414708950722E-12,  1.41258074366137813316E-11,
+            3.25260358301548823856E-11,  -1.89749581235054123450E-11, -5.58974346219658380687E-10,
+            -3.83538038596423702205E-9,  -2.63146884688951950684E-8,  -2.51223623787020892529E-7,
+            -3.88256480887769039346E-6,  -1.10588938762623716291E-4,  -9.76109749136146840777E-3,
+            7.78576235018280120474E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double i1(double x) {
+        double y, z;
+
+        z = std::abs(x);
+        if (z <= 8.0) {
+            y = (z / 2.0) - 2.0;
+            z = chbevl(y, detail::i1_A, 29) * z * std::exp(z);
+        } else {
+            z = std::exp(z) * chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z);
+        }
+        if (x < 0.0)
+            z = -z;
+        return (z);
+    }
+
+    /*                                                     i1e()   */
+
+    XSF_HOST_DEVICE inline double i1e(double x) {
+        double y, z;
+
+        z = std::abs(x);
+        if (z <= 8.0) {
+            y = (z / 2.0) - 2.0;
+            z = chbevl(y, detail::i1_A, 29) * z;
+        } else {
+            z = chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z);
+        }
+        if (x < 0.0)
+            z = -z;
+        return (z);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h
new file mode 100644
index 0000000000000000000000000000000000000000..dbe4f6519b13111d520306c5eec75bf811b02d0d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h
@@ -0,0 +1,421 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     igam.c
+ *
+ *     Incomplete Gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igam();
+ *
+ * y = igam( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *                           x
+ *                            -
+ *                   1       | |  -t  a-1
+ *  igam(a,x)  =   -----     |   e   t   dt.
+ *                  -      | |
+ *                 | (a)    -
+ *                           0
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30       200000       3.6e-14     2.9e-15
+ *    IEEE      0,100      300000       9.9e-14     1.5e-14
+ */
+/*							igamc()
+ *
+ *	Complemented incomplete Gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igamc();
+ *
+ * y = igamc( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *
+ *  igamc(a,x)   =   1 - igam(a,x)
+ *
+ *                            inf.
+ *                              -
+ *                     1       | |  -t  a-1
+ *               =   -----     |   e   t   dt.
+ *                    -      | |
+ *                   | (a)    -
+ *                             x
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ * Tested at random a, x.
+ *                a         x                      Relative error:
+ * arithmetic   domain   domain     # trials      peak         rms
+ *    IEEE     0.5,100   0,100      200000       1.9e-14     1.7e-15
+ *    IEEE     0.01,0.5  0,100      200000       1.4e-13     1.6e-15
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+
+/* Sources
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ * [2] Maddock et. al., "Incomplete Gamma Functions",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/sf_gamma/igamma.html
+ */
+
+/* Scipy changes:
+ * - 05-01-2016: added asymptotic expansion for igam to improve the
+ *   a ~ x regime.
+ * - 06-19-2016: additional series expansion added for igamc to
+ *   improve accuracy at small arguments.
+ * - 06-24-2016: better choice of domain for the asymptotic series;
+ *   improvements in accuracy for the asymptotic series when a and x
+ *   are very close.
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "igam_asymp_coeff.h"
+#include "lanczos.h"
+#include "ndtr.h"
+#include "unity.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int igam_MAXITER = 2000;
+        constexpr int IGAM = 1;
+        constexpr int IGAMC = 0;
+        constexpr double igam_SMALL = 20;
+        constexpr double igam_LARGE = 200;
+        constexpr double igam_SMALLRATIO = 0.3;
+        constexpr double igam_LARGERATIO = 4.5;
+
+        constexpr double igam_big = 4.503599627370496e15;
+        constexpr double igam_biginv = 2.22044604925031308085e-16;
+
+        /* Compute
+         *
+         * x^a * exp(-x) / gamma(a)
+         *
+         * corrected from (15) and (16) in [2] by replacing exp(x - a) with
+         * exp(a - x).
+         */
+        XSF_HOST_DEVICE inline double igam_fac(double a, double x) {
+            double ax, fac, res, num;
+
+            if (std::abs(a - x) > 0.4 * std::abs(a)) {
+                ax = a * std::log(x) - x - xsf::cephes::lgam(a);
+                if (ax < -MAXLOG) {
+                    set_error("igam", SF_ERROR_UNDERFLOW, NULL);
+                    return 0.0;
+                }
+                return std::exp(ax);
+            }
+
+            fac = a + xsf::cephes::lanczos_g - 0.5;
+            res = std::sqrt(fac / std::exp(1)) / xsf::cephes::lanczos_sum_expg_scaled(a);
+
+            if ((a < 200) && (x < 200)) {
+                res *= std::exp(a - x) * std::pow(x / fac, a);
+            } else {
+                num = x - a - xsf::cephes::lanczos_g + 0.5;
+                res *= std::exp(a * xsf::cephes::log1pmx(num / fac) + x * (0.5 - xsf::cephes::lanczos_g) / fac);
+            }
+
+            return res;
+        }
+
+        /* Compute igamc using DLMF 8.9.2. */
+        XSF_HOST_DEVICE inline double igamc_continued_fraction(double a, double x) {
+            int i;
+            double ans, ax, c, yc, r, t, y, z;
+            double pk, pkm1, pkm2, qk, qkm1, qkm2;
+
+            ax = igam_fac(a, x);
+            if (ax == 0.0) {
+                return 0.0;
+            }
+
+            /* continued fraction */
+            y = 1.0 - a;
+            z = x + y + 1.0;
+            c = 0.0;
+            pkm2 = 1.0;
+            qkm2 = x;
+            pkm1 = x + 1.0;
+            qkm1 = z * x;
+            ans = pkm1 / qkm1;
+
+            for (i = 0; i < igam_MAXITER; i++) {
+                c += 1.0;
+                y += 1.0;
+                z += 2.0;
+                yc = y * c;
+                pk = pkm1 * z - pkm2 * yc;
+                qk = qkm1 * z - qkm2 * yc;
+                if (qk != 0) {
+                    r = pk / qk;
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else
+                    t = 1.0;
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+                if (std::abs(pk) > igam_big) {
+                    pkm2 *= igam_biginv;
+                    pkm1 *= igam_biginv;
+                    qkm2 *= igam_biginv;
+                    qkm1 *= igam_biginv;
+                }
+                if (t <= MACHEP) {
+                    break;
+                }
+            }
+
+            return (ans * ax);
+        }
+
+        /* Compute igam using DLMF 8.11.4. */
+        XSF_HOST_DEVICE inline double igam_series(double a, double x) {
+            int i;
+            double ans, ax, c, r;
+
+            ax = igam_fac(a, x);
+            if (ax == 0.0) {
+                return 0.0;
+            }
+
+            /* power series */
+            r = a;
+            c = 1.0;
+            ans = 1.0;
+
+            for (i = 0; i < igam_MAXITER; i++) {
+                r += 1.0;
+                c *= x / r;
+                ans += c;
+                if (c <= MACHEP * ans) {
+                    break;
+                }
+            }
+
+            return (ans * ax / a);
+        }
+
+        /* Compute igamc using DLMF 8.7.3. This is related to the series in
+         * igam_series but extra care is taken to avoid cancellation.
+         */
+        XSF_HOST_DEVICE inline double igamc_series(double a, double x) {
+            int n;
+            double fac = 1;
+            double sum = 0;
+            double term, logx;
+
+            for (n = 1; n < igam_MAXITER; n++) {
+                fac *= -x / n;
+                term = fac / (a + n);
+                sum += term;
+                if (std::abs(term) <= MACHEP * std::abs(sum)) {
+                    break;
+                }
+            }
+
+            logx = std::log(x);
+            term = -xsf::cephes::expm1(a * logx - xsf::cephes::lgam1p(a));
+            return term - std::exp(a * logx - xsf::cephes::lgam(a)) * sum;
+        }
+
+        /* Compute igam/igamc using DLMF 8.12.3/8.12.4. */
+        XSF_HOST_DEVICE inline double asymptotic_series(double a, double x, int func) {
+            int k, n, sgn;
+            int maxpow = 0;
+            double lambda = x / a;
+            double sigma = (x - a) / a;
+            double eta, res, ck, ckterm, term, absterm;
+            double absoldterm = std::numeric_limits::infinity();
+            double etapow[detail::igam_asymp_coeff_N] = {1};
+            double sum = 0;
+            double afac = 1;
+
+            if (func == detail::IGAM) {
+                sgn = -1;
+            } else {
+                sgn = 1;
+            }
+
+            if (lambda > 1) {
+                eta = std::sqrt(-2 * xsf::cephes::log1pmx(sigma));
+            } else if (lambda < 1) {
+                eta = -std::sqrt(-2 * xsf::cephes::log1pmx(sigma));
+            } else {
+                eta = 0;
+            }
+            res = 0.5 * xsf::cephes::erfc(sgn * eta * std::sqrt(a / 2));
+
+            for (k = 0; k < igam_asymp_coeff_K; k++) {
+                ck = igam_asymp_coeff_d[k][0];
+                for (n = 1; n < igam_asymp_coeff_N; n++) {
+                    if (n > maxpow) {
+                        etapow[n] = eta * etapow[n - 1];
+                        maxpow += 1;
+                    }
+                    ckterm = igam_asymp_coeff_d[k][n] * etapow[n];
+                    ck += ckterm;
+                    if (std::abs(ckterm) < MACHEP * std::abs(ck)) {
+                        break;
+                    }
+                }
+                term = ck * afac;
+                absterm = std::abs(term);
+                if (absterm > absoldterm) {
+                    break;
+                }
+                sum += term;
+                if (absterm < MACHEP * std::abs(sum)) {
+                    break;
+                }
+                absoldterm = absterm;
+                afac /= a;
+            }
+            res += sgn * std::exp(-0.5 * a * eta * eta) * sum / std::sqrt(2 * M_PI * a);
+
+            return res;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double igamc(double a, double x);
+
+    XSF_HOST_DEVICE inline double igam(double a, double x) {
+        double absxma_a;
+
+        if (x < 0 || a < 0) {
+            set_error("gammainc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        } else if (a == 0) {
+            if (x > 0) {
+                return 1;
+            } else {
+                return std::numeric_limits::quiet_NaN();
+            }
+        } else if (x == 0) {
+            /* Zero integration limit */
+            return 0;
+        } else if (std::isinf(a)) {
+            if (std::isinf(x)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+            return 0;
+        } else if (std::isinf(x)) {
+            return 1;
+        }
+
+        /* Asymptotic regime where a ~ x; see [2]. */
+        absxma_a = std::abs(x - a) / a;
+        if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) {
+            return detail::asymptotic_series(a, x, detail::IGAM);
+        } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) {
+            return detail::asymptotic_series(a, x, detail::IGAM);
+        }
+
+        if ((x > 1.0) && (x > a)) {
+            return (1.0 - igamc(a, x));
+        }
+
+        return detail::igam_series(a, x);
+    }
+
+    XSF_HOST_DEVICE double igamc(double a, double x) {
+        double absxma_a;
+
+        if (x < 0 || a < 0) {
+            set_error("gammaincc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        } else if (a == 0) {
+            if (x > 0) {
+                return 0;
+            } else {
+                return std::numeric_limits::quiet_NaN();
+            }
+        } else if (x == 0) {
+            return 1;
+        } else if (std::isinf(a)) {
+            if (std::isinf(x)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+            return 1;
+        } else if (std::isinf(x)) {
+            return 0;
+        }
+
+        /* Asymptotic regime where a ~ x; see [2]. */
+        absxma_a = std::abs(x - a) / a;
+        if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) {
+            return detail::asymptotic_series(a, x, detail::IGAMC);
+        } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) {
+            return detail::asymptotic_series(a, x, detail::IGAMC);
+        }
+
+        /* Everywhere else; see [2]. */
+        if (x > 1.1) {
+            if (x < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_continued_fraction(a, x);
+            }
+        } else if (x <= 0.5) {
+            if (-0.4 / std::log(x) < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_series(a, x);
+            }
+        } else {
+            if (x * 1.1 < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_series(a, x);
+            }
+        }
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h
new file mode 100644
index 0000000000000000000000000000000000000000..98404c65ebca79239022c0bae10cfe5e43c361c0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h
@@ -0,0 +1,195 @@
+/* Translated into C++ by SciPy developers in 2024.  */
+
+/* This file was automatically generated by _precomp/gammainc.py.
+ * Do not edit it manually!
+ */
+#pragma once
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int igam_asymp_coeff_K = 25;
+        constexpr int igam_asymp_coeff_N = 25;
+
+        static const double igam_asymp_coeff_d[igam_asymp_coeff_K][igam_asymp_coeff_N] = {
+            {-3.3333333333333333e-1,  8.3333333333333333e-2,   -1.4814814814814815e-2,  1.1574074074074074e-3,
+             3.527336860670194e-4,    -1.7875514403292181e-4,  3.9192631785224378e-5,   -2.1854485106799922e-6,
+             -1.85406221071516e-6,    8.296711340953086e-7,    -1.7665952736826079e-7,  6.7078535434014986e-9,
+             1.0261809784240308e-8,   -4.3820360184533532e-9,  9.1476995822367902e-10,  -2.551419399494625e-11,
+             -5.8307721325504251e-11, 2.4361948020667416e-11,  -5.0276692801141756e-12, 1.1004392031956135e-13,
+             3.3717632624009854e-13,  -1.3923887224181621e-13, 2.8534893807047443e-14,  -5.1391118342425726e-16,
+             -1.9752288294349443e-15},
+            {-1.8518518518518519e-3,  -3.4722222222222222e-3,  2.6455026455026455e-3,   -9.9022633744855967e-4,
+             2.0576131687242798e-4,   -4.0187757201646091e-7,  -1.8098550334489978e-5,  7.6491609160811101e-6,
+             -1.6120900894563446e-6,  4.6471278028074343e-9,   1.378633446915721e-7,    -5.752545603517705e-8,
+             1.1951628599778147e-8,   -1.7543241719747648e-11, -1.0091543710600413e-9,  4.1627929918425826e-10,
+             -8.5639070264929806e-11, 6.0672151016047586e-14,  7.1624989648114854e-12,  -2.9331866437714371e-12,
+             5.9966963656836887e-13,  -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14,
+             -4.13125571381061e-15},
+            {4.1335978835978836e-3,   -2.6813271604938272e-3,  7.7160493827160494e-4,  2.0093878600823045e-6,
+             -1.0736653226365161e-4,  5.2923448829120125e-5,   -1.2760635188618728e-5, 3.4235787340961381e-8,
+             1.3721957309062933e-6,   -6.298992138380055e-7,   1.4280614206064242e-7,  -2.0477098421990866e-10,
+             -1.4092529910867521e-8,  6.228974084922022e-9,    -1.3670488396617113e-9, 9.4283561590146782e-13,
+             1.2872252400089318e-10,  -5.5645956134363321e-11, 1.1975935546366981e-11, -4.1689782251838635e-15,
+             -1.0940640427884594e-12, 4.6622399463901357e-13,  -9.905105763906906e-14, 1.8931876768373515e-17,
+             8.8592218725911273e-15},
+            {6.4943415637860082e-4,   2.2947209362139918e-4,   -4.6918949439525571e-4,  2.6772063206283885e-4,
+             -7.5618016718839764e-5,  -2.3965051138672967e-7,  1.1082654115347302e-5,   -5.6749528269915966e-6,
+             1.4230900732435884e-6,   -2.7861080291528142e-11, -1.6958404091930277e-7,  8.0994649053880824e-8,
+             -1.9111168485973654e-8,  2.3928620439808118e-12,  2.0620131815488798e-9,   -9.4604966618551322e-10,
+             2.1541049775774908e-10,  -1.388823336813903e-14,  -2.1894761681963939e-11, 9.7909989511716851e-12,
+             -2.1782191880180962e-12, 6.2088195734079014e-17,  2.126978363279737e-13,   -9.3446887915174333e-14,
+             2.0453671226782849e-14},
+            {-8.618882909167117e-4,   7.8403922172006663e-4,   -2.9907248030319018e-4, -1.4638452578843418e-6,
+             6.6414982154651222e-5,   -3.9683650471794347e-5,  1.1375726970678419e-5,  2.5074972262375328e-10,
+             -1.6954149536558306e-6,  8.9075075322053097e-7,   -2.2929348340008049e-7, 2.956794137544049e-11,
+             2.8865829742708784e-8,   -1.4189739437803219e-8,  3.4463580499464897e-9,  -2.3024517174528067e-13,
+             -3.9409233028046405e-10, 1.8602338968504502e-10,  -4.356323005056618e-11, 1.2786001016296231e-15,
+             4.6792750266579195e-12,  -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18,
+             -5.0453320690800944e-14},
+            {-3.3679855336635815e-4,  -6.9728137583658578e-5,  2.7727532449593921e-4,  -1.9932570516188848e-4,
+             6.7977804779372078e-5,   1.419062920643967e-7,    -1.3594048189768693e-5, 8.0184702563342015e-6,
+             -2.2914811765080952e-6,  -3.252473551298454e-10,  3.4652846491085265e-7,  -1.8447187191171343e-7,
+             4.8240967037894181e-8,   -1.7989466721743515e-14, -6.3061945000135234e-9, 3.1624176287745679e-9,
+             -7.8409242536974293e-10, 5.1926791652540407e-15,  9.3589442423067836e-11, -4.5134262161632782e-11,
+             1.0799129993116827e-11,  -3.661886712685252e-17,  -1.210902069055155e-12, 5.6807435849905643e-13,
+             -1.3249659916340829e-13},
+            {5.3130793646399222e-4,   -5.9216643735369388e-4,  2.7087820967180448e-4,   7.9023532326603279e-7,
+             -8.1539693675619688e-5,  5.6116827531062497e-5,   -1.8329116582843376e-5,  -3.0796134506033048e-9,
+             3.4651553688036091e-6,   -2.0291327396058604e-6,  5.7887928631490037e-7,   2.338630673826657e-13,
+             -8.8286007463304835e-8,  4.7435958880408128e-8,   -1.2545415020710382e-8,  8.6496488580102925e-14,
+             1.6846058979264063e-9,   -8.5754928235775947e-10, 2.1598224929232125e-10,  -7.6132305204761539e-16,
+             -2.6639822008536144e-11, 1.3065700536611057e-11,  -3.1799163902367977e-12, 4.7109761213674315e-18,
+             3.6902800842763467e-13},
+            {3.4436760689237767e-4,   5.1717909082605922e-5,   -3.3493161081142236e-4,  2.812695154763237e-4,
+             -1.0976582244684731e-4,  -1.2741009095484485e-7,  2.7744451511563644e-5,   -1.8263488805711333e-5,
+             5.7876949497350524e-6,   4.9387589339362704e-10,  -1.0595367014026043e-6,  6.1667143761104075e-7,
+             -1.7562973359060462e-7,  -1.2974473287015439e-12, 2.695423606288966e-8,    -1.4578352908731271e-8,
+             3.887645959386175e-9,    -3.8810022510194121e-17, -5.3279941738772867e-10, 2.7437977643314845e-10,
+             -6.9957960920705679e-11, 2.5899863874868481e-17,  8.8566890996696381e-12,  -4.403168815871311e-12,
+             1.0865561947091654e-12},
+            {-6.5262391859530942e-4, 8.3949872067208728e-4,   -4.3829709854172101e-4, -6.969091458420552e-7,
+             1.6644846642067548e-4,  -1.2783517679769219e-4,  4.6299532636913043e-5,  4.5579098679227077e-9,
+             -1.0595271125805195e-5, 6.7833429048651666e-6,   -2.1075476666258804e-6, -1.7213731432817145e-11,
+             3.7735877416110979e-7,  -2.1867506700122867e-7,  6.2202288040189269e-8,  6.5977038267330006e-16,
+             -9.5903864974256858e-9, 5.2132144922808078e-9,   -1.3991589583935709e-9, 5.382058999060575e-16,
+             1.9484714275467745e-10, -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18,
+             -3.3721464474854592e-12},
+            {-5.9676129019274625e-4, -7.2048954160200106e-5,  6.7823088376673284e-4,   -6.4014752602627585e-4,
+             2.7750107634328704e-4,  1.8197008380465151e-7,   -8.4795071170685032e-5,  6.105192082501531e-5,
+             -2.1073920183404862e-5, -8.8585890141255994e-10, 4.5284535953805377e-6,   -2.8427815022504408e-6,
+             8.7082341778646412e-7,  3.6886101871706965e-12,  -1.5344695190702061e-7,  8.862466778790695e-8,
+             -2.5184812301826817e-8, -1.0225912098215092e-14, 3.8969470758154777e-9,   -2.1267304792235635e-9,
+             5.7370135528051385e-10, -1.887749850169741e-19,  -8.0931538694657866e-11, 4.2382723283449199e-11,
+             -1.1002224534207726e-11},
+            {1.3324454494800656e-3,  -1.9144384985654775e-3, 1.1089369134596637e-3,   9.932404122642299e-7,
+             -5.0874501293093199e-4, 4.2735056665392884e-4,  -1.6858853767910799e-4,  -8.1301893922784998e-9,
+             4.5284402370562147e-5,  -3.127053674781734e-5,  1.044986828530338e-5,    4.8435226265680926e-11,
+             -2.1482565873456258e-6, 1.329369701097492e-6,   -4.0295693092101029e-7,  -1.7567877666323291e-13,
+             7.0145043163668257e-8,  -4.040787734999483e-8,  1.1474026743371963e-8,   3.9642746853563325e-18,
+             -1.7804938269892714e-9, 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18,
+             3.7647749553543836e-11},
+            {1.579727660730835e-3,   1.6251626278391582e-4,   -2.0633421035543276e-3, 2.1389686185689098e-3,
+             -1.0108559391263003e-3, -3.9912705529919201e-7,  3.6235025084764691e-4,  -2.8143901463712154e-4,
+             1.0449513336495887e-4,  2.1211418491830297e-9,   -2.5779417251947842e-5, 1.7281818956040463e-5,
+             -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6,  -6.8693396379526735e-7,
+             2.0653236975414887e-7,  4.6714772409838506e-14,  -3.5609886164949055e-8, 2.0470855345905963e-8,
+             -5.8091738633283358e-9, -1.332821287582869e-16,  9.0354604391335133e-10, -4.9598782517330834e-10,
+             1.3481607129399749e-10},
+            {-4.0725121195140166e-3, 6.4033628338080698e-3,  -4.0410161081676618e-3, -2.183732802866233e-6,
+             2.1740441801254639e-3,  -1.9700440518418892e-3, 8.3595469747962458e-4,  1.9445447567109655e-8,
+             -2.5779387120421696e-4, 1.9009987368139304e-4,  -6.7696499937438965e-5, -1.4440629666426572e-10,
+             1.5712512518742269e-5,  -1.0304008744776893e-5, 3.304517767401387e-6,   7.9829760242325709e-13,
+             -6.4097794149313004e-7, 3.8894624761300056e-7,  -1.1618347644948869e-7, -2.816808630596451e-15,
+             1.9878012911297093e-8,  -1.1407719956357511e-8, 3.2355857064185555e-9,  4.1759468293455945e-20,
+             -5.0423112718105824e-10},
+            {-5.9475779383993003e-3, -5.4016476789260452e-4,  8.7910413550767898e-3,  -9.8576315587856125e-3,
+             5.0134695031021538e-3,  1.2807521786221875e-6,   -2.0626019342754683e-3, 1.7109128573523058e-3,
+             -6.7695312714133799e-4, -6.9011545676562133e-9,  1.8855128143995902e-4,  -1.3395215663491969e-4,
+             4.6263183033528039e-5,  4.0034230613321351e-11,  -1.0255652921494033e-5, 6.612086372797651e-6,
+             -2.0913022027253008e-6, -2.0951775649603837e-13, 3.9756029041993247e-7,  -2.3956211978815887e-7,
+             7.1182883382145864e-8,  8.925574873053455e-16,   -1.2101547235064676e-8, 6.9350618248334386e-9,
+             -1.9661464453856102e-9},
+            {1.7402027787522711e-2,  -2.9527880945699121e-2, 2.0045875571402799e-2,  7.0289515966903407e-6,
+             -1.2375421071343148e-2, 1.1976293444235254e-2,  -5.4156038466518525e-3, -6.3290893396418616e-8,
+             1.8855118129005065e-3,  -1.473473274825001e-3,  5.5515810097708387e-4,  5.2406834412550662e-10,
+             -1.4357913535784836e-4, 9.9181293224943297e-5,  -3.3460834749478311e-5, -3.5755837291098993e-12,
+             7.1560851960630076e-6,  -4.5516802628155526e-6, 1.4236576649271475e-6,  1.8803149082089664e-14,
+             -2.6623403898929211e-7, 1.5950642189595716e-7,  -4.7187514673841102e-8, -6.5107872958755177e-17,
+             7.9795091026746235e-9},
+            {3.0249124160905891e-2,  2.4817436002649977e-3,  -4.9939134373457022e-2, 5.9915643009307869e-2,
+             -3.2483207601623391e-2, -5.7212968652103441e-6, 1.5085251778569354e-2,  -1.3261324005088445e-2,
+             5.5515262632426148e-3,  3.0263182257030016e-8,  -1.7229548406756723e-3, 1.2893570099929637e-3,
+             -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4,  -7.7378565221244477e-5,
+             2.5625836246985201e-5,  1.0766165333192814e-12, -5.3246809282422621e-6, 3.349634863064464e-6,
+             -1.0381253128684018e-6, -5.608909920621128e-15, 1.9150821930676591e-7,  -1.1418365800203486e-7,
+             3.3654425209171788e-8},
+            {-9.9051020880159045e-2, 1.7954011706123486e-1,  -1.2989606383463778e-1, -3.1478872752284357e-5,
+             9.0510635276848131e-2,  -9.2828824411184397e-2, 4.4412112839877808e-2,  2.7779236316835888e-7,
+             -1.7229543805449697e-2, 1.4182925050891573e-2,  -5.6214161633747336e-3, -2.39598509186381e-9,
+             1.6029634366079908e-3,  -1.1606784674435773e-3, 4.1001337768153873e-4,  1.8365800754090661e-11,
+             -9.5844256563655903e-5, 6.3643062337764708e-5,  -2.076250624489065e-5,  -1.1806020912804483e-13,
+             4.2131808239120649e-6,  -2.6262241337012467e-6, 8.0770620494930662e-7,  6.0125912123632725e-16,
+             -1.4729737374018841e-7},
+            {-1.9994542198219728e-1, -1.5056113040026424e-2,  3.6470239469348489e-1,  -4.6435192311733545e-1,
+             2.6640934719197893e-1,  3.4038266027147191e-5,   -1.3784338709329624e-1, 1.276467178337056e-1,
+             -5.6213828755200985e-2, -1.753150885483011e-7,   1.9235592956768113e-2,  -1.5088821281095315e-2,
+             5.7401854451350123e-3,  1.0622382710310225e-9,   -1.5335082692563998e-3, 1.0819320643228214e-3,
+             -3.7372510193945659e-4, -6.6170909729031985e-12, 8.4263617380909628e-5,  -5.5150706827483479e-5,
+             1.7769536448348069e-5,  3.8827923210205533e-14,  -3.53513697488768e-6,   2.1865832130045269e-6,
+             -6.6812849447625594e-7},
+            {7.2438608504029431e-1,  -1.3918010932653375,    1.0654143352413968,     1.876173868950258e-4,
+             -8.2705501176152696e-1, 8.9352433347828414e-1,  -4.4971003995291339e-1, -1.6107401567546652e-6,
+             1.9235590165271091e-1,  -1.6597702160042609e-1, 6.8882222681814333e-2,  1.3910091724608687e-8,
+             -2.146911561508663e-2,  1.6228980898865892e-2,  -5.9796016172584256e-3, -1.1287469112826745e-10,
+             1.5167451119784857e-3,  -1.0478634293553899e-3, 3.5539072889126421e-4,  8.1704322111801517e-13,
+             -7.7773013442452395e-5, 5.0291413897007722e-5,  -1.6035083867000518e-5, 1.2469354315487605e-14,
+             3.1369106244517615e-6},
+            {1.6668949727276811,     1.165462765994632e-1,   -3.3288393225018906,    4.4692325482864037,
+             -2.6977693045875807,    -2.600667859891061e-4,  1.5389017615694539,     -1.4937962361134612,
+             6.8881964633233148e-1,  1.3077482004552385e-6,  -2.5762963325596288e-1, 2.1097676102125449e-1,
+             -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2,  -1.7813678334552311e-2,
+             6.3970330388900056e-3,  4.9430807090480523e-11, -1.5554602758465635e-3, 1.0561196919903214e-3,
+             -3.5277184460472902e-4, 9.3002334645022459e-14, 7.5285855026557172e-5,  -4.8186515569156351e-5,
+             1.5227271505597605e-5},
+            {-6.6188298861372935,    1.3397985455142589e+1,  -1.0789350606845146e+1, -1.4352254537875018e-3,
+             9.2333694596189809,     -1.0456552819547769e+1, 5.5105526029033471,     1.2024439690716742e-5,
+             -2.5762961164755816,    2.3207442745387179,     -1.0045728797216284,    -1.0207833290021914e-7,
+             3.3975092171169466e-1,  -2.6720517450757468e-1, 1.0235252851562706e-1,  8.4329730484871625e-10,
+             -2.7998284958442595e-2, 2.0066274144976813e-2,  -7.0554368915086242e-3, 1.9402238183698188e-12,
+             1.6562888105449611e-3,  -1.1082898580743683e-3, 3.654545161310169e-4,   -5.1290032026971794e-11,
+             -7.6340103696869031e-5},
+            {-1.7112706061976095e+1, -1.1208044642899116,     3.7131966511885444e+1,  -5.2298271025348962e+1,
+             3.3058589696624618e+1,  2.4791298976200222e-3,   -2.061089403411526e+1,  2.088672775145582e+1,
+             -1.0045703956517752e+1, -1.2238783449063012e-5,  4.0770134274221141,     -3.473667358470195,
+             1.4329352617312006,     7.1359914411879712e-8,   -4.4797257159115612e-1, 3.4112666080644461e-1,
+             -1.2699786326594923e-1, -2.8953677269081528e-10, 3.3125776278259863e-2,  -2.3274087021036101e-2,
+             8.0399993503648882e-3,  -1.177805216235265e-9,   -1.8321624891071668e-3, 1.2108282933588665e-3,
+             -3.9479941246822517e-4},
+            {7.389033153567425e+1,   -1.5680141270402273e+2, 1.322177542759164e+2,   1.3692876877324546e-2,
+             -1.2366496885920151e+2, 1.4620689391062729e+2,  -8.0365587724865346e+1, -1.1259851148881298e-4,
+             4.0770132196179938e+1,  -3.8210340013273034e+1, 1.719522294277362e+1,   9.3519707955168356e-7,
+             -6.2716159907747034,    5.1168999071852637,     -2.0319658112299095,    -4.9507215582761543e-9,
+             5.9626397294332597e-1,  -4.4220765337238094e-1, 1.6079998700166273e-1,  -2.4733786203223402e-8,
+             -4.0307574759979762e-2, 2.7849050747097869e-2,  -9.4751858992054221e-3, 6.419922235909132e-6,
+             2.1250180774699461e-3},
+            {2.1216837098382522e+2,  1.3107863022633868e+1,  -4.9698285932871748e+2, 7.3121595266969204e+2,
+             -4.8213821720890847e+2, -2.8817248692894889e-2, 3.2616720302947102e+2,  -3.4389340280087117e+2,
+             1.7195193870816232e+2,  1.4038077378096158e-4,  -7.52594195897599e+1,   6.651969984520934e+1,
+             -2.8447519748152462e+1, -7.613702615875391e-7,  9.5402237105304373,     -7.5175301113311376,
+             2.8943997568871961,     -4.6612194999538201e-7, -8.0615149598794088e-1, 5.8483006570631029e-1,
+             -2.0845408972964956e-1, 1.4765818959305817e-4,  5.1000433863753019e-2,  -3.3066252141883665e-2,
+             1.5109265210467774e-2},
+            {-9.8959643098322368e+2, 2.1925555360905233e+3,  -1.9283586782723356e+3, -1.5925738122215253e-1,
+             1.9569985945919857e+3,  -2.4072514765081556e+3, 1.3756149959336496e+3,  1.2920735237496668e-3,
+             -7.525941715948055e+2,  7.3171668742208716e+2,  -3.4137023466220065e+2, -9.9857390260608043e-6,
+             1.3356313181291573e+2,  -1.1276295161252794e+2, 4.6310396098204458e+1,  -7.9237387133614756e-6,
+             -1.4510726927018646e+1, 1.1111771248100563e+1,  -4.1690817945270892,    3.1008219800117808e-3,
+             1.1220095449981468,     -7.6052379926149916e-1, 3.6262236505085254e-1,  2.216867741940747e-1,
+             4.8683443692930507e-1}};
+
+    } // namespace detail
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff82c35f682b04a250f6a86721312f860b3fe7cb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h
@@ -0,0 +1,313 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*
+ * (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. (See accompanying file
+ *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "igam.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        XSF_HOST_DEVICE double find_inverse_s(double p, double q) {
+            /*
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             *
+             * See equation 32.
+             */
+            double s, t;
+            constexpr double a[4] = {0.213623493715853, 4.28342155967104, 11.6616720288968, 3.31125922108741};
+            constexpr double b[5] = {0.3611708101884203e-1, 1.27364489782223, 6.40691597760039, 6.61053765625462, 1};
+
+            if (p < 0.5) {
+                t = std::sqrt(-2 * std::log(p));
+            } else {
+                t = std::sqrt(-2 * std::log(q));
+            }
+            s = t - polevl(t, a, 3) / polevl(t, b, 4);
+            if (p < 0.5)
+                s = -s;
+            return s;
+        }
+
+        XSF_HOST_DEVICE inline double didonato_SN(double a, double x, unsigned N, double tolerance) {
+            /*
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             *
+             * See equation 34.
+             */
+            double sum = 1.0;
+
+            if (N >= 1) {
+                unsigned i;
+                double partial = x / (a + 1);
+
+                sum += partial;
+                for (i = 2; i <= N; ++i) {
+                    partial *= x / (a + i);
+                    sum += partial;
+                    if (partial < tolerance) {
+                        break;
+                    }
+                }
+            }
+            return sum;
+        }
+
+        XSF_HOST_DEVICE inline double find_inverse_gamma(double a, double p, double q) {
+            /*
+             * In order to understand what's going on here, you will
+             * need to refer to:
+             *
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             */
+            double result;
+
+            if (a == 1) {
+                if (q > 0.9) {
+                    result = -std::log1p(-p);
+                } else {
+                    result = -std::log(q);
+                }
+            } else if (a < 1) {
+                double g = xsf::cephes::Gamma(a);
+                double b = q * g;
+
+                if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) {
+                    /* DiDonato & Morris Eq 21:
+                     *
+                     * There is a slight variation from DiDonato and Morris here:
+                     * the first form given here is unstable when p is close to 1,
+                     * making it impossible to compute the inverse of Q(a,x) for small
+                     * q. Fortunately the second form works perfectly well in this case.
+                     */
+                    double u;
+                    if ((b * q > 1e-8) && (q > 1e-5)) {
+                        u = std::pow(p * g * a, 1 / a);
+                    } else {
+                        u = std::exp((-q / a) - SCIPY_EULER);
+                    }
+                    result = u / (1 - (u / (a + 1)));
+                } else if ((a < 0.3) && (b >= 0.35)) {
+                    /* DiDonato & Morris Eq 22: */
+                    double t = std::exp(-SCIPY_EULER - b);
+                    double u = t * std::exp(t);
+                    result = t * std::exp(u);
+                } else if ((b > 0.15) || (a >= 0.3)) {
+                    /* DiDonato & Morris Eq 23: */
+                    double y = -std::log(b);
+                    double u = y - (1 - a) * std::log(y);
+                    result = y - (1 - a) * std::log(u) - std::log(1 + (1 - a) / (1 + u));
+                } else if (b > 0.1) {
+                    /* DiDonato & Morris Eq 24: */
+                    double y = -std::log(b);
+                    double u = y - (1 - a) * std::log(y);
+                    result = y - (1 - a) * std::log(u) -
+                             std::log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) / (u * u + (5 - a) * u + 2));
+                } else {
+                    /* DiDonato & Morris Eq 25: */
+                    double y = -std::log(b);
+                    double c1 = (a - 1) * std::log(y);
+                    double c1_2 = c1 * c1;
+                    double c1_3 = c1_2 * c1;
+                    double c1_4 = c1_2 * c1_2;
+                    double a_2 = a * a;
+                    double a_3 = a_2 * a;
+
+                    double c2 = (a - 1) * (1 + c1);
+                    double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);
+                    double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 +
+                                           (11 * a_2 - 46 * a + 47) / 6);
+                    double c5 = (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 +
+                                           (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 +
+                                           (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);
+
+                    double y_2 = y * y;
+                    double y_3 = y_2 * y;
+                    double y_4 = y_2 * y_2;
+                    result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);
+                }
+            } else {
+                /* DiDonato and Morris Eq 31: */
+                double s = find_inverse_s(p, q);
+
+                double s_2 = s * s;
+                double s_3 = s_2 * s;
+                double s_4 = s_2 * s_2;
+                double s_5 = s_4 * s;
+                double ra = std::sqrt(a);
+
+                double w = a + s * ra + (s_2 - 1) / 3;
+                w += (s_3 - 7 * s) / (36 * ra);
+                w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a);
+                w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra);
+
+                if ((a >= 500) && (std::abs(1 - w / a) < 1e-6)) {
+                    result = w;
+                } else if (p > 0.5) {
+                    if (w < 3 * a) {
+                        result = w;
+                    } else {
+                        double D = std::fmax(2, a * (a - 1));
+                        double lg = xsf::cephes::lgam(a);
+                        double lb = std::log(q) + lg;
+                        if (lb < -D * 2.3) {
+                            /* DiDonato and Morris Eq 25: */
+                            double y = -lb;
+                            double c1 = (a - 1) * std::log(y);
+                            double c1_2 = c1 * c1;
+                            double c1_3 = c1_2 * c1;
+                            double c1_4 = c1_2 * c1_2;
+                            double a_2 = a * a;
+                            double a_3 = a_2 * a;
+
+                            double c2 = (a - 1) * (1 + c1);
+                            double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);
+                            double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 +
+                                                   (11 * a_2 - 46 * a + 47) / 6);
+                            double c5 =
+                                (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 +
+                                           (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 +
+                                           (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);
+
+                            double y_2 = y * y;
+                            double y_3 = y_2 * y;
+                            double y_4 = y_2 * y_2;
+                            result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);
+                        } else {
+                            /* DiDonato and Morris Eq 33: */
+                            double u = -lb + (a - 1) * std::log(w) - std::log(1 + (1 - a) / (1 + w));
+                            result = -lb + (a - 1) * std::log(u) - std::log(1 + (1 - a) / (1 + u));
+                        }
+                    }
+                } else {
+                    double z = w;
+                    double ap1 = a + 1;
+                    double ap2 = a + 2;
+                    if (w < 0.15 * ap1) {
+                        /* DiDonato and Morris Eq 35: */
+                        double v = std::log(p) + xsf::cephes::lgam(ap1);
+                        z = std::exp((v + w) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2));
+                        z = std::exp((v + z - s) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2));
+                        z = std::exp((v + z - s) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3))));
+                        z = std::exp((v + z - s) / a);
+                    }
+
+                    if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) {
+                        result = z;
+                    } else {
+                        /* DiDonato and Morris Eq 36: */
+                        double ls = std::log(didonato_SN(a, z, 100, 1e-4));
+                        double v = std::log(p) + xsf::cephes::lgam(ap1);
+                        z = std::exp((v + z - ls) / a);
+                        result = z * (1 - (a * std::log(z) - z - v + ls) / (a - z));
+                    }
+                }
+            }
+            return result;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double igamci(double a, double q);
+
+    XSF_HOST_DEVICE inline double igami(double a, double p) {
+        int i;
+        double x, fac, f_fp, fpp_fp;
+
+        if (std::isnan(a) || std::isnan(p)) {
+            return std::numeric_limits::quiet_NaN();
+            ;
+        } else if ((a < 0) || (p < 0) || (p > 1)) {
+            set_error("gammaincinv", SF_ERROR_DOMAIN, NULL);
+        } else if (p == 0.0) {
+            return 0.0;
+        } else if (p == 1.0) {
+            return std::numeric_limits::infinity();
+        } else if (p > 0.9) {
+            return igamci(a, 1 - p);
+        }
+
+        x = detail::find_inverse_gamma(a, p, 1 - p);
+        /* Halley's method */
+        for (i = 0; i < 3; i++) {
+            fac = detail::igam_fac(a, x);
+            if (fac == 0.0) {
+                return x;
+            }
+            f_fp = (igam(a, x) - p) * x / fac;
+            /* The ratio of the first and second derivatives simplifies */
+            fpp_fp = -1.0 + (a - 1) / x;
+            if (std::isinf(fpp_fp)) {
+                /* Resort to Newton's method in the case of overflow */
+                x = x - f_fp;
+            } else {
+                x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp);
+            }
+        }
+
+        return x;
+    }
+
+    XSF_HOST_DEVICE inline double igamci(double a, double q) {
+        int i;
+        double x, fac, f_fp, fpp_fp;
+
+        if (std::isnan(a) || std::isnan(q)) {
+            return std::numeric_limits::quiet_NaN();
+        } else if ((a < 0.0) || (q < 0.0) || (q > 1.0)) {
+            set_error("gammainccinv", SF_ERROR_DOMAIN, NULL);
+        } else if (q == 0.0) {
+            return std::numeric_limits::infinity();
+        } else if (q == 1.0) {
+            return 0.0;
+        } else if (q > 0.9) {
+            return igami(a, 1 - q);
+        }
+
+        x = detail::find_inverse_gamma(a, 1 - q, q);
+        for (i = 0; i < 3; i++) {
+            fac = detail::igam_fac(a, x);
+            if (fac == 0.0) {
+                return x;
+            }
+            f_fp = (igamc(a, x) - q) * x / (-fac);
+            fpp_fp = -1.0 + (a - 1) / x;
+            if (std::isinf(fpp_fp)) {
+                x = x - f_fp;
+            } else {
+                x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp);
+            }
+        }
+
+        return x;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h
new file mode 100644
index 0000000000000000000000000000000000000000..29236ef966e05f615920b381489e627950e78740
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h
@@ -0,0 +1,225 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     j0.c
+ *
+ *     Bessel function of order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, j0();
+ *
+ * y = j0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order zero of the argument.
+ *
+ * The domain is divided into the intervals [0, 5] and
+ * (5, infinity). In the first interval the following rational
+ * approximation is used:
+ *
+ *
+ *        2         2
+ * (w - r  ) (w - r  ) P (w) / Q (w)
+ *       1         2    3       8
+ *
+ *            2
+ * where w = x  and the two r's are zeros of the function.
+ *
+ * In the second interval, the Hankel asymptotic expansion
+ * is employed with two rational functions of degree 6/6
+ * and 7/7.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       60000       4.2e-16     1.1e-16
+ *
+ */
+/*							y0.c
+ *
+ *	Bessel function of the second kind, order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, y0();
+ *
+ * y = y0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of the second kind, of order
+ * zero, of the argument.
+ *
+ * The domain is divided into the intervals [0, 5] and
+ * (5, infinity). In the first interval a rational approximation
+ * R(x) is employed to compute
+ *   y0(x)  = R(x)  +   2 * log(x) * j0(x) / M_PI.
+ * Thus a call to j0() is required.
+ *
+ * In the second interval, the Hankel asymptotic expansion
+ * is employed with two rational functions of degree 6/6
+ * and 7/7.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *  Absolute error, when y0(x) < 1; else relative error:
+ *
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.3e-15     1.6e-16
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+
+/* Note: all coefficients satisfy the relative error criterion
+ * except YP, YQ which are designed for absolute error. */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double j0_PP[7] = {
+            7.96936729297347051624E-4, 8.28352392107440799803E-2, 1.23953371646414299388E0,  5.44725003058768775090E0,
+            8.74716500199817011941E0,  5.30324038235394892183E0,  9.99999999999999997821E-1,
+        };
+
+        constexpr double j0_PQ[7] = {
+            9.24408810558863637013E-4, 8.56288474354474431428E-2, 1.25352743901058953537E0, 5.47097740330417105182E0,
+            8.76190883237069594232E0,  5.30605288235394617618E0,  1.00000000000000000218E0,
+        };
+
+        constexpr double j0_QP[8] = {
+            -1.13663838898469149931E-2, -1.28252718670509318512E0, -1.95539544257735972385E1, -9.32060152123768231369E1,
+            -1.77681167980488050595E2,  -1.47077505154951170175E2, -5.14105326766599330220E1, -6.05014350600728481186E0,
+        };
+
+        constexpr double j0_QQ[7] = {
+            /*  1.00000000000000000000E0, */
+            6.43178256118178023184E1, 8.56430025976980587198E2, 3.88240183605401609683E3, 7.24046774195652478189E3,
+            5.93072701187316984827E3, 2.06209331660327847417E3, 2.42005740240291393179E2,
+        };
+
+        constexpr double j0_YP[8] = {
+            1.55924367855235737965E4,   -1.46639295903971606143E7,  5.43526477051876500413E9,
+            -9.82136065717911466409E11, 8.75906394395366999549E13,  -3.46628303384729719441E15,
+            4.42733268572569800351E16,  -1.84950800436986690637E16,
+        };
+
+        constexpr double j0_YQ[7] = {
+            /* 1.00000000000000000000E0, */
+            1.04128353664259848412E3,  6.26107330137134956842E5,  2.68919633393814121987E8,  8.64002487103935000337E10,
+            2.02979612750105546709E13, 3.17157752842975028269E15, 2.50596256172653059228E17,
+        };
+
+        /*  5.783185962946784521175995758455807035071 */
+        constexpr double j0_DR1 = 5.78318596294678452118E0;
+
+        /* 30.47126234366208639907816317502275584842 */
+        constexpr double j0_DR2 = 3.04712623436620863991E1;
+
+        constexpr double j0_RP[4] = {
+            -4.79443220978201773821E9,
+            1.95617491946556577543E12,
+            -2.49248344360967716204E14,
+            9.70862251047306323952E15,
+        };
+
+        constexpr double j0_RQ[8] = {
+            /* 1.00000000000000000000E0, */
+            4.99563147152651017219E2,  1.73785401676374683123E5,  4.84409658339962045305E7,  1.11855537045356834862E10,
+            2.11277520115489217587E12, 3.10518229857422583814E14, 3.18121955943204943306E16, 1.71086294081043136091E18,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double j0(double x) {
+        double w, z, p, q, xn;
+
+        if (x < 0) {
+            x = -x;
+        }
+
+        if (x <= 5.0) {
+            z = x * x;
+            if (x < 1.0e-5) {
+                return (1.0 - z / 4.0);
+            }
+
+            p = (z - detail::j0_DR1) * (z - detail::j0_DR2);
+            p = p * polevl(z, detail::j0_RP, 3) / p1evl(z, detail::j0_RQ, 8);
+            return (p);
+        }
+
+        w = 5.0 / x;
+        q = 25.0 / (x * x);
+        p = polevl(q, detail::j0_PP, 6) / polevl(q, detail::j0_PQ, 6);
+        q = polevl(q, detail::j0_QP, 7) / p1evl(q, detail::j0_QQ, 7);
+        xn = x - M_PI_4;
+        p = p * std::cos(xn) - w * q * std::sin(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+    /*                                                     y0() 2  */
+    /* Bessel function of second kind, order zero  */
+
+    /* Rational approximation coefficients YP[], YQ[] are used here.
+     * The function computed is  y0(x)  -  2 * log(x) * j0(x) / M_PI,
+     * whose value at x = 0 is  2 * ( log(0.5) + EUL ) / M_PI
+     * = 0.073804295108687225.
+     */
+
+    XSF_HOST_DEVICE inline double y0(double x) {
+        double w, z, p, q, xn;
+
+        if (x <= 5.0) {
+            if (x == 0.0) {
+                set_error("y0", SF_ERROR_SINGULAR, NULL);
+                return -std::numeric_limits::infinity();
+            } else if (x < 0.0) {
+                set_error("y0", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            z = x * x;
+            w = polevl(z, detail::j0_YP, 7) / p1evl(z, detail::j0_YQ, 7);
+            w += M_2_PI * std::log(x) * j0(x);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = 25.0 / (x * x);
+        p = polevl(z, detail::j0_PP, 6) / polevl(z, detail::j0_PQ, 6);
+        q = polevl(z, detail::j0_QP, 7) / p1evl(z, detail::j0_QQ, 7);
+        xn = x - M_PI_4;
+        p = p * std::sin(xn) + w * q * std::cos(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h
new file mode 100644
index 0000000000000000000000000000000000000000..46532249550d214723291f7ca9874bb4a31380ac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h
@@ -0,0 +1,198 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     j1.c
+ *
+ *     Bessel function of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, j1();
+ *
+ * y = j1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order one of the argument.
+ *
+ * The domain is divided into the intervals [0, 8] and
+ * (8, infinity). In the first interval a 24 term Chebyshev
+ * expansion is used. In the second, the asymptotic
+ * trigonometric representation is employed using two
+ * rational functions of degree 5/5.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      0, 30       30000       2.6e-16     1.1e-16
+ *
+ *
+ */
+/*							y1.c
+ *
+ *	Bessel function of second kind of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, y1();
+ *
+ * y = y1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of the second kind of order one
+ * of the argument.
+ *
+ * The domain is divided into the intervals [0, 8] and
+ * (8, infinity). In the first interval a 25 term Chebyshev
+ * expansion is used, and a call to j1() is required.
+ * In the second, the asymptotic trigonometric representation
+ * is employed using two rational functions of degree 5/5.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      0, 30       30000       1.0e-15     1.3e-16
+ *
+ * (error criterion relative when |y1| > 1).
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * #define PIO4 .78539816339744830962
+ * #define THPIO4 2.35619449019234492885
+ * #define SQ2OPI .79788456080286535588
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double j1_RP[4] = {
+            -8.99971225705559398224E8,
+            4.52228297998194034323E11,
+            -7.27494245221818276015E13,
+            3.68295732863852883286E15,
+        };
+
+        constexpr double j1_RQ[8] = {
+            /* 1.00000000000000000000E0, */
+            6.20836478118054335476E2,  2.56987256757748830383E5,  8.35146791431949253037E7,  2.21511595479792499675E10,
+            4.74914122079991414898E12, 7.84369607876235854894E14, 8.95222336184627338078E16, 5.32278620332680085395E18,
+        };
+
+        constexpr double j1_PP[7] = {
+            7.62125616208173112003E-4, 7.31397056940917570436E-2, 1.12719608129684925192E0, 5.11207951146807644818E0,
+            8.42404590141772420927E0,  5.21451598682361504063E0,  1.00000000000000000254E0,
+        };
+
+        constexpr double j1_PQ[7] = {
+            5.71323128072548699714E-4, 6.88455908754495404082E-2, 1.10514232634061696926E0,  5.07386386128601488557E0,
+            8.39985554327604159757E0,  5.20982848682361821619E0,  9.99999999999999997461E-1,
+        };
+
+        constexpr double j1_QP[8] = {
+            5.10862594750176621635E-2, 4.98213872951233449420E0, 7.58238284132545283818E1, 3.66779609360150777800E2,
+            7.10856304998926107277E2,  5.97489612400613639965E2, 2.11688757100572135698E2, 2.52070205858023719784E1,
+        };
+
+        constexpr double j1_QQ[7] = {
+            /* 1.00000000000000000000E0, */
+            7.42373277035675149943E1, 1.05644886038262816351E3, 4.98641058337653607651E3, 9.56231892404756170795E3,
+            7.99704160447350683650E3, 2.82619278517639096600E3, 3.36093607810698293419E2,
+        };
+
+        constexpr double j1_YP[6] = {
+            1.26320474790178026440E9,   -6.47355876379160291031E11, 1.14509511541823727583E14,
+            -8.12770255501325109621E15, 2.02439475713594898196E17,  -7.78877196265950026825E17,
+        };
+
+        constexpr double j1_YQ[8] = {
+            /* 1.00000000000000000000E0, */
+            5.94301592346128195359E2,  2.35564092943068577943E5,  7.34811944459721705660E7,  1.87601316108706159478E10,
+            3.88231277496238566008E12, 6.20557727146953693363E14, 6.87141087355300489866E16, 3.97270608116560655612E18,
+        };
+
+        constexpr double j1_Z1 = 1.46819706421238932572E1;
+        constexpr double j1_Z2 = 4.92184563216946036703E1;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double j1(double x) {
+        double w, z, p, q, xn;
+
+        w = x;
+        if (x < 0) {
+            return -j1(-x);
+        }
+
+        if (w <= 5.0) {
+            z = x * x;
+            w = polevl(z, detail::j1_RP, 3) / p1evl(z, detail::j1_RQ, 8);
+            w = w * x * (z - detail::j1_Z1) * (z - detail::j1_Z2);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = w * w;
+        p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
+        q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
+        xn = x - detail::THPIO4;
+        p = p * std::cos(xn) - w * q * std::sin(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+    XSF_HOST_DEVICE inline double y1(double x) {
+        double w, z, p, q, xn;
+
+        if (x <= 5.0) {
+            if (x == 0.0) {
+                set_error("y1", SF_ERROR_SINGULAR, NULL);
+                return -std::numeric_limits::infinity();
+            } else if (x <= 0.0) {
+                set_error("y1", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            z = x * x;
+            w = x * (polevl(z, detail::j1_YP, 5) / p1evl(z, detail::j1_YQ, 8));
+            w += M_2_PI * (j1(x) * std::log(x) - 1.0 / x);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = w * w;
+        p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
+        q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
+        xn = x - detail::THPIO4;
+        p = p * std::sin(xn) + w * q * std::cos(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h
new file mode 100644
index 0000000000000000000000000000000000000000..db5272f27fb4e6619dafaa02f9fc2cd2b2f57f9e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h
@@ -0,0 +1,715 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     jv.c
+ *
+ *     Bessel function of noninteger order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, jv();
+ *
+ * y = jv( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order v of the argument,
+ * where v is real.  Negative x is allowed if v is an integer.
+ *
+ * Several expansions are included: the ascending power
+ * series, the Hankel expansion, and two transitional
+ * expansions for large v.  If v is not too large, it
+ * is reduced by recurrence to a region of best accuracy.
+ * The transitional expansions give 12D accuracy for v > 500.
+ *
+ *
+ *
+ * ACCURACY:
+ * Results for integer v are indicated by *, where x and v
+ * both vary from -125 to +125.  Otherwise,
+ * x ranges from 0 to 125, v ranges as indicated by "domain."
+ * Error criterion is absolute, except relative when |jv()| > 1.
+ *
+ * arithmetic  v domain  x domain    # trials      peak       rms
+ *    IEEE      0,125     0,125      100000      4.6e-15    2.2e-16
+ *    IEEE   -125,0       0,125       40000      5.4e-11    3.7e-13
+ *    IEEE      0,500     0,500       20000      4.4e-15    4.0e-16
+ * Integer v:
+ *    IEEE   -125,125   -125,125      50000      3.5e-15*   1.9e-16*
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "airy.h"
+#include "cbrt.h"
+#include "rgamma.h"
+#include "j0.h"
+#include "j1.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double jv_BIG = 1.44115188075855872E+17;
+
+        /* Reduce the order by backward recurrence.
+         * AMS55 #9.1.27 and 9.1.73.
+         */
+
+        XSF_HOST_DEVICE inline double jv_recur(double *n, double x, double *newn, int cancel) {
+            double pkm2, pkm1, pk, qkm2, qkm1;
+
+            /* double pkp1; */
+            double k, ans, qk, xk, yk, r, t, kf;
+            constexpr double big = jv_BIG;
+            int nflag, ctr;
+            int miniter, maxiter;
+
+            /* Continued fraction for Jn(x)/Jn-1(x)
+             * AMS 9.1.73
+             *
+             *    x       -x^2      -x^2
+             * ------  ---------  ---------   ...
+             * 2 n +   2(n+1) +   2(n+2) +
+             *
+             * Compute it with the simplest possible algorithm.
+             *
+             * This continued fraction starts to converge when (|n| + m) > |x|.
+             * Hence, at least |x|-|n| iterations are necessary before convergence is
+             * achieved. There is a hard limit set below, m <= 30000, which is chosen
+             * so that no branch in `jv` requires more iterations to converge.
+             * The exact maximum number is (500/3.6)^2 - 500 ~ 19000
+             */
+
+            maxiter = 22000;
+            miniter = std::abs(x) - std::abs(*n);
+            if (miniter < 1) {
+                miniter = 1;
+            }
+
+            if (*n < 0.0) {
+                nflag = 1;
+            } else {
+                nflag = 0;
+            }
+
+        fstart:
+            pkm2 = 0.0;
+            qkm2 = 1.0;
+            pkm1 = x;
+            qkm1 = *n + *n;
+            xk = -x * x;
+            yk = qkm1;
+            ans = 0.0; /* ans=0.0 ensures that t=1.0 in the first iteration */
+            ctr = 0;
+            do {
+                yk += 2.0;
+                pk = pkm1 * yk + pkm2 * xk;
+                qk = qkm1 * yk + qkm2 * xk;
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+
+                /* check convergence */
+                if (qk != 0 && ctr > miniter)
+                    r = pk / qk;
+                else
+                    r = 0.0;
+
+                if (r != 0) {
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else {
+                    t = 1.0;
+                }
+
+                if (++ctr > maxiter) {
+                    set_error("jv", SF_ERROR_UNDERFLOW, NULL);
+                    goto done;
+                }
+                if (t < MACHEP) {
+                    goto done;
+                }
+
+                /* renormalize coefficients */
+                if (std::abs(pk) > big) {
+                    pkm2 /= big;
+                    pkm1 /= big;
+                    qkm2 /= big;
+                    qkm1 /= big;
+                }
+            } while (t > MACHEP);
+
+        done:
+            if (ans == 0)
+                ans = 1.0;
+
+            /* Change n to n-1 if n < 0 and the continued fraction is small */
+            if (nflag > 0) {
+                if (std::abs(ans) < 0.125) {
+                    nflag = -1;
+                    *n = *n - 1.0;
+                    goto fstart;
+                }
+            }
+
+            kf = *newn;
+
+            /* backward recurrence
+             *              2k
+             *  J   (x)  =  --- J (x)  -  J   (x)
+             *   k-1         x   k         k+1
+             */
+
+            pk = 1.0;
+            pkm1 = 1.0 / ans;
+            k = *n - 1.0;
+            r = 2 * k;
+            do {
+                pkm2 = (pkm1 * r - pk * x) / x;
+                /*      pkp1 = pk; */
+                pk = pkm1;
+                pkm1 = pkm2;
+                r -= 2.0;
+                /*
+                 * t = fabs(pkp1) + fabs(pk);
+                 * if( (k > (kf + 2.5)) && (fabs(pkm1) < 0.25*t) )
+                 * {
+                 * k -= 1.0;
+                 * t = x*x;
+                 * pkm2 = ( (r*(r+2.0)-t)*pk - r*x*pkp1 )/t;
+                 * pkp1 = pk;
+                 * pk = pkm1;
+                 * pkm1 = pkm2;
+                 * r -= 2.0;
+                 * }
+                 */
+                k -= 1.0;
+            } while (k > (kf + 0.5));
+
+            /* Take the larger of the last two iterates
+             * on the theory that it may have less cancellation error.
+             */
+
+            if (cancel) {
+                if ((kf >= 0.0) && (std::abs(pk) > std::abs(pkm1))) {
+                    k += 1.0;
+                    pkm2 = pk;
+                }
+            }
+            *newn = k;
+            return (pkm2);
+        }
+
+        /* Ascending power series for Jv(x).
+         * AMS55 #9.1.10.
+         */
+
+        XSF_HOST_DEVICE inline double jv_jvs(double n, double x) {
+            double t, u, y, z, k;
+            int ex, sgngam;
+
+            z = -x * x / 4.0;
+            u = 1.0;
+            y = u;
+            k = 1.0;
+            t = 1.0;
+
+            while (t > MACHEP) {
+                u *= z / (k * (n + k));
+                y += u;
+                k += 1.0;
+                if (y != 0)
+                    t = std::abs(u / y);
+            }
+            t = std::frexp(0.5 * x, &ex);
+            ex = ex * n;
+            if ((ex > -1023) && (ex < 1023) && (n > 0.0) && (n < (MAXGAM - 1.0))) {
+                t = std::pow(0.5 * x, n) * xsf::cephes::rgamma(n + 1.0);
+                y *= t;
+            } else {
+                t = n * std::log(0.5 * x) - lgam_sgn(n + 1.0, &sgngam);
+                if (y < 0) {
+                    sgngam = -sgngam;
+                    y = -y;
+                }
+                t += std::log(y);
+                if (t < -MAXLOG) {
+                    return (0.0);
+                }
+                if (t > MAXLOG) {
+                    set_error("Jv", SF_ERROR_OVERFLOW, NULL);
+                    return (std::numeric_limits::infinity());
+                }
+                y = sgngam * std::exp(t);
+            }
+            return (y);
+        }
+
+        /* Hankel's asymptotic expansion
+         * for large x.
+         * AMS55 #9.2.5.
+         */
+
+        XSF_HOST_DEVICE inline double jv_hankel(double n, double x) {
+            double t, u, z, k, sign, conv;
+            double p, q, j, m, pp, qq;
+            int flag;
+
+            m = 4.0 * n * n;
+            j = 1.0;
+            z = 8.0 * x;
+            k = 1.0;
+            p = 1.0;
+            u = (m - 1.0) / z;
+            q = u;
+            sign = 1.0;
+            conv = 1.0;
+            flag = 0;
+            t = 1.0;
+            pp = 1.0e38;
+            qq = 1.0e38;
+
+            while (t > MACHEP) {
+                k += 2.0;
+                j += 1.0;
+                sign = -sign;
+                u *= (m - k * k) / (j * z);
+                p += sign * u;
+                k += 2.0;
+                j += 1.0;
+                u *= (m - k * k) / (j * z);
+                q += sign * u;
+                t = std::abs(u / p);
+                if (t < conv) {
+                    conv = t;
+                    qq = q;
+                    pp = p;
+                    flag = 1;
+                }
+                /* stop if the terms start getting larger */
+                if ((flag != 0) && (t > conv)) {
+                    goto hank1;
+                }
+            }
+
+        hank1:
+            u = x - (0.5 * n + 0.25) * M_PI;
+            t = std::sqrt(2.0 / (M_PI * x)) * (pp * std::cos(u) - qq * std::sin(u));
+            return (t);
+        }
+
+        /* Asymptotic expansion for transition region,
+         * n large and x close to n.
+         * AMS55 #9.3.23.
+         */
+
+        constexpr double jv_PF2[] = {-9.0000000000000000000e-2, 8.5714285714285714286e-2};
+
+        constexpr double jv_PF3[] = {1.3671428571428571429e-1, -5.4920634920634920635e-2, -4.4444444444444444444e-3};
+
+        constexpr double jv_PF4[] = {1.3500000000000000000e-3, -1.6036054421768707483e-1, 4.2590187590187590188e-2,
+                                     2.7330447330447330447e-3};
+
+        constexpr double jv_PG1[] = {-2.4285714285714285714e-1, 1.4285714285714285714e-2};
+
+        constexpr double jv_PG2[] = {-9.0000000000000000000e-3, 1.9396825396825396825e-1, -1.1746031746031746032e-2};
+
+        constexpr double jv_PG3[] = {1.9607142857142857143e-2, -1.5983694083694083694e-1, 6.3838383838383838384e-3};
+
+        XSF_HOST_DEVICE inline double jv_jnt(double n, double x) {
+            double z, zz, z3;
+            double cbn, n23, cbtwo;
+            double ai, aip, bi, bip; /* Airy functions */
+            double nk, fk, gk, pp, qq;
+            double F[5], G[4];
+            int k;
+
+            cbn = cbrt(n);
+            z = (x - n) / cbn;
+            cbtwo = cbrt(2.0);
+
+            /* Airy function */
+            zz = -cbtwo * z;
+            xsf::cephes::airy(zz, &ai, &aip, &bi, &bip);
+
+            /* polynomials in expansion */
+            zz = z * z;
+            z3 = zz * z;
+            F[0] = 1.0;
+            F[1] = -z / 5.0;
+            F[2] = xsf::cephes::polevl(z3, jv_PF2, 1) * zz;
+            F[3] = xsf::cephes::polevl(z3, jv_PF3, 2);
+            F[4] = xsf::cephes::polevl(z3, jv_PF4, 3) * z;
+            G[0] = 0.3 * zz;
+            G[1] = xsf::cephes::polevl(z3, jv_PG1, 1);
+            G[2] = xsf::cephes::polevl(z3, jv_PG2, 2) * z;
+            G[3] = xsf::cephes::polevl(z3, jv_PG3, 2) * zz;
+
+            pp = 0.0;
+            qq = 0.0;
+            nk = 1.0;
+            n23 = cbrt(n * n);
+
+            for (k = 0; k <= 4; k++) {
+                fk = F[k] * nk;
+                pp += fk;
+                if (k != 4) {
+                    gk = G[k] * nk;
+                    qq += gk;
+                }
+                nk /= n23;
+            }
+
+            fk = cbtwo * ai * pp / cbn + cbrt(4.0) * aip * qq / n;
+            return (fk);
+        }
+
+        /* Asymptotic expansion for large n.
+         * AMS55 #9.3.35.
+         */
+
+        constexpr double jv_lambda[] = {1.0,
+                                        1.041666666666666666666667E-1,
+                                        8.355034722222222222222222E-2,
+                                        1.282265745563271604938272E-1,
+                                        2.918490264641404642489712E-1,
+                                        8.816272674437576524187671E-1,
+                                        3.321408281862767544702647E+0,
+                                        1.499576298686255465867237E+1,
+                                        7.892301301158651813848139E+1,
+                                        4.744515388682643231611949E+2,
+                                        3.207490090890661934704328E+3};
+
+        constexpr double jv_mu[] = {1.0,
+                                    -1.458333333333333333333333E-1,
+                                    -9.874131944444444444444444E-2,
+                                    -1.433120539158950617283951E-1,
+                                    -3.172272026784135480967078E-1,
+                                    -9.424291479571202491373028E-1,
+                                    -3.511203040826354261542798E+0,
+                                    -1.572726362036804512982712E+1,
+                                    -8.228143909718594444224656E+1,
+                                    -4.923553705236705240352022E+2,
+                                    -3.316218568547972508762102E+3};
+
+        constexpr double jv_P1[] = {-2.083333333333333333333333E-1, 1.250000000000000000000000E-1};
+
+        constexpr double jv_P2[] = {3.342013888888888888888889E-1, -4.010416666666666666666667E-1,
+                                    7.031250000000000000000000E-2};
+
+        constexpr double jv_P3[] = {-1.025812596450617283950617E+0, 1.846462673611111111111111E+0,
+                                    -8.912109375000000000000000E-1, 7.324218750000000000000000E-2};
+
+        constexpr double jv_P4[] = {4.669584423426247427983539E+0, -1.120700261622299382716049E+1,
+                                    8.789123535156250000000000E+0, -2.364086914062500000000000E+0,
+                                    1.121520996093750000000000E-1};
+
+        constexpr double jv_P5[] = {-2.8212072558200244877E1, 8.4636217674600734632E1,  -9.1818241543240017361E1,
+                                    4.2534998745388454861E1,  -7.3687943594796316964E0, 2.27108001708984375E-1};
+
+        constexpr double jv_P6[] = {2.1257013003921712286E2,  -7.6525246814118164230E2, 1.0599904525279998779E3,
+                                    -6.9957962737613254123E2, 2.1819051174421159048E2,  -2.6491430486951555525E1,
+                                    5.7250142097473144531E-1};
+
+        constexpr double jv_P7[] = {-1.9194576623184069963E3, 8.0617221817373093845E3,  -1.3586550006434137439E4,
+                                    1.1655393336864533248E4,  -5.3056469786134031084E3, 1.2009029132163524628E3,
+                                    -1.0809091978839465550E2, 1.7277275025844573975E0};
+
+        XSF_HOST_DEVICE inline double jv_jnx(double n, double x) {
+            double zeta, sqz, zz, zp, np;
+            double cbn, n23, t, z, sz;
+            double pp, qq, z32i, zzi;
+            double ak, bk, akl, bkl;
+            int sign, doa, dob, nflg, k, s, tk, tkp1, m;
+            double u[8];
+            double ai, aip, bi, bip;
+
+            /* Test for x very close to n. Use expansion for transition region if so. */
+            cbn = cbrt(n);
+            z = (x - n) / cbn;
+            if (std::abs(z) <= 0.7) {
+                return (jv_jnt(n, x));
+            }
+
+            z = x / n;
+            zz = 1.0 - z * z;
+            if (zz == 0.0) {
+                return (0.0);
+            }
+
+            if (zz > 0.0) {
+                sz = std::sqrt(zz);
+                t = 1.5 * (std::log((1.0 + sz) / z) - sz); /* zeta ** 3/2          */
+                zeta = cbrt(t * t);
+                nflg = 1;
+            } else {
+                sz = std::sqrt(-zz);
+                t = 1.5 * (sz - std::acos(1.0 / z));
+                zeta = -cbrt(t * t);
+                nflg = -1;
+            }
+            z32i = std::abs(1.0 / t);
+            sqz = cbrt(t);
+
+            /* Airy function */
+            n23 = cbrt(n * n);
+            t = n23 * zeta;
+
+            xsf::cephes::airy(t, &ai, &aip, &bi, &bip);
+
+            /* polynomials in expansion */
+            u[0] = 1.0;
+            zzi = 1.0 / zz;
+            u[1] = xsf::cephes::polevl(zzi, jv_P1, 1) / sz;
+            u[2] = xsf::cephes::polevl(zzi, jv_P2, 2) / zz;
+            u[3] = xsf::cephes::polevl(zzi, jv_P3, 3) / (sz * zz);
+            pp = zz * zz;
+            u[4] = xsf::cephes::polevl(zzi, jv_P4, 4) / pp;
+            u[5] = xsf::cephes::polevl(zzi, jv_P5, 5) / (pp * sz);
+            pp *= zz;
+            u[6] = xsf::cephes::polevl(zzi, jv_P6, 6) / pp;
+            u[7] = xsf::cephes::polevl(zzi, jv_P7, 7) / (pp * sz);
+
+            pp = 0.0;
+            qq = 0.0;
+            np = 1.0;
+            /* flags to stop when terms get larger */
+            doa = 1;
+            dob = 1;
+            akl = std::numeric_limits::infinity();
+            bkl = std::numeric_limits::infinity();
+
+            for (k = 0; k <= 3; k++) {
+                tk = 2 * k;
+                tkp1 = tk + 1;
+                zp = 1.0;
+                ak = 0.0;
+                bk = 0.0;
+                for (s = 0; s <= tk; s++) {
+                    if (doa) {
+                        if ((s & 3) > 1)
+                            sign = nflg;
+                        else
+                            sign = 1;
+                        ak += sign * jv_mu[s] * zp * u[tk - s];
+                    }
+
+                    if (dob) {
+                        m = tkp1 - s;
+                        if (((m + 1) & 3) > 1)
+                            sign = nflg;
+                        else
+                            sign = 1;
+                        bk += sign * jv_lambda[s] * zp * u[m];
+                    }
+                    zp *= z32i;
+                }
+
+                if (doa) {
+                    ak *= np;
+                    t = std::abs(ak);
+                    if (t < akl) {
+                        akl = t;
+                        pp += ak;
+                    } else
+                        doa = 0;
+                }
+
+                if (dob) {
+                    bk += jv_lambda[tkp1] * zp * u[0];
+                    bk *= -np / sqz;
+                    t = std::abs(bk);
+                    if (t < bkl) {
+                        bkl = t;
+                        qq += bk;
+                    } else
+                        dob = 0;
+                }
+                if (np < MACHEP)
+                    break;
+                np /= n * n;
+            }
+
+            /* normalizing factor ( 4*zeta/(1 - z**2) )**1/4    */
+            t = 4.0 * zeta / zz;
+            t = sqrt(sqrt(t));
+
+            t *= ai * pp / cbrt(n) + aip * qq / (n23 * n);
+            return (t);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double jv(double n, double x) {
+        double k, q, t, y, an;
+        int i, sign, nint;
+
+        nint = 0; /* Flag for integer n */
+        sign = 1; /* Flag for sign inversion */
+        an = std::abs(n);
+        y = std::floor(an);
+        if (y == an) {
+            nint = 1;
+            i = an - 16384.0 * std::floor(an / 16384.0);
+            if (n < 0.0) {
+                if (i & 1)
+                    sign = -sign;
+                n = an;
+            }
+            if (x < 0.0) {
+                if (i & 1)
+                    sign = -sign;
+                x = -x;
+            }
+            if (n == 0.0)
+                return (j0(x));
+            if (n == 1.0)
+                return (sign * j1(x));
+        }
+
+        if ((x < 0.0) && (y != an)) {
+            set_error("Jv", SF_ERROR_DOMAIN, NULL);
+            y = std::numeric_limits::quiet_NaN();
+            goto done;
+        }
+
+        if (x == 0 && n < 0 && !nint) {
+            set_error("Jv", SF_ERROR_OVERFLOW, NULL);
+            return std::numeric_limits::infinity() * rgamma(n + 1);
+        }
+
+        y = std::abs(x);
+
+        if (y * y < std::abs(n + 1) * detail::MACHEP) {
+            return std::pow(0.5 * x, n) * rgamma(n + 1);
+        }
+
+        k = 3.6 * std::sqrt(y);
+        t = 3.6 * std::sqrt(an);
+        if ((y < t) && (an > 21.0)) {
+            return (sign * detail::jv_jvs(n, x));
+        }
+        if ((an < k) && (y > 21.0))
+            return (sign * detail::jv_hankel(n, x));
+
+        if (an < 500.0) {
+            /* Note: if x is too large, the continued fraction will fail; but then the
+             * Hankel expansion can be used. */
+            if (nint != 0) {
+                k = 0.0;
+                q = detail::jv_recur(&n, x, &k, 1);
+                if (k == 0.0) {
+                    y = j0(x) / q;
+                    goto done;
+                }
+                if (k == 1.0) {
+                    y = j1(x) / q;
+                    goto done;
+                }
+            }
+
+            if (an > 2.0 * y)
+                goto rlarger;
+
+            if ((n >= 0.0) && (n < 20.0) && (y > 6.0) && (y < 20.0)) {
+                /* Recur backwards from a larger value of n */
+            rlarger:
+                k = n;
+
+                y = y + an + 1.0;
+                if (y < 30.0)
+                    y = 30.0;
+                y = n + std::floor(y - n);
+                q = detail::jv_recur(&y, x, &k, 0);
+                y = detail::jv_jvs(y, x) * q;
+                goto done;
+            }
+
+            if (k <= 30.0) {
+                k = 2.0;
+            } else if (k < 90.0) {
+                k = (3 * k) / 4;
+            }
+            if (an > (k + 3.0)) {
+                if (n < 0.0) {
+                    k = -k;
+                }
+                q = n - std::floor(n);
+                k = std::floor(k) + q;
+                if (n > 0.0) {
+                    q = detail::jv_recur(&n, x, &k, 1);
+                } else {
+                    t = k;
+                    k = n;
+                    q = detail::jv_recur(&t, x, &k, 1);
+                    k = t;
+                }
+                if (q == 0.0) {
+                    y = 0.0;
+                    goto done;
+                }
+            } else {
+                k = n;
+                q = 1.0;
+            }
+
+            /* boundary between convergence of
+             * power series and Hankel expansion
+             */
+            y = std::abs(k);
+            if (y < 26.0)
+                t = (0.0083 * y + 0.09) * y + 12.9;
+            else
+                t = 0.9 * y;
+
+            if (x > t)
+                y = detail::jv_hankel(k, x);
+            else
+                y = detail::jv_jvs(k, x);
+            if (n > 0.0)
+                y /= q;
+            else
+                y *= q;
+        }
+
+        else {
+            /* For large n, use the uniform expansion or the transitional expansion.
+             * But if x is of the order of n**2, these may blow up, whereas the
+             * Hankel expansion will then work.
+             */
+            if (n < 0.0) {
+                set_error("jv", SF_ERROR_LOSS, NULL);
+                y = std::numeric_limits::quiet_NaN();
+                goto done;
+            }
+            t = x / n;
+            t /= n;
+            if (t > 0.3)
+                y = detail::jv_hankel(n, x);
+            else
+                y = detail::jv_jnx(n, x);
+        }
+
+    done:
+        return (sign * y);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h
new file mode 100644
index 0000000000000000000000000000000000000000..f617b93c73009072498fe4f6f20671a9f83d84e1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h
@@ -0,0 +1,164 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     k0.c
+ *
+ *     Modified Bessel function, third kind, order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k0();
+ *
+ * y = k0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of the third kind
+ * of order zero of the argument.
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at 2000 random points between 0 and 8.  Peak absolute
+ * error (relative when K0 > 1) was 1.46e-14; rms, 4.26e-15.
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.2e-15     1.6e-16
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ *  K0 domain          x <= 0          INFINITY
+ *
+ */
+/*							k0e()
+ *
+ *	Modified Bessel function, third kind, order zero,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k0e();
+ *
+ * y = k0e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of the third kind of order zero of the argument.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.4e-15     1.4e-16
+ * See k0().
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "chbevl.h"
+#include "i0.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Chebyshev coefficients for K0(x) + log(x/2) I0(x)
+         * in the interval [0,2].  The odd order coefficients are all
+         * zero; only the even order coefficients are listed.
+         *
+         * lim(x->0){ K0(x) + log(x/2) I0(x) } = -EUL.
+         */
+
+        constexpr double k0_A[] = {1.37446543561352307156E-16, 4.25981614279661018399E-14, 1.03496952576338420167E-11,
+                                   1.90451637722020886025E-9,  2.53479107902614945675E-7,  2.28621210311945178607E-5,
+                                   1.26461541144692592338E-3,  3.59799365153615016266E-2,  3.44289899924628486886E-1,
+                                   -5.35327393233902768720E-1};
+
+        /* Chebyshev coefficients for exp(x) sqrt(x) K0(x)
+         * in the inverted interval [2,infinity].
+         *
+         * lim(x->inf){ exp(x) sqrt(x) K0(x) } = sqrt(pi/2).
+         */
+        constexpr double k0_B[] = {
+            5.30043377268626276149E-18,  -1.64758043015242134646E-17, 5.21039150503902756861E-17,
+            -1.67823109680541210385E-16, 5.51205597852431940784E-16,  -1.84859337734377901440E-15,
+            6.34007647740507060557E-15,  -2.22751332699166985548E-14, 8.03289077536357521100E-14,
+            -2.98009692317273043925E-13, 1.14034058820847496303E-12,  -4.51459788337394416547E-12,
+            1.85594911495471785253E-11,  -7.95748924447710747776E-11, 3.57739728140030116597E-10,
+            -1.69753450938905987466E-9,  8.57403401741422608519E-9,   -4.66048989768794782956E-8,
+            2.76681363944501510342E-7,   -1.83175552271911948767E-6,  1.39498137188764993662E-5,
+            -1.28495495816278026384E-4,  1.56988388573005337491E-3,   -3.14481013119645005427E-2,
+            2.44030308206595545468E0};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double k0(double x) {
+        double y, z;
+
+        if (x == 0.0) {
+            set_error("k0", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k0", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x);
+            return (y);
+        }
+        z = 8.0 / x - 2.0;
+        y = std::exp(-x) * chbevl(z, detail::k0_B, 25) / std::sqrt(x);
+        return (y);
+    }
+
+    XSF_HOST_DEVICE double inline k0e(double x) {
+        double y;
+
+        if (x == 0.0) {
+            set_error("k0e", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k0e", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x);
+            return (y * exp(x));
+        }
+
+        y = chbevl(8.0 / x - 2.0, detail::k0_B, 25) / std::sqrt(x);
+        return (y);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h
new file mode 100644
index 0000000000000000000000000000000000000000..96594fd9c345e6fd2ecf02a269601cd2d9592525
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h
@@ -0,0 +1,163 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     k1.c
+ *
+ *     Modified Bessel function, third kind, order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k1();
+ *
+ * y = k1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Computes the modified Bessel function of the third kind
+ * of order one of the argument.
+ *
+ * The range is partitioned into the two intervals [0,2] and
+ * (2, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.2e-15     1.6e-16
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * k1 domain          x <= 0          INFINITY
+ *
+ */
+/*							k1e.c
+ *
+ *	Modified Bessel function, third kind, order one,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k1e();
+ *
+ * y = k1e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of the third kind of order one of the argument:
+ *
+ *      k1e(x) = exp(x) * k1(x).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       7.8e-16     1.2e-16
+ * See k1().
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "chbevl.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Chebyshev coefficients for x(K1(x) - log(x/2) I1(x))
+         * in the interval [0,2].
+         *
+         * lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1.
+         */
+
+        constexpr double k1_A[] = {
+            -7.02386347938628759343E-18, -2.42744985051936593393E-15, -6.66690169419932900609E-13,
+            -1.41148839263352776110E-10, -2.21338763073472585583E-8,  -2.43340614156596823496E-6,
+            -1.73028895751305206302E-4,  -6.97572385963986435018E-3,  -1.22611180822657148235E-1,
+            -3.53155960776544875667E-1,  1.52530022733894777053E0};
+
+        /* Chebyshev coefficients for exp(x) sqrt(x) K1(x)
+         * in the interval [2,infinity].
+         *
+         * lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2).
+         */
+        constexpr double k1_B[] = {
+            -5.75674448366501715755E-18, 1.79405087314755922667E-17,  -5.68946255844285935196E-17,
+            1.83809354436663880070E-16,  -6.05704724837331885336E-16, 2.03870316562433424052E-15,
+            -7.01983709041831346144E-15, 2.47715442448130437068E-14,  -8.97670518232499435011E-14,
+            3.34841966607842919884E-13,  -1.28917396095102890680E-12, 5.13963967348173025100E-12,
+            -2.12996783842756842877E-11, 9.21831518760500529508E-11,  -4.19035475934189648750E-10,
+            2.01504975519703286596E-9,   -1.03457624656780970260E-8,  5.74108412545004946722E-8,
+            -3.50196060308781257119E-7,  2.40648494783721712015E-6,   -1.93619797416608296024E-5,
+            1.95215518471351631108E-4,   -2.85781685962277938680E-3,  1.03923736576817238437E-1,
+            2.72062619048444266945E0};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double k1(double x) {
+        double y, z;
+
+        if (x == 0.0) {
+            set_error("k1", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k1", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        z = 0.5 * x;
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = std::log(z) * i1(x) + chbevl(y, detail::k1_A, 11) / x;
+            return (y);
+        }
+
+        return (std::exp(-x) * chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x));
+    }
+
+    XSF_HOST_DEVICE double k1e(double x) {
+        double y;
+
+        if (x == 0.0) {
+            set_error("k1e", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k1e", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = std::log(0.5 * x) * i1(x) + chbevl(y, detail::k1_A, 11) / x;
+            return (y * exp(x));
+        }
+
+        return (chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h
new file mode 100644
index 0000000000000000000000000000000000000000..31bc9fd7f735002f3381749f8d14c02545155c69
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h
@@ -0,0 +1,243 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     kn.c
+ *
+ *     Modified Bessel function, third kind, integer order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, kn();
+ * int n;
+ *
+ * y = kn( n, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of the third kind
+ * of order n of the argument.
+ *
+ * The range is partitioned into the two intervals [0,9.55] and
+ * (9.55, infinity).  An ascending power series is used in the
+ * low range, and an asymptotic expansion in the high range.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        90000       1.8e-8      3.0e-10
+ *
+ *  Error is high only near the crossover point x = 9.55
+ * between the two expansions used.
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * Algorithm for Kn.
+ *                        n-1
+ *                    -n   -  (n-k-1)!    2   k
+ * K (x)  =  0.5 (x/2)     >  -------- (-x /4)
+ *  n                      -     k!
+ *                        k=0
+ *
+ *                     inf.                                   2   k
+ *        n         n   -                                   (x /4)
+ *  + (-1)  0.5(x/2)    >  {p(k+1) + p(n+k+1) - 2log(x/2)} ---------
+ *                      -                                  k! (n+k)!
+ *                     k=0
+ *
+ * where  p(m) is the psi function: p(1) = -EUL and
+ *
+ *                       m-1
+ *                        -
+ *       p(m)  =  -EUL +  >  1/k
+ *                        -
+ *                       k=1
+ *
+ * For large x,
+ *                                          2        2     2
+ *                                       u-1     (u-1 )(u-3 )
+ * K (z)  =  sqrt(pi/2z) exp(-z) { 1 + ------- + ------------ + ...}
+ *  v                                        1            2
+ *                                     1! (8z)     2! (8z)
+ * asymptotically, where
+ *
+ *            2
+ *     u = 4 v .
+ *
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int kn_MAXFAC = 31;
+
+    }
+
+    XSF_HOST_DEVICE inline double kn(int nn, double x) {
+        double k, kf, nk1f, nkf, zn, t, s, z0, z;
+        double ans, fn, pn, pk, zmn, tlg, tox;
+        int i, n;
+
+        if (nn < 0)
+            n = -nn;
+        else
+            n = nn;
+
+        if (n > detail::kn_MAXFAC) {
+        overf:
+            set_error("kn", SF_ERROR_OVERFLOW, NULL);
+            return (std::numeric_limits::infinity());
+        }
+
+        if (x <= 0.0) {
+            if (x < 0.0) {
+                set_error("kn", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            } else {
+                set_error("kn", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+
+        if (x > 9.55)
+            goto asymp;
+
+        ans = 0.0;
+        z0 = 0.25 * x * x;
+        fn = 1.0;
+        pn = 0.0;
+        zmn = 1.0;
+        tox = 2.0 / x;
+
+        if (n > 0) {
+            /* compute factorial of n and psi(n) */
+            pn = -detail::SCIPY_EULER;
+            k = 1.0;
+            for (i = 1; i < n; i++) {
+                pn += 1.0 / k;
+                k += 1.0;
+                fn *= k;
+            }
+
+            zmn = tox;
+
+            if (n == 1) {
+                ans = 1.0 / x;
+            } else {
+                nk1f = fn / n;
+                kf = 1.0;
+                s = nk1f;
+                z = -z0;
+                zn = 1.0;
+                for (i = 1; i < n; i++) {
+                    nk1f = nk1f / (n - i);
+                    kf = kf * i;
+                    zn *= z;
+                    t = nk1f * zn / kf;
+                    s += t;
+                    if ((std::numeric_limits::max() - std::abs(t)) < std::abs(s)) {
+                        goto overf;
+                    }
+                    if ((tox > 1.0) && ((std::numeric_limits::max() / tox) < zmn)) {
+                        goto overf;
+                    }
+                    zmn *= tox;
+                }
+                s *= 0.5;
+                t = std::abs(s);
+                if ((zmn > 1.0) && ((std::numeric_limits::max() / zmn) < t)) {
+                    goto overf;
+                }
+                if ((t > 1.0) && ((std::numeric_limits::max() / t) < zmn)) {
+                    goto overf;
+                }
+                ans = s * zmn;
+            }
+        }
+
+        tlg = 2.0 * log(0.5 * x);
+        pk = -detail::SCIPY_EULER;
+        if (n == 0) {
+            pn = pk;
+            t = 1.0;
+        } else {
+            pn = pn + 1.0 / n;
+            t = 1.0 / fn;
+        }
+        s = (pk + pn - tlg) * t;
+        k = 1.0;
+        do {
+            t *= z0 / (k * (k + n));
+            pk += 1.0 / k;
+            pn += 1.0 / (k + n);
+            s += (pk + pn - tlg) * t;
+            k += 1.0;
+        } while (fabs(t / s) > detail::MACHEP);
+
+        s = 0.5 * s / zmn;
+        if (n & 1) {
+            s = -s;
+        }
+        ans += s;
+
+        return (ans);
+
+        /* Asymptotic expansion for Kn(x) */
+        /* Converges to 1.4e-17 for x > 18.4 */
+
+    asymp:
+
+        if (x > detail::MAXLOG) {
+            set_error("kn", SF_ERROR_UNDERFLOW, NULL);
+            return (0.0);
+        }
+        k = n;
+        pn = 4.0 * k * k;
+        pk = 1.0;
+        z0 = 8.0 * x;
+        fn = 1.0;
+        t = 1.0;
+        s = t;
+        nkf = std::numeric_limits::infinity();
+        i = 0;
+        do {
+            z = pn - pk * pk;
+            t = t * z / (fn * z0);
+            nk1f = std::abs(t);
+            if ((i >= n) && (nk1f > nkf)) {
+                goto adone;
+            }
+            nkf = nk1f;
+            s += t;
+            fn += 1.0;
+            pk += 2.0;
+            i += 1;
+        } while (std::abs(t / s) > detail::MACHEP);
+
+    adone:
+        ans = std::exp(-x) * std::sqrt(M_PI / (2.0 * x)) * s;
+        return (ans);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8cbbe1d693f99e96d74cd40a1a15e32b8035871
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h
@@ -0,0 +1,112 @@
+/*  (C) Copyright John Maddock 2006.
+ *  Use, modification and distribution are subject to the
+ *  Boost Software License, Version 1.0. (See accompanying file
+ *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+
+/* Both lanczos.h and lanczos.c were formed from Boost's lanczos.hpp
+ *
+ * Scipy changes:
+ * - 06-22-2016: Removed all code not related to double precision and
+ *   ported to c for use in Cephes. Note that the order of the
+ *   coefficients is reversed to match the behavior of polevl.
+ */
+
+/*
+ * Optimal values for G for each N are taken from
+ * https://web.viu.ca/pughg/phdThesis/phdThesis.pdf,
+ * as are the theoretical error bounds.
+ *
+ * Constants calculated using the method described by Godfrey
+ * https://my.fit.edu/~gabdo/gamma.txt and elaborated by Toth at
+ * https://www.rskey.org/gamma.htm using NTL::RR at 1000 bit precision.
+ */
+
+/*
+ * Lanczos Coefficients for N=13 G=6.024680040776729583740234375
+ * Max experimental error (with arbitrary precision arithmetic) 1.196214e-17
+ * Generated with compiler: Microsoft Visual C++ version 8.0 on Win32 at Mar 23 2006
+ *
+ * Use for double precision.
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double lanczos_num[] = {
+            2.506628274631000270164908177133837338626, 210.8242777515793458725097339207133627117,
+            8071.672002365816210638002902272250613822, 186056.2653952234950402949897160456992822,
+            2876370.628935372441225409051620849613599, 31426415.58540019438061423162831820536287,
+            248874557.8620541565114603864132294232163, 1439720407.311721673663223072794912393972,
+            6039542586.35202800506429164430729792107,  17921034426.03720969991975575445893111267,
+            35711959237.35566804944018545154716670596, 42919803642.64909876895789904700198885093,
+            23531376880.41075968857200767445163675473};
+
+        constexpr double lanczos_denom[] = {1,        66,        1925,      32670,     357423,   2637558, 13339535,
+                                            45995730, 105258076, 150917976, 120543840, 39916800, 0};
+
+        constexpr double lanczos_sum_expg_scaled_num[] = {
+            0.006061842346248906525783753964555936883222, 0.5098416655656676188125178644804694509993,
+            19.51992788247617482847860966235652136208,    449.9445569063168119446858607650988409623,
+            6955.999602515376140356310115515198987526,    75999.29304014542649875303443598909137092,
+            601859.6171681098786670226533699352302507,    3481712.15498064590882071018964774556468,
+            14605578.08768506808414169982791359218571,    43338889.32467613834773723740590533316085,
+            86363131.28813859145546927288977868422342,    103794043.1163445451906271053616070238554,
+            56906521.91347156388090791033559122686859};
+
+        constexpr double lanczos_sum_expg_scaled_denom[] = {
+            1, 66, 1925, 32670, 357423, 2637558, 13339535, 45995730, 105258076, 150917976, 120543840, 39916800, 0};
+
+        constexpr double lanczos_sum_near_1_d[] = {
+            0.3394643171893132535170101292240837927725e-9,  -0.2499505151487868335680273909354071938387e-8,
+            0.8690926181038057039526127422002498960172e-8,  -0.1933117898880828348692541394841204288047e-7,
+            0.3075580174791348492737947340039992829546e-7,  -0.2752907702903126466004207345038327818713e-7,
+            -0.1515973019871092388943437623825208095123e-5, 0.004785200610085071473880915854204301886437,
+            -0.1993758927614728757314233026257810172008,    1.483082862367253753040442933770164111678,
+            -3.327150580651624233553677113928873034916,     2.208709979316623790862569924861841433016};
+
+        constexpr double lanczos_sum_near_2_d[] = {
+            0.1009141566987569892221439918230042368112e-8,  -0.7430396708998719707642735577238449585822e-8,
+            0.2583592566524439230844378948704262291927e-7,  -0.5746670642147041587497159649318454348117e-7,
+            0.9142922068165324132060550591210267992072e-7,  -0.8183698410724358930823737982119474130069e-7,
+            -0.4506604409707170077136555010018549819192e-5, 0.01422519127192419234315002746252160965831,
+            -0.5926941084905061794445733628891024027949,    4.408830289125943377923077727900630927902,
+            -9.8907772644920670589288081640128194231,       6.565936202082889535528455955485877361223};
+
+        XSF_HOST_DEVICE double lanczos_sum(double x) { return ratevl(x, lanczos_num, 12, lanczos_denom, 12); }
+
+        XSF_HOST_DEVICE double lanczos_sum_near_1(double dx) {
+            double result = 0;
+            unsigned k;
+
+            for (k = 1; k <= 12; ++k) {
+                result += (-lanczos_sum_near_1_d[k - 1] * dx) / (k * dx + k * k);
+            }
+            return result;
+        }
+
+        XSF_HOST_DEVICE double lanczos_sum_near_2(double dx) {
+            double result = 0;
+            double x = dx + 2;
+            unsigned k;
+
+            for (k = 1; k <= 12; ++k) {
+                result += (-lanczos_sum_near_2_d[k - 1] * dx) / (x + k * x + k * k - 1);
+            }
+            return result;
+        }
+    } // namespace detail
+
+    constexpr double lanczos_g = 6.024680040776729583740234375;
+    XSF_HOST_DEVICE double lanczos_sum_expg_scaled(double x) {
+        return ratevl(x, detail::lanczos_sum_expg_scaled_num, 12, detail::lanczos_sum_expg_scaled_denom, 12);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h
new file mode 100644
index 0000000000000000000000000000000000000000..a3611d26ba44a78ab69736f9c69fe5dd4d2bc538
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h
@@ -0,0 +1,275 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ndtr.c
+ *
+ *     Normal distribution function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, ndtr();
+ *
+ * y = ndtr( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the Gaussian probability density
+ * function, integrated from minus infinity to x:
+ *
+ *                            x
+ *                             -
+ *                   1        | |          2
+ *    ndtr(x)  = ---------    |    exp( - t /2 ) dt
+ *               sqrt(2pi)  | |
+ *                           -
+ *                          -inf.
+ *
+ *             =  ( 1 + erf(z) ) / 2
+ *             =  erfc(z) / 2
+ *
+ * where z = x/sqrt(2). Computation is via the functions
+ * erf and erfc.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -13,0        30000       3.4e-14     6.7e-15
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition         value returned
+ * erfc underflow    x > 37.519379347       0.0
+ *
+ */
+/*							erf.c
+ *
+ *	Error function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, erf();
+ *
+ * y = erf( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * The integral is
+ *
+ *                           x
+ *                            -
+ *                 2         | |          2
+ *   erf(x)  =  --------     |    exp( - t  ) dt.
+ *              sqrt(pi)   | |
+ *                          -
+ *                           0
+ *
+ * For 0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2); otherwise
+ * erf(x) = 1 - erfc(x).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,1         30000       3.7e-16     1.0e-16
+ *
+ */
+/*							erfc.c
+ *
+ *	Complementary error function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, erfc();
+ *
+ * y = erfc( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *  1 - erf(x) =
+ *
+ *                           inf.
+ *                             -
+ *                  2         | |          2
+ *   erfc(x)  =  --------     |    exp( - t  ) dt
+ *               sqrt(pi)   | |
+ *                           -
+ *                            x
+ *
+ *
+ * For small x, erfc(x) = 1 - erf(x); otherwise rational
+ * approximations are computed.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,26.6417   30000       5.7e-14     1.5e-14
+ */
+
+/*
+ * Cephes Math Library Release 2.2:  June, 1992
+ * Copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ndtr_P[] = {2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0,
+                                     4.86371970985681366614E1,   1.96520832956077098242E2,  5.26445194995477358631E2,
+                                     9.34528527171957607540E2,   1.02755188689515710272E3,  5.57535335369399327526E2};
+
+        constexpr double ndtr_Q[] = {
+            /* 1.00000000000000000000E0, */
+            1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, 9.75708501743205489753E2,
+            1.82390916687909736289E3, 2.24633760818710981792E3, 1.65666309194161350182E3, 5.57535340817727675546E2};
+
+        constexpr double ndtr_R[] = {5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0,
+                                     6.16021097993053585195E0,  7.40974269950448939160E0, 2.97886665372100240670E0};
+
+        constexpr double ndtr_S[] = {
+            /* 1.00000000000000000000E0, */
+            2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1,
+            1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0};
+
+        constexpr double ndtr_T[] = {9.60497373987051638749E0, 9.00260197203842689217E1, 2.23200534594684319226E3,
+                                     7.00332514112805075473E3, 5.55923013010394962768E4};
+
+        constexpr double ndtr_U[] = {
+            /* 1.00000000000000000000E0, */
+            3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, 2.26290000613890934246E4,
+            4.92673942608635921086E4};
+
+        constexpr double ndtri_UTHRESH = 37.519379347;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double erf(double x);
+
+    XSF_HOST_DEVICE inline double erfc(double a) {
+        double p, q, x, y, z;
+
+        if (std::isnan(a)) {
+            set_error("erfc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (a < 0.0) {
+            x = -a;
+        } else {
+            x = a;
+        }
+
+        if (x < 1.0) {
+            return 1.0 - erf(a);
+        }
+
+        z = -a * a;
+
+        if (z < -detail::MAXLOG) {
+            goto under;
+        }
+
+        z = std::exp(z);
+
+        if (x < 8.0) {
+            p = polevl(x, detail::ndtr_P, 8);
+            q = p1evl(x, detail::ndtr_Q, 8);
+        } else {
+            p = polevl(x, detail::ndtr_R, 5);
+            q = p1evl(x, detail::ndtr_S, 6);
+        }
+        y = (z * p) / q;
+
+        if (a < 0) {
+            y = 2.0 - y;
+        }
+
+        if (y != 0.0) {
+            return y;
+        }
+
+    under:
+        set_error("erfc", SF_ERROR_UNDERFLOW, NULL);
+        if (a < 0) {
+            return 2.0;
+        } else {
+            return 0.0;
+        }
+    }
+
+    XSF_HOST_DEVICE inline double erf(double x) {
+        double y, z;
+
+        if (std::isnan(x)) {
+            set_error("erf", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x < 0.0) {
+            return -erf(-x);
+        }
+
+        if (std::abs(x) > 1.0) {
+            return (1.0 - erfc(x));
+        }
+        z = x * x;
+
+        y = x * polevl(z, detail::ndtr_T, 4) / p1evl(z, detail::ndtr_U, 5);
+        return y;
+    }
+
+    XSF_HOST_DEVICE inline double ndtr(double a) {
+        double x, y, z;
+
+        if (std::isnan(a)) {
+            set_error("ndtr", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        x = a * M_SQRT1_2;
+        z = std::abs(x);
+
+        if (z < 1.0) {
+            y = 0.5 + 0.5 * erf(x);
+        } else {
+            y = 0.5 * erfc(z);
+            if (x > 0) {
+                y = 1.0 - y;
+            }
+        }
+
+        return y;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h
new file mode 100644
index 0000000000000000000000000000000000000000..add3a995f38870cad5155b5fda1730e4fcbf1ee3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h
@@ -0,0 +1,85 @@
+/*
+ * Pochhammer symbol (a)_m = gamma(a + m) / gamma(a)
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "gamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        XSF_HOST_DEVICE inline double is_nonpos_int(double x) {
+            return x <= 0 && x == std::ceil(x) && std::abs(x) < 1e13;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double poch(double a, double m) {
+        double r = 1.0;
+
+        /*
+         * 1. Reduce magnitude of `m` to |m| < 1 by using recurrence relations.
+         *
+         * This may end up in over/underflow, but then the function itself either
+         * diverges or goes to zero. In case the remainder goes to the opposite
+         * direction, we end up returning 0*INF = NAN, which is OK.
+         */
+
+        /* Recurse down */
+        while (m >= 1.0) {
+            if (a + m == 1) {
+                break;
+            }
+            m -= 1.0;
+            r *= (a + m);
+            if (!std::isfinite(r) || r == 0) {
+                break;
+            }
+        }
+
+        /* Recurse up */
+        while (m <= -1.0) {
+            if (a + m == 0) {
+                break;
+            }
+            r /= (a + m);
+            m += 1.0;
+            if (!std::isfinite(r) || r == 0) {
+                break;
+            }
+        }
+
+        /*
+         * 2. Evaluate function with reduced `m`
+         *
+         * Now either `m` is not big, or the `r` product has over/underflown.
+         * If so, the function itself does similarly.
+         */
+
+        if (m == 0) {
+            /* Easy case */
+            return r;
+        } else if (a > 1e4 && std::abs(m) <= 1) {
+            /* Avoid loss of precision */
+            return r * std::pow(a, m) *
+                   (1 + m * (m - 1) / (2 * a) + m * (m - 1) * (m - 2) * (3 * m - 1) / (24 * a * a) +
+                    m * m * (m - 1) * (m - 1) * (m - 2) * (m - 3) / (48 * a * a * a));
+        }
+
+        /* Check for infinity */
+        if (detail::is_nonpos_int(a + m) && !detail::is_nonpos_int(a) && a + m != m) {
+            return std::numeric_limits::infinity();
+        }
+
+        /* Check for zero */
+        if (!detail::is_nonpos_int(a + m) && detail::is_nonpos_int(a)) {
+            return 0;
+        }
+
+        return r * std::exp(lgam(a + m) - lgam(a)) * gammasgn(a + m) * gammasgn(a);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h
new file mode 100644
index 0000000000000000000000000000000000000000..912a506cfb6c0d5fe75ead2d14576ddd57698788
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h
@@ -0,0 +1,167 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     polevl.c
+ *                                                     p1evl.c
+ *
+ *     Evaluate polynomial
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int N;
+ * double x, y, coef[N+1], polevl[];
+ *
+ * y = polevl( x, coef, N );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates polynomial of degree N:
+ *
+ *                     2          N
+ * y  =  C  + C x + C x  +...+ C x
+ *        0    1     2          N
+ *
+ * Coefficients are stored in reverse order:
+ *
+ * coef[0] = C  , ..., coef[N] = C  .
+ *            N                   0
+ *
+ * The function p1evl() assumes that c_N = 1.0 so that coefficent
+ * is omitted from the array.  Its calling arguments are
+ * otherwise the same as polevl().
+ *
+ *
+ * SPEED:
+ *
+ * In the interest of speed, there are no checks for out
+ * of bounds arithmetic.  This routine is used by most of
+ * the functions in the library.  Depending on available
+ * equipment features, the user may wish to rewrite the
+ * program in microcode or assembly language.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.1:  December, 1988
+ * Copyright 1984, 1987, 1988 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+
+/* Sources:
+ * [1] Holin et. al., "Polynomial and Rational Function Evaluation",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/roots/rational.html
+ */
+
+/* Scipy changes:
+ * - 06-23-2016: add code for evaluating rational functions
+ */
+
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+    XSF_HOST_DEVICE inline double polevl(double x, const double coef[], int N) {
+        double ans;
+        int i;
+        const double *p;
+
+        p = coef;
+        ans = *p++;
+        i = N;
+
+        do {
+            ans = ans * x + *p++;
+        } while (--i);
+
+        return (ans);
+    }
+
+    /*                                                     p1evl() */
+    /*                                          N
+     * Evaluate polynomial when coefficient of x  is 1.0.
+     * That is, C_{N} is assumed to be 1, and that coefficient
+     * is not included in the input array coef.
+     * coef must have length N and contain the polynomial coefficients
+     * stored as
+     *     coef[0] = C_{N-1}
+     *     coef[1] = C_{N-2}
+     *          ...
+     *     coef[N-2] = C_1
+     *     coef[N-1] = C_0
+     * Otherwise same as polevl.
+     */
+
+    XSF_HOST_DEVICE inline double p1evl(double x, const double coef[], int N) {
+        double ans;
+        const double *p;
+        int i;
+
+        p = coef;
+        ans = x + *p++;
+        i = N - 1;
+
+        do
+            ans = ans * x + *p++;
+        while (--i);
+
+        return (ans);
+    }
+
+    /* Evaluate a rational function. See [1]. */
+
+    /* The function ratevl is only used once in cephes/lanczos.h. */
+    XSF_HOST_DEVICE inline double ratevl(double x, const double num[], int M, const double denom[], int N) {
+        int i, dir;
+        double y, num_ans, denom_ans;
+        double absx = std::abs(x);
+        const double *p;
+
+        if (absx > 1) {
+            /* Evaluate as a polynomial in 1/x. */
+            dir = -1;
+            p = num + M;
+            y = 1 / x;
+        } else {
+            dir = 1;
+            p = num;
+            y = x;
+        }
+
+        /* Evaluate the numerator */
+        num_ans = *p;
+        p += dir;
+        for (i = 1; i <= M; i++) {
+            num_ans = num_ans * y + *p;
+            p += dir;
+        }
+
+        /* Evaluate the denominator */
+        if (absx > 1) {
+            p = denom + N;
+        } else {
+            p = denom;
+        }
+
+        denom_ans = *p;
+        p += dir;
+        for (i = 1; i <= N; i++) {
+            denom_ans = denom_ans * y + *p;
+            p += dir;
+        }
+
+        if (absx > 1) {
+            i = M - N;
+            return std::pow(x, i) * num_ans / denom_ans;
+        } else {
+            return num_ans / denom_ans;
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h
new file mode 100644
index 0000000000000000000000000000000000000000..c028e9ea14e0066c3b8c13d2c26c2773e61f767a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h
@@ -0,0 +1,194 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     psi.c
+ *
+ *     Psi (digamma) function
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, psi();
+ *
+ * y = psi( x );
+ *
+ *
+ * DESCRIPTION:
+ *
+ *              d      -
+ *   psi(x)  =  -- ln | (x)
+ *              dx
+ *
+ * is the logarithmic derivative of the gamma function.
+ * For integer x,
+ *                   n-1
+ *                    -
+ * psi(n) = -EUL  +   >  1/k.
+ *                    -
+ *                   k=1
+ *
+ * This formula is used for 0 < n <= 10.  If x is negative, it
+ * is transformed to a positive argument by the reflection
+ * formula  psi(1-x) = psi(x) + pi cot(pi x).
+ * For general positive x, the argument is made greater than 10
+ * using the recurrence  psi(x+1) = psi(x) + 1/x.
+ * Then the following asymptotic expansion is applied:
+ *
+ *                           inf.   B
+ *                            -      2k
+ * psi(x) = log(x) - 1/2x -   >   -------
+ *                            -        2k
+ *                           k=1   2k x
+ *
+ * where the B2k are Bernoulli numbers.
+ *
+ * ACCURACY:
+ *    Relative error (except absolute when |psi| < 1):
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       1.3e-15     1.4e-16
+ *    IEEE      -30,0       40000       1.5e-15     2.2e-16
+ *
+ * ERROR MESSAGES:
+ *     message         condition      value returned
+ * psi singularity    x integer <=0      INFINITY
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * Code for the rational approximation on [1, 2] is:
+ *
+ * (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. (See accompanying file
+ * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr double psi_A[] = {8.33333333333333333333E-2,  -2.10927960927960927961E-2, 7.57575757575757575758E-3,
+                                    -4.16666666666666666667E-3, 3.96825396825396825397E-3,  -8.33333333333333333333E-3,
+                                    8.33333333333333333333E-2};
+
+        constexpr float psi_Y = 0.99558162689208984f;
+
+        constexpr double psi_root1 = 1569415565.0 / 1073741824.0;
+        constexpr double psi_root2 = (381566830.0 / 1073741824.0) / 1073741824.0;
+        constexpr double psi_root3 = 0.9016312093258695918615325266959189453125e-19;
+
+        constexpr double psi_P[] = {-0.0020713321167745952, -0.045251321448739056, -0.28919126444774784,
+                                    -0.65031853770896507,   -0.32555031186804491,  0.25479851061131551};
+        constexpr double psi_Q[] = {-0.55789841321675513e-6,
+                                    0.0021284987017821144,
+                                    0.054151797245674225,
+                                    0.43593529692665969,
+                                    1.4606242909763515,
+                                    2.0767117023730469,
+                                    1.0};
+
+        XSF_HOST_DEVICE double digamma_imp_1_2(double x) {
+            /*
+             * Rational approximation on [1, 2] taken from Boost.
+             *
+             * Now for the approximation, we use the form:
+             *
+             * digamma(x) = (x - root) * (Y + R(x-1))
+             *
+             * Where root is the location of the positive root of digamma,
+             * Y is a constant, and R is optimised for low absolute error
+             * compared to Y.
+             *
+             * Maximum Deviation Found:               1.466e-18
+             * At double precision, max error found:  2.452e-17
+             */
+            double r, g;
+
+            g = x - psi_root1;
+            g -= psi_root2;
+            g -= psi_root3;
+            r = xsf::cephes::polevl(x - 1.0, psi_P, 5) / xsf::cephes::polevl(x - 1.0, psi_Q, 6);
+
+            return g * psi_Y + g * r;
+        }
+
+        XSF_HOST_DEVICE double psi_asy(double x) {
+            double y, z;
+
+            if (x < 1.0e17) {
+                z = 1.0 / (x * x);
+                y = z * xsf::cephes::polevl(z, psi_A, 6);
+            } else {
+                y = 0.0;
+            }
+
+            return std::log(x) - (0.5 / x) - y;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double psi(double x) {
+        double y = 0.0;
+        double q, r;
+        int i, n;
+
+        if (std::isnan(x)) {
+            return x;
+        } else if (x == std::numeric_limits::infinity()) {
+            return x;
+        } else if (x == -std::numeric_limits::infinity()) {
+            return std::numeric_limits::quiet_NaN();
+        } else if (x == 0) {
+            set_error("psi", SF_ERROR_SINGULAR, NULL);
+            return std::copysign(std::numeric_limits::infinity(), -x);
+        } else if (x < 0.0) {
+            /* argument reduction before evaluating tan(pi * x) */
+            r = std::modf(x, &q);
+            if (r == 0.0) {
+                set_error("psi", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            y = -M_PI / std::tan(M_PI * r);
+            x = 1.0 - x;
+        }
+
+        /* check for positive integer up to 10 */
+        if ((x <= 10.0) && (x == std::floor(x))) {
+            n = static_cast(x);
+            for (i = 1; i < n; i++) {
+                y += 1.0 / i;
+            }
+            y -= detail::SCIPY_EULER;
+            return y;
+        }
+
+        /* use the recurrence relation to move x into [1, 2] */
+        if (x < 1.0) {
+            y -= 1.0 / x;
+            x += 1.0;
+        } else if (x < 10.0) {
+            while (x > 2.0) {
+                x -= 1.0;
+                y += 1.0 / x;
+            }
+        }
+        if ((1.0 <= x) && (x <= 2.0)) {
+            y += detail::digamma_imp_1_2(x);
+            return y;
+        }
+
+        /* x is large, use the asymptotic series */
+        y += detail::psi_asy(x);
+        return y;
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..97f29b33ab50abb01f4ee4b71d0f2fbc6ffd1858
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h
@@ -0,0 +1,111 @@
+/*                                             rgamma.c
+ *
+ *     Reciprocal Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, rgamma();
+ *
+ * y = rgamma( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns one divided by the Gamma function of the argument.
+ *
+ * The function is approximated by a Chebyshev expansion in
+ * the interval [0,1].  Range reduction is by recurrence
+ * for arguments between -34.034 and +34.84425627277176174.
+ * 0 is returned for positive arguments outside this
+ * range.  For arguments less than -34.034 the cosecant
+ * reflection formula is applied; lograrithms are employed
+ * to avoid unnecessary overflow.
+ *
+ * The reciprocal Gamma function has no singularities,
+ * but overflow and underflow may occur for large arguments.
+ * These conditions return either INFINITY or 0 with
+ * appropriate sign.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -30,+30      30000       1.1e-15     2.0e-16
+ * For arguments less than -34.034 the peak error is on the
+ * order of 5e-15 (DEC), excepting overflow or underflow.
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "chbevl.h"
+#include "const.h"
+#include "gamma.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for reciprocal Gamma function
+         * in interval 0 to 1.  Function is 1/(x Gamma(x)) - 1
+         */
+
+        constexpr double rgamma_R[] = {
+            3.13173458231230000000E-17, -6.70718606477908000000E-16, 2.20039078172259550000E-15,
+            2.47691630348254132600E-13, -6.60074100411295197440E-12, 5.13850186324226978840E-11,
+            1.08965386454418662084E-9,  -3.33964630686836942556E-8,  2.68975996440595483619E-7,
+            2.96001177518801696639E-6,  -8.04814124978471142852E-5,  4.16609138709688864714E-4,
+            5.06579864028608725080E-3,  -6.41925436109158228810E-2,  -4.98558728684003594785E-3,
+            1.27546015610523951063E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE double rgamma(double x) {
+        double w, y, z;
+
+	if (x == 0) {
+	    // This case is separate from below to get correct sign for zero.
+	    return x;
+	}
+
+	if (x < 0 && x == std::floor(x)) {
+	    // Gamma poles.
+	    return 0.0;
+	}
+
+	if (std::abs(x) > 4.0) {
+	    return 1.0 / Gamma(x);
+	}
+
+        z = 1.0;
+        w = x;
+
+        while (w > 1.0) { /* Downward recurrence */
+            w -= 1.0;
+            z *= w;
+        }
+        while (w < 0.0) { /* Upward recurrence */
+            z /= w;
+            w += 1.0;
+        }
+        if (w == 0.0) /* Nonpositive integer */
+            return (0.0);
+        if (w == 1.0) /* Other integer */
+            return (1.0 / z);
+
+        y = w * (1.0 + chbevl(4.0 * w - 2.0, detail::rgamma_R, 16)) / z;
+        return (y);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h
new file mode 100644
index 0000000000000000000000000000000000000000..fe0c631e34582d32132afdf41e2e6904fda90c82
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h
@@ -0,0 +1,811 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     iv.c
+ *
+ *     Modified Bessel function of noninteger order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, iv();
+ *
+ * y = iv( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order v of the
+ * argument.  If x is negative, v must be integer valued.
+ *
+ */
+/*                                                     iv.c    */
+/*     Modified Bessel function of noninteger order            */
+/* If x < 0, then v must be an integer. */
+
+/*
+ * Parts of the code are copyright:
+ *
+ *     Cephes Math Library Release 2.8:  June, 2000
+ *     Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ *
+ * And other parts:
+ *
+ *     Copyright (c) 2006 Xiaogang Zhang
+ *     Use, modification and distribution are subject to the
+ *     Boost Software License, Version 1.0.
+ *
+ *     Boost Software License - Version 1.0 - August 17th, 2003
+ *
+ *     Permission is hereby granted, free of charge, to any person or
+ *     organization obtaining a copy of the software and accompanying
+ *     documentation covered by this license (the "Software") to use, reproduce,
+ *     display, distribute, execute, and transmit the Software, and to prepare
+ *     derivative works of the Software, and to permit third-parties to whom the
+ *     Software is furnished to do so, all subject to the following:
+ *
+ *     The copyright notices in the Software and this entire statement,
+ *     including the above license grant, this restriction and the following
+ *     disclaimer, must be included in all copies of the Software, in whole or
+ *     in part, and all derivative works of the Software, unless such copies or
+ *     derivative works are solely in the form of machine-executable object code
+ *     generated by a source language processor.
+ *
+ *     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, TITLE AND
+ *     NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
+ *     DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
+ *     WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ *     CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ *     SOFTWARE.
+ *
+ * And the rest are:
+ *
+ *     Copyright (C) 2009 Pauli Virtanen
+ *     Distributed under the same license as Scipy.
+ *
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /*
+         * Compute Iv from (AMS5 9.7.1), asymptotic expansion for large |z|
+         * Iv ~ exp(x)/sqrt(2 pi x) ( 1 + (4*v*v-1)/8x + (4*v*v-1)(4*v*v-9)/8x/2! + ...)
+         */
+        XSF_HOST_DEVICE inline double iv_asymptotic(double v, double x) {
+            double mu;
+            double sum, term, prefactor, factor;
+            int k;
+
+            prefactor = std::exp(x) / std::sqrt(2 * M_PI * x);
+
+            if (prefactor == std::numeric_limits::infinity()) {
+                return prefactor;
+            }
+
+            mu = 4 * v * v;
+            sum = 1.0;
+            term = 1.0;
+            k = 1;
+
+            do {
+                factor = (mu - (2 * k - 1) * (2 * k - 1)) / (8 * x) / k;
+                if (k > 100) {
+                    /* didn't converge */
+                    set_error("iv(iv_asymptotic)", SF_ERROR_NO_RESULT, NULL);
+                    break;
+                }
+                term *= -factor;
+                sum += term;
+                ++k;
+            } while (std::abs(term) > MACHEP * std::abs(sum));
+            return sum * prefactor;
+        }
+
+        /*
+         * Uniform asymptotic expansion factors, (AMS5 9.3.9; AMS5 9.3.10)
+         *
+         * Computed with:
+         * --------------------
+         import numpy as np
+         t = np.poly1d([1,0])
+         def up1(p):
+         return .5*t*t*(1-t*t)*p.deriv() + 1/8. * ((1-5*t*t)*p).integ()
+         us = [np.poly1d([1])]
+         for k in range(10):
+         us.append(up1(us[-1]))
+         n = us[-1].order
+         for p in us:
+         print "{" + ", ".join(["0"]*(n-p.order) + map(repr, p)) + "},"
+         print "N_UFACTORS", len(us)
+         print "N_UFACTOR_TERMS", us[-1].order + 1
+         * --------------------
+         */
+        constexpr int iv_N_UFACTORS = 11;
+        constexpr int iv_N_UFACTOR_TERMS = 31;
+
+        constexpr double iv_asymptotic_ufactors[iv_N_UFACTORS][iv_N_UFACTOR_TERMS] = {
+            {0, 0, 0, 0, 0, 0, 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, 0, 0, 0, -0.20833333333333334,
+             0.0, 0.125, 0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0.3342013888888889,
+             0.0,
+             -0.40104166666666669,
+             0.0,
+             0.0703125,
+             0.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.0258125964506173,
+             0.0, 1.8464626736111112,
+             0.0, -0.89121093750000002,
+             0.0, 0.0732421875,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             4.6695844234262474,
+             0.0,
+             -11.207002616222995,
+             0.0,
+             8.78912353515625,
+             0.0,
+             -2.3640869140624998,
+             0.0,
+             0.112152099609375,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -28.212072558200244,
+             0.0, 84.636217674600744,
+             0.0, -91.818241543240035,
+             0.0, 42.534998745388457,
+             0.0, -7.3687943594796312,
+             0.0, 0.22710800170898438,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             212.5701300392171,
+             0.0,
+             -765.25246814118157,
+             0.0,
+             1059.9904525279999,
+             0.0,
+             -699.57962737613275,
+             0.0,
+             218.19051174421159,
+             0.0,
+             -26.491430486951554,
+             0.0,
+             0.57250142097473145,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -1919.4576623184068,
+             0.0, 8061.7221817373083,
+             0.0, -13586.550006434136,
+             0.0, 11655.393336864536,
+             0.0, -5305.6469786134048,
+             0.0, 1200.9029132163525,
+             0.0, -108.09091978839464,
+             0.0, 1.7277275025844574,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             20204.291330966149,
+             0.0,
+             -96980.598388637503,
+             0.0,
+             192547.0012325315,
+             0.0,
+             -203400.17728041555,
+             0.0,
+             122200.46498301747,
+             0.0,
+             -41192.654968897557,
+             0.0,
+             7109.5143024893641,
+             0.0,
+             -493.915304773088,
+             0.0,
+             6.074042001273483,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   -242919.18790055133,
+             0.0, 1311763.6146629769,
+             0.0, -2998015.9185381061,
+             0.0, 3763271.2976564039,
+             0.0, -2813563.2265865342,
+             0.0, 1268365.2733216248,
+             0.0, -331645.17248456361,
+             0.0, 45218.768981362737,
+             0.0, -2499.8304818112092,
+             0.0, 24.380529699556064,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {3284469.8530720375,
+             0.0,
+             -19706819.11843222,
+             0.0,
+             50952602.492664628,
+             0.0,
+             -74105148.211532637,
+             0.0,
+             66344512.274729028,
+             0.0,
+             -37567176.660763353,
+             0.0,
+             13288767.166421819,
+             0.0,
+             -2785618.1280864552,
+             0.0,
+             308186.40461266245,
+             0.0,
+             -13886.089753717039,
+             0.0,
+             110.01714026924674,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0}};
+
+        /*
+         * Compute Iv, Kv from (AMS5 9.7.7 + 9.7.8), asymptotic expansion for large v
+         */
+        XSF_HOST_DEVICE inline void ikv_asymptotic_uniform(double v, double x, double *i_value, double *k_value) {
+            double i_prefactor, k_prefactor;
+            double t, t2, eta, z;
+            double i_sum, k_sum, term, divisor;
+            int k, n;
+            int sign = 1;
+
+            if (v < 0) {
+                /* Negative v; compute I_{-v} and K_{-v} and use (AMS 9.6.2) */
+                sign = -1;
+                v = -v;
+            }
+
+            z = x / v;
+            t = 1 / std::sqrt(1 + z * z);
+            t2 = t * t;
+            eta = std::sqrt(1 + z * z) + std::log(z / (1 + 1 / t));
+
+            i_prefactor = std::sqrt(t / (2 * M_PI * v)) * std::exp(v * eta);
+            i_sum = 1.0;
+
+            k_prefactor = std::sqrt(M_PI * t / (2 * v)) * std::exp(-v * eta);
+            k_sum = 1.0;
+
+            divisor = v;
+            for (n = 1; n < iv_N_UFACTORS; ++n) {
+                /*
+                 * Evaluate u_k(t) with Horner's scheme;
+                 * (using the knowledge about which coefficients are zero)
+                 */
+                term = 0;
+                for (k = iv_N_UFACTOR_TERMS - 1 - 3 * n; k < iv_N_UFACTOR_TERMS - n; k += 2) {
+                    term *= t2;
+                    term += iv_asymptotic_ufactors[n][k];
+                }
+                for (k = 1; k < n; k += 2) {
+                    term *= t2;
+                }
+                if (n % 2 == 1) {
+                    term *= t;
+                }
+
+                /* Sum terms */
+                term /= divisor;
+                i_sum += term;
+                k_sum += (n % 2 == 0) ? term : -term;
+
+                /* Check convergence */
+                if (std::abs(term) < MACHEP) {
+                    break;
+                }
+
+                divisor *= v;
+            }
+
+            if (std::abs(term) > 1e-3 * std::abs(i_sum)) {
+                /* Didn't converge */
+                set_error("ikv_asymptotic_uniform", SF_ERROR_NO_RESULT, NULL);
+            }
+            if (std::abs(term) > MACHEP * std::abs(i_sum)) {
+                /* Some precision lost */
+                set_error("ikv_asymptotic_uniform", SF_ERROR_LOSS, NULL);
+            }
+
+            if (k_value != NULL) {
+                /* symmetric in v */
+                *k_value = k_prefactor * k_sum;
+            }
+
+            if (i_value != NULL) {
+                if (sign == 1) {
+                    *i_value = i_prefactor * i_sum;
+                } else {
+                    /* (AMS 9.6.2) */
+                    *i_value = (i_prefactor * i_sum + (2 / M_PI) * xsf::cephes::sinpi(v) * k_prefactor * k_sum);
+                }
+            }
+        }
+
+        /*
+         * The following code originates from the Boost C++ library,
+         * from file `boost/math/special_functions/detail/bessel_ik.hpp`,
+         * converted from C++ to C.
+         */
+
+        /*
+         * Modified Bessel functions of the first and second kind of fractional order
+         *
+         * Calculate K(v, x) and K(v+1, x) by method analogous to
+         * Temme, Journal of Computational Physics, vol 21, 343 (1976)
+         */
+        XSF_HOST_DEVICE inline int temme_ik_series(double v, double x, double *K, double *K1) {
+            double f, h, p, q, coef, sum, sum1, tolerance;
+            double a, b, c, d, sigma, gamma1, gamma2;
+            std::uint64_t k;
+            double gp;
+            double gm;
+
+            /*
+             * |x| <= 2, Temme series converge rapidly
+             * |x| > 2, the larger the |x|, the slower the convergence
+             */
+            XSF_ASSERT(std::abs(x) <= 2);
+            XSF_ASSERT(std::abs(v) <= 0.5f);
+
+            gp = xsf::cephes::Gamma(v + 1) - 1;
+            gm = xsf::cephes::Gamma(-v + 1) - 1;
+
+            a = std::log(x / 2);
+            b = std::exp(v * a);
+            sigma = -a * v;
+            c = std::abs(v) < MACHEP ? 1 : xsf::cephes::sinpi(v) / (v * M_PI);
+            d = std::abs(sigma) < MACHEP ? 1 : std::sinh(sigma) / sigma;
+            gamma1 = std::abs(v) < MACHEP ? -SCIPY_EULER : (0.5 / v) * (gp - gm) * c;
+            gamma2 = (2 + gp + gm) * c / 2;
+
+            /* initial values */
+            p = (gp + 1) / (2 * b);
+            q = (1 + gm) * b / 2;
+            f = (std::cosh(sigma) * gamma1 + d * (-a) * gamma2) / c;
+            h = p;
+            coef = 1;
+            sum = coef * f;
+            sum1 = coef * h;
+
+            /* series summation */
+            tolerance = MACHEP;
+            for (k = 1; k < MAXITER; k++) {
+                f = (k * f + p + q) / (k * k - v * v);
+                p /= k - v;
+                q /= k + v;
+                h = p - k * f;
+                coef *= x * x / (4 * k);
+                sum += coef * f;
+                sum1 += coef * h;
+                if (std::abs(coef * f) < std::abs(sum) * tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(temme_ik_series)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *K = sum;
+            *K1 = 2 * sum1 / x;
+
+            return 0;
+        }
+
+        /* Evaluate continued fraction fv = I_(v+1) / I_v, derived from
+         * Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73 */
+        XSF_HOST_DEVICE inline int CF1_ik(double v, double x, double *fv) {
+            double C, D, f, a, b, delta, tiny, tolerance;
+            std::uint64_t k;
+
+            /*
+             * |x| <= |v|, CF1_ik converges rapidly
+             * |x| > |v|, CF1_ik needs O(|x|) iterations to converge
+             */
+
+            /*
+             * modified Lentz's method, see
+             * Lentz, Applied Optics, vol 15, 668 (1976)
+             */
+            tolerance = 2 * MACHEP;
+            tiny = 1 / std::sqrt(std::numeric_limits::max());
+            C = f = tiny; /* b0 = 0, replace with tiny */
+            D = 0;
+            for (k = 1; k < MAXITER; k++) {
+                a = 1;
+                b = 2 * (v + k) / x;
+                C = b + a / C;
+                D = b + a * D;
+                if (C == 0) {
+                    C = tiny;
+                }
+                if (D == 0) {
+                    D = tiny;
+                }
+                D = 1 / D;
+                delta = C * D;
+                f *= delta;
+                if (std::abs(delta - 1) <= tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(CF1_ik)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *fv = f;
+
+            return 0;
+        }
+
+        /*
+         * Calculate K(v, x) and K(v+1, x) by evaluating continued fraction
+         * z1 / z0 = U(v+1.5, 2v+1, 2x) / U(v+0.5, 2v+1, 2x), see
+         * Thompson and Barnett, Computer Physics Communications, vol 47, 245 (1987)
+         */
+        XSF_HOST_DEVICE inline int CF2_ik(double v, double x, double *Kv, double *Kv1) {
+
+            double S, C, Q, D, f, a, b, q, delta, tolerance, current, prev;
+            std::uint64_t k;
+
+            /*
+             * |x| >= |v|, CF2_ik converges rapidly
+             * |x| -> 0, CF2_ik fails to converge
+             */
+
+            XSF_ASSERT(std::abs(x) > 1);
+
+            /*
+             * Steed's algorithm, see Thompson and Barnett,
+             * Journal of Computational Physics, vol 64, 490 (1986)
+             */
+            tolerance = MACHEP;
+            a = v * v - 0.25;
+            b = 2 * (x + 1);                /* b1 */
+            D = 1 / b;                      /* D1 = 1 / b1 */
+            f = delta = D;                  /* f1 = delta1 = D1, coincidence */
+            prev = 0;                       /* q0 */
+            current = 1;                    /* q1 */
+            Q = C = -a;                     /* Q1 = C1 because q1 = 1 */
+            S = 1 + Q * delta;              /* S1 */
+            for (k = 2; k < MAXITER; k++) { /* starting from 2 */
+                /* continued fraction f = z1 / z0 */
+                a -= 2 * (k - 1);
+                b += 2;
+                D = 1 / (b + a * D);
+                delta *= b * D - 1;
+                f += delta;
+
+                /* series summation S = 1 + \sum_{n=1}^{\infty} C_n * z_n / z_0 */
+                q = (prev - (b - 2) * current) / a;
+                prev = current;
+                current = q; /* forward recurrence for q */
+                C *= -a / k;
+                Q += C * q;
+                S += Q * delta;
+
+                /* S converges slower than f */
+                if (std::abs(Q * delta) < std::abs(S) * tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(CF2_ik)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *Kv = std::sqrt(M_PI / (2 * x)) * std::exp(-x) / S;
+            *Kv1 = *Kv * (0.5 + v + x + (v * v - 0.25) * f) / x;
+
+            return 0;
+        }
+
+        /* Flags for what to compute */
+        enum { ikv_temme_need_i = 0x1, ikv_temme_need_k = 0x2 };
+
+        /*
+         * Compute I(v, x) and K(v, x) simultaneously by Temme's method, see
+         * Temme, Journal of Computational Physics, vol 19, 324 (1975)
+         */
+        XSF_HOST_DEVICE inline void ikv_temme(double v, double x, double *Iv_p, double *Kv_p) {
+            /* Kv1 = K_(v+1), fv = I_(v+1) / I_v */
+            /* Ku1 = K_(u+1), fu = I_(u+1) / I_u */
+            double u, Iv, Kv, Kv1, Ku, Ku1, fv;
+            double W, current, prev, next;
+            int reflect = 0;
+            unsigned n, k;
+            int kind;
+
+            kind = 0;
+            if (Iv_p != NULL) {
+                kind |= ikv_temme_need_i;
+            }
+            if (Kv_p != NULL) {
+                kind |= ikv_temme_need_k;
+            }
+
+            if (v < 0) {
+                reflect = 1;
+                v = -v; /* v is non-negative from here */
+                kind |= ikv_temme_need_k;
+            }
+            n = std::round(v);
+            u = v - n; /* -1/2 <= u < 1/2 */
+
+            if (x < 0) {
+                if (Iv_p != NULL)
+                    *Iv_p = std::numeric_limits::quiet_NaN();
+                if (Kv_p != NULL)
+                    *Kv_p = std::numeric_limits::quiet_NaN();
+                set_error("ikv_temme", SF_ERROR_DOMAIN, NULL);
+                return;
+            }
+            if (x == 0) {
+                Iv = (v == 0) ? 1 : 0;
+                if (kind & ikv_temme_need_k) {
+                    set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL);
+                    Kv = std::numeric_limits::infinity();
+                } else {
+                    Kv = std::numeric_limits::quiet_NaN(); /* any value will do */
+                }
+
+                if (reflect && (kind & ikv_temme_need_i)) {
+                    double z = (u + n % 2);
+
+                    Iv = xsf::cephes::sinpi(z) == 0 ? Iv : std::numeric_limits::infinity();
+                    if (std::isinf(Iv)) {
+                        set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL);
+                    }
+                }
+
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv;
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+                return;
+            }
+            /* x is positive until reflection */
+            W = 1 / x;                            /* Wronskian */
+            if (x <= 2) {                         /* x in (0, 2] */
+                temme_ik_series(u, x, &Ku, &Ku1); /* Temme series */
+            } else {                              /* x in (2, \infty) */
+                CF2_ik(u, x, &Ku, &Ku1);          /* continued fraction CF2_ik */
+            }
+            prev = Ku;
+            current = Ku1;
+            for (k = 1; k <= n; k++) { /* forward recurrence for K */
+                next = 2 * (u + k) * current / x + prev;
+                prev = current;
+                current = next;
+            }
+            Kv = prev;
+            Kv1 = current;
+            if (kind & ikv_temme_need_i) {
+                double lim = (4 * v * v + 10) / (8 * x);
+
+                lim *= lim;
+                lim *= lim;
+                lim /= 24;
+                if ((lim < MACHEP * 10) && (x > 100)) {
+                    /*
+                     * x is huge compared to v, CF1 may be very slow
+                     * to converge so use asymptotic expansion for large
+                     * x case instead.  Note that the asymptotic expansion
+                     * isn't very accurate - so it's deliberately very hard
+                     * to get here - probably we're going to overflow:
+                     */
+                    Iv = iv_asymptotic(v, x);
+                } else {
+                    CF1_ik(v, x, &fv);        /* continued fraction CF1_ik */
+                    Iv = W / (Kv * fv + Kv1); /* Wronskian relation */
+                }
+            } else {
+                Iv = std::numeric_limits::quiet_NaN(); /* any value will do */
+            }
+
+            if (reflect) {
+                double z = (u + n % 2);
+
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv + (2 / M_PI) * xsf::cephes::sinpi(z) * Kv; /* reflection formula */
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+            } else {
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv;
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+            }
+            return;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double iv(double v, double x) {
+        int sign;
+        double t, ax, res;
+
+        if (std::isnan(v) || std::isnan(x)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        /* If v is a negative integer, invoke symmetry */
+        t = std::floor(v);
+        if (v < 0.0) {
+            if (t == v) {
+                v = -v; /* symmetry */
+                t = -t;
+            }
+        }
+        /* If x is negative, require v to be an integer */
+        sign = 1;
+        if (x < 0.0) {
+            if (t != v) {
+                set_error("iv", SF_ERROR_DOMAIN, NULL);
+                return (std::numeric_limits::quiet_NaN());
+            }
+            if (v != 2.0 * std::floor(v / 2.0)) {
+                sign = -1;
+            }
+        }
+
+        /* Avoid logarithm singularity */
+        if (x == 0.0) {
+            if (v == 0.0) {
+                return 1.0;
+            }
+            if (v < 0.0) {
+                set_error("iv", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            } else
+                return 0.0;
+        }
+
+        ax = std::abs(x);
+        if (std::abs(v) > 50) {
+            /*
+             * Uniform asymptotic expansion for large orders.
+             *
+             * This appears to overflow slightly later than the Boost
+             * implementation of Temme's method.
+             */
+            detail::ikv_asymptotic_uniform(v, ax, &res, NULL);
+        } else {
+            /* Otherwise: Temme's method */
+            detail::ikv_temme(v, ax, &res, NULL);
+        }
+        res *= sign;
+        return res;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h
new file mode 100644
index 0000000000000000000000000000000000000000..fcdd2d7986466e33bff8bf15235c2d2814206d61
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h
@@ -0,0 +1,248 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     shichi.c
+ *
+ *     Hyperbolic sine and cosine integrals
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, Chi, Shi, shichi();
+ *
+ * shichi( x, &Chi, &Shi );
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integrals
+ *
+ *                            x
+ *                            -
+ *                           | |   cosh t - 1
+ *   Chi(x) = eul + ln x +   |    -----------  dt,
+ *                         | |          t
+ *                          -
+ *                          0
+ *
+ *               x
+ *               -
+ *              | |  sinh t
+ *   Shi(x) =   |    ------  dt
+ *            | |       t
+ *             -
+ *             0
+ *
+ * where eul = 0.57721566490153286061 is Euler's constant.
+ * The integrals are evaluated by power series for x < 8
+ * and by Chebyshev expansions for x between 8 and 88.
+ * For large x, both functions approach exp(x)/2x.
+ * Arguments greater than 88 in magnitude return INFINITY.
+ *
+ *
+ * ACCURACY:
+ *
+ * Test interval 0 to 88.
+ *                      Relative error:
+ * arithmetic   function  # trials      peak         rms
+ *    IEEE         Shi      30000       6.9e-16     1.6e-16
+ *        Absolute error, except relative when |Chi| > 1:
+ *    IEEE         Chi      30000       8.4e-16     1.4e-16
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "chbevl.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* x exp(-x) shi(x), inverted interval 8 to 18 */
+        constexpr double shichi_S1[] = {
+            1.83889230173399459482E-17,  -9.55485532279655569575E-17, 2.04326105980879882648E-16,
+            1.09896949074905343022E-15,  -1.31313534344092599234E-14, 5.93976226264314278932E-14,
+            -3.47197010497749154755E-14, -1.40059764613117131000E-12, 9.49044626224223543299E-12,
+            -1.61596181145435454033E-11, -1.77899784436430310321E-10, 1.35455469767246947469E-9,
+            -1.03257121792819495123E-9,  -3.56699611114982536845E-8,  1.44818877384267342057E-7,
+            7.82018215184051295296E-7,   -5.39919118403805073710E-6,  -3.12458202168959833422E-5,
+            8.90136741950727517826E-5,   2.02558474743846862168E-3,   2.96064440855633256972E-2,
+            1.11847751047257036625E0};
+
+        /* x exp(-x) shi(x), inverted interval 18 to 88 */
+        constexpr double shichi_S2[] = {
+            -1.05311574154850938805E-17, 2.62446095596355225821E-17,  8.82090135625368160657E-17,
+            -3.38459811878103047136E-16, -8.30608026366935789136E-16, 3.93397875437050071776E-15,
+            1.01765565969729044505E-14,  -4.21128170307640802703E-14, -1.60818204519802480035E-13,
+            3.34714954175994481761E-13,  2.72600352129153073807E-12,  1.66894954752839083608E-12,
+            -3.49278141024730899554E-11, -1.58580661666482709598E-10, -1.79289437183355633342E-10,
+            1.76281629144264523277E-9,   1.69050228879421288846E-8,   1.25391771228487041649E-7,
+            1.16229947068677338732E-6,   1.61038260117376323993E-5,   3.49810375601053973070E-4,
+            1.28478065259647610779E-2,   1.03665722588798326712E0};
+
+        /* x exp(-x) chin(x), inverted interval 8 to 18 */
+        constexpr double shichi_C1[] = {
+            -8.12435385225864036372E-18, 2.17586413290339214377E-17, 5.22624394924072204667E-17,
+            -9.48812110591690559363E-16, 5.35546311647465209166E-15, -1.21009970113732918701E-14,
+            -6.00865178553447437951E-14, 7.16339649156028587775E-13, -2.93496072607599856104E-12,
+            -1.40359438136491256904E-12, 8.76302288609054966081E-11, -4.40092476213282340617E-10,
+            -1.87992075640569295479E-10, 1.31458150989474594064E-8,  -4.75513930924765465590E-8,
+            -2.21775018801848880741E-7,  1.94635531373272490962E-6,  4.33505889257316408893E-6,
+            -6.13387001076494349496E-5,  -3.13085477492997465138E-4, 4.97164789823116062801E-4,
+            2.64347496031374526641E-2,   1.11446150876699213025E0};
+
+        /* x exp(-x) chin(x), inverted interval 18 to 88 */
+        constexpr double shichi_C2[] = {
+            8.06913408255155572081E-18,  -2.08074168180148170312E-17, -5.98111329658272336816E-17,
+            2.68533951085945765591E-16,  4.52313941698904694774E-16,  -3.10734917335299464535E-15,
+            -4.42823207332531972288E-15, 3.49639695410806959872E-14,  6.63406731718911586609E-14,
+            -3.71902448093119218395E-13, -1.27135418132338309016E-12, 2.74851141935315395333E-12,
+            2.33781843985453438400E-11,  2.71436006377612442764E-11,  -2.56600180000355990529E-10,
+            -1.61021375163803438552E-9,  -4.72543064876271773512E-9,  -3.00095178028681682282E-9,
+            7.79387474390914922337E-8,   1.06942765566401507066E-6,   1.59503164802313196374E-5,
+            3.49592575153777996871E-4,   1.28475387530065247392E-2,   1.03665693917934275131E0};
+
+        /*
+         * Evaluate 3F0(a1, a2, a3; z)
+         *
+         * The series is only asymptotic, so this requires z large enough.
+         */
+        XSF_HOST_DEVICE inline double hyp3f0(double a1, double a2, double a3, double z) {
+            int n, maxiter;
+            double err, sum, term, m;
+
+            m = std::pow(z, -1.0 / 3);
+            if (m < 50) {
+                maxiter = m;
+            } else {
+                maxiter = 50;
+            }
+
+            term = 1.0;
+            sum = term;
+            for (n = 0; n < maxiter; ++n) {
+                term *= (a1 + n) * (a2 + n) * (a3 + n) * z / (n + 1);
+                sum += term;
+                if (std::abs(term) < 1e-13 * std::abs(sum) || term == 0) {
+                    break;
+                }
+            }
+
+            err = std::abs(term);
+
+            if (err > 1e-13 * std::abs(sum)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            return sum;
+        }
+
+    } // namespace detail
+
+    /* Sine and cosine integrals */
+    XSF_HOST_DEVICE inline int shichi(double x, double *si, double *ci) {
+        double k, z, c, s, a, b;
+        short sign;
+
+        if (x < 0.0) {
+            sign = -1;
+            x = -x;
+        } else {
+            sign = 0;
+        }
+
+        if (x == 0.0) {
+            *si = 0.0;
+            *ci = -std::numeric_limits::infinity();
+            return (0);
+        }
+
+        if (x >= 8.0) {
+            goto chb;
+        }
+
+        if (x >= 88.0) {
+            goto asymp;
+        }
+
+        z = x * x;
+
+        /*     Direct power series expansion   */
+        a = 1.0;
+        s = 1.0;
+        c = 0.0;
+        k = 2.0;
+
+        do {
+            a *= z / k;
+            c += a / k;
+            k += 1.0;
+            a /= k;
+            s += a / k;
+            k += 1.0;
+        } while (std::abs(a / s) > detail::MACHEP);
+
+        s *= x;
+        goto done;
+
+    chb:
+        /* Chebyshev series expansions */
+        if (x < 18.0) {
+            a = (576.0 / x - 52.0) / 10.0;
+            k = std::exp(x) / x;
+            s = k * chbevl(a, detail::shichi_S1, 22);
+            c = k * chbevl(a, detail::shichi_C1, 23);
+            goto done;
+        }
+
+        if (x <= 88.0) {
+            a = (6336.0 / x - 212.0) / 70.0;
+            k = std::exp(x) / x;
+            s = k * chbevl(a, detail::shichi_S2, 23);
+            c = k * chbevl(a, detail::shichi_C2, 24);
+            goto done;
+        }
+
+    asymp:
+        if (x > 1000) {
+            *si = std::numeric_limits::infinity();
+            *ci = std::numeric_limits::infinity();
+        } else {
+            /* Asymptotic expansions
+             * http://functions.wolfram.com/GammaBetaErf/CoshIntegral/06/02/
+             * http://functions.wolfram.com/GammaBetaErf/SinhIntegral/06/02/0001/
+             */
+            a = detail::hyp3f0(0.5, 1, 1, 4.0 / (x * x));
+            b = detail::hyp3f0(1, 1, 1.5, 4.0 / (x * x));
+            *si = std::cosh(x) / x * a + std::sinh(x) / (x * x) * b;
+            *ci = std::sinh(x) / x * a + std::cosh(x) / (x * x) * b;
+        }
+        if (sign) {
+            *si = -*si;
+        }
+        return 0;
+
+    done:
+        if (sign) {
+            s = -s;
+        }
+
+        *si = s;
+
+        *ci = detail::SCIPY_EULER + std::log(x) + c;
+        return (0);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h
new file mode 100644
index 0000000000000000000000000000000000000000..c22612ccc9abfd0594467ad40ad466b4559db2bc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h
@@ -0,0 +1,224 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     sici.c
+ *
+ *     Sine and cosine integrals
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, Ci, Si, sici();
+ *
+ * sici( x, &Si, &Ci );
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the integrals
+ *
+ *                          x
+ *                          -
+ *                         |  cos t - 1
+ *   Ci(x) = eul + ln x +  |  --------- dt,
+ *                         |      t
+ *                        -
+ *                         0
+ *             x
+ *             -
+ *            |  sin t
+ *   Si(x) =  |  ----- dt
+ *            |    t
+ *           -
+ *            0
+ *
+ * where eul = 0.57721566490153286061 is Euler's constant.
+ * The integrals are approximated by rational functions.
+ * For x > 8 auxiliary functions f(x) and g(x) are employed
+ * such that
+ *
+ * Ci(x) = f(x) sin(x) - g(x) cos(x)
+ * Si(x) = pi/2 - f(x) cos(x) - g(x) sin(x)
+ *
+ *
+ * ACCURACY:
+ *    Test interval = [0,50].
+ * Absolute error, except relative when > 1:
+ * arithmetic   function   # trials      peak         rms
+ *    IEEE        Si        30000       4.4e-16     7.3e-17
+ *    IEEE        Ci        30000       6.9e-16     5.1e-17
+ */
+
+/*
+ * Cephes Math Library Release 2.1:  January, 1989
+ * Copyright 1984, 1987, 1989 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double sici_SN[] = {
+            -8.39167827910303881427E-11, 4.62591714427012837309E-8,  -9.75759303843632795789E-6,
+            9.76945438170435310816E-4,   -4.13470316229406538752E-2, 1.00000000000000000302E0,
+        };
+
+        constexpr double sici_SD[] = {
+            2.03269266195951942049E-12, 1.27997891179943299903E-9, 4.41827842801218905784E-7,
+            9.96412122043875552487E-5,  1.42085239326149893930E-2, 9.99999999999999996984E-1,
+        };
+
+        constexpr double sici_CN[] = {
+            2.02524002389102268789E-11, -1.35249504915790756375E-8, 3.59325051419993077021E-6,
+            -4.74007206873407909465E-4, 2.89159652607555242092E-2,  -1.00000000000000000080E0,
+        };
+
+        constexpr double sici_CD[] = {
+            4.07746040061880559506E-12, 3.06780997581887812692E-9, 1.23210355685883423679E-6,
+            3.17442024775032769882E-4,  5.10028056236446052392E-2, 4.00000000000000000080E0,
+        };
+
+        constexpr double sici_FN4[] = {
+            4.23612862892216586994E0,  5.45937717161812843388E0,  1.62083287701538329132E0,  1.67006611831323023771E-1,
+            6.81020132472518137426E-3, 1.08936580650328664411E-4, 5.48900223421373614008E-7,
+        };
+
+        constexpr double sici_FD4[] = {
+            /*  1.00000000000000000000E0, */
+            8.16496634205391016773E0,  7.30828822505564552187E0,  1.86792257950184183883E0,  1.78792052963149907262E-1,
+            7.01710668322789753610E-3, 1.10034357153915731354E-4, 5.48900252756255700982E-7,
+        };
+
+        constexpr double sici_FN8[] = {
+            4.55880873470465315206E-1, 7.13715274100146711374E-1,  1.60300158222319456320E-1,
+            1.16064229408124407915E-2, 3.49556442447859055605E-4,  4.86215430826454749482E-6,
+            3.20092790091004902806E-8, 9.41779576128512936592E-11, 9.70507110881952024631E-14,
+        };
+
+        constexpr double sici_FD8[] = {
+            /*  1.00000000000000000000E0, */
+            9.17463611873684053703E-1,  1.78685545332074536321E-1,  1.22253594771971293032E-2,
+            3.58696481881851580297E-4,  4.92435064317881464393E-6,  3.21956939101046018377E-8,
+            9.43720590350276732376E-11, 9.70507110881952025725E-14,
+        };
+
+        constexpr double sici_GN4[] = {
+            8.71001698973114191777E-2, 6.11379109952219284151E-1, 3.97180296392337498885E-1, 7.48527737628469092119E-2,
+            5.38868681462177273157E-3, 1.61999794598934024525E-4, 1.97963874140963632189E-6, 7.82579040744090311069E-9,
+        };
+
+        constexpr double sici_GD4[] = {
+            /*  1.00000000000000000000E0, */
+            1.64402202413355338886E0,  6.66296701268987968381E-1, 9.88771761277688796203E-2, 6.22396345441768420760E-3,
+            1.73221081474177119497E-4, 2.02659182086343991969E-6, 7.82579218933534490868E-9,
+        };
+
+        constexpr double sici_GN8[] = {
+            6.97359953443276214934E-1, 3.30410979305632063225E-1,  3.84878767649974295920E-2,
+            1.71718239052347903558E-3, 3.48941165502279436777E-5,  3.47131167084116673800E-7,
+            1.70404452782044526189E-9, 3.85945925430276600453E-12, 3.14040098946363334640E-15,
+        };
+
+        constexpr double sici_GD8[] = {
+            /*  1.00000000000000000000E0, */
+            1.68548898811011640017E0,  4.87852258695304967486E-1,  4.67913194259625806320E-2,
+            1.90284426674399523638E-3, 3.68475504442561108162E-5,  3.57043223443740838771E-7,
+            1.72693748966316146736E-9, 3.87830166023954706752E-12, 3.14040098946363335242E-15,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
+        double z, c, s, f, g;
+        short sign;
+
+        if (x < 0.0) {
+            sign = -1;
+            x = -x;
+        } else {
+            sign = 0;
+        }
+
+        if (x == 0.0) {
+            *si = 0.0;
+            *ci = -std::numeric_limits::infinity();
+            return (0);
+        }
+
+        if (x > 1.0e9) {
+            if (std::isinf(x)) {
+                if (sign == -1) {
+                    *si = -M_PI_2;
+                    *ci = std::numeric_limits::quiet_NaN();
+                } else {
+                    *si = M_PI_2;
+                    *ci = 0;
+                }
+                return 0;
+            }
+            *si = M_PI_2 - std::cos(x) / x;
+            *ci = std::sin(x) / x;
+        }
+
+        if (x > 4.0) {
+            goto asympt;
+        }
+
+        z = x * x;
+        s = x * polevl(z, detail::sici_SN, 5) / polevl(z, detail::sici_SD, 5);
+        c = z * polevl(z, detail::sici_CN, 5) / polevl(z, detail::sici_CD, 5);
+
+        if (sign) {
+            s = -s;
+        }
+        *si = s;
+        *ci = detail::SCIPY_EULER + std::log(x) + c; /* real part if x < 0 */
+        return (0);
+
+        /* The auxiliary functions are:
+         *
+         *
+         * *si = *si - M_PI_2;
+         * c = cos(x);
+         * s = sin(x);
+         *
+         * t = *ci * s - *si * c;
+         * a = *ci * c + *si * s;
+         *
+         * *si = t;
+         * *ci = -a;
+         */
+
+    asympt:
+
+        s = std::sin(x);
+        c = std::cos(x);
+        z = 1.0 / (x * x);
+        if (x < 8.0) {
+            f = polevl(z, detail::sici_FN4, 6) / (x * p1evl(z, detail::sici_FD4, 7));
+            g = z * polevl(z, detail::sici_GN4, 7) / p1evl(z, detail::sici_GD4, 7);
+        } else {
+            f = polevl(z, detail::sici_FN8, 8) / (x * p1evl(z, detail::sici_FD8, 8));
+            g = z * polevl(z, detail::sici_GN8, 8) / p1evl(z, detail::sici_GD8, 9);
+        }
+        *si = M_PI_2 - f * c - g * s;
+        if (sign) {
+            *si = -(*si);
+        }
+        *ci = f * s - g * c;
+
+        return (0);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h
new file mode 100644
index 0000000000000000000000000000000000000000..63adb1698f4c6e51d971484c92b3cf2c98dcba6f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h
@@ -0,0 +1,221 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     sindg.c
+ *
+ *     Circular sine of angle in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, sindg();
+ *
+ * y = sindg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Range reduction is into intervals of 45 degrees.
+ *
+ * Two polynomial approximating functions are employed.
+ * Between 0 and pi/4 the sine is approximated by
+ *      x  +  x**3 P(x**2).
+ * Between pi/4 and pi/2 the cosine is represented as
+ *      1  -  x**2 P(x**2).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      +-1000       30000      2.3e-16      5.6e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message           condition        value returned
+ * sindg total loss   x > 1.0e14 (IEEE)     0.0
+ *
+ */
+/*							cosdg.c
+ *
+ *	Circular cosine of angle in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cosdg();
+ *
+ * y = cosdg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Range reduction is into intervals of 45 degrees.
+ *
+ * Two polynomial approximating functions are employed.
+ * Between 0 and pi/4 the cosine is approximated by
+ *      1  -  x**2 P(x**2).
+ * Between pi/4 and pi/2 the sine is represented as
+ *      x  +  x**3 P(x**2).
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE     +-1000        30000       2.1e-16     5.7e-17
+ *  See also sin().
+ *
+ */
+
+/* Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double sincof[] = {1.58962301572218447952E-10, -2.50507477628503540135E-8,
+                                     2.75573136213856773549E-6,  -1.98412698295895384658E-4,
+                                     8.33333333332211858862E-3,  -1.66666666666666307295E-1};
+
+        constexpr double coscof[] = {1.13678171382044553091E-11, -2.08758833757683644217E-9, 2.75573155429816611547E-7,
+                                     -2.48015872936186303776E-5, 1.38888888888806666760E-3,  -4.16666666666666348141E-2,
+                                     4.99999999999999999798E-1};
+
+        constexpr double sindg_lossth = 1.0e14;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double sindg(double x) {
+        double y, z, zz;
+        int j, sign;
+
+        /* make argument positive but save the sign */
+        sign = 1;
+        if (x < 0) {
+            x = -x;
+            sign = -1;
+        }
+
+        if (x > detail::sindg_lossth) {
+            set_error("sindg", SF_ERROR_NO_RESULT, NULL);
+            return (0.0);
+        }
+
+        y = std::floor(x / 45.0); /* integer part of x/M_PI_4 */
+
+        /* strip high bits of integer part to prevent integer overflow */
+        z = std::ldexp(y, -4);
+        z = std::floor(z);        /* integer part of y/8 */
+        z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */
+
+        j = z; /* convert to integer for tests on the phase angle */
+        /* map zeros to origin */
+        if (j & 1) {
+            j += 1;
+            y += 1.0;
+        }
+        j = j & 07; /* octant modulo 360 degrees */
+        /* reflect in x axis */
+        if (j > 3) {
+            sign = -sign;
+            j -= 4;
+        }
+
+        z = x - y * 45.0;   /* x mod 45 degrees */
+        z *= detail::PI180; /* multiply by pi/180 to convert to radians */
+        zz = z * z;
+
+        if ((j == 1) || (j == 2)) {
+            y = 1.0 - zz * polevl(zz, detail::coscof, 6);
+        } else {
+            y = z + z * (zz * polevl(zz, detail::sincof, 5));
+        }
+
+        if (sign < 0)
+            y = -y;
+
+        return (y);
+    }
+
+    XSF_HOST_DEVICE inline double cosdg(double x) {
+        double y, z, zz;
+        int j, sign;
+
+        /* make argument positive */
+        sign = 1;
+        if (x < 0)
+            x = -x;
+
+        if (x > detail::sindg_lossth) {
+            set_error("cosdg", SF_ERROR_NO_RESULT, NULL);
+            return (0.0);
+        }
+
+        y = std::floor(x / 45.0);
+        z = std::ldexp(y, -4);
+        z = std::floor(z);        /* integer part of y/8 */
+        z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */
+
+        /* integer and fractional part modulo one octant */
+        j = z;
+        if (j & 1) { /* map zeros to origin */
+            j += 1;
+            y += 1.0;
+        }
+        j = j & 07;
+        if (j > 3) {
+            j -= 4;
+            sign = -sign;
+        }
+
+        if (j > 1)
+            sign = -sign;
+
+        z = x - y * 45.0;   /* x mod 45 degrees */
+        z *= detail::PI180; /* multiply by pi/180 to convert to radians */
+
+        zz = z * z;
+
+        if ((j == 1) || (j == 2)) {
+            y = z + z * (zz * polevl(zz, detail::sincof, 5));
+        } else {
+            y = 1.0 - zz * polevl(zz, detail::coscof, 6);
+        }
+
+        if (sign < 0)
+            y = -y;
+
+        return (y);
+    }
+
+    /* Degrees, minutes, seconds to radians: */
+
+    /* 1 arc second, in radians = 4.848136811095359935899141023579479759563533023727e-6 */
+
+    namespace detail {
+        constexpr double sindg_P64800 = 4.848136811095359935899141023579479759563533023727e-6;
+    }
+
+    XSF_HOST_DEVICE inline double radian(double d, double m, double s) {
+        return (((d * 60.0 + m) * 60.0 + s) * detail::sindg_P64800);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h
new file mode 100644
index 0000000000000000000000000000000000000000..071b1a81d8bd5467fabf99fa54881f5862c0218b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h
@@ -0,0 +1,139 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     tandg.c
+ *
+ *     Circular tangent of argument in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, tandg();
+ *
+ * y = tandg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the circular tangent of the argument x in degrees.
+ *
+ * Range reduction is modulo pi/4.  A rational function
+ *       x + x**3 P(x**2)/Q(x**2)
+ * is employed in the basic interval [0, pi/4].
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     0,10         30000      3.2e-16      8.4e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * tandg total loss   x > 1.0e14 (IEEE)     0.0
+ * tandg singularity  x = 180 k  +  90     INFINITY
+ */
+/*							cotdg.c
+ *
+ *	Circular cotangent of argument in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cotdg();
+ *
+ * y = cotdg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the circular cotangent of the argument x in degrees.
+ *
+ * Range reduction is modulo pi/4.  A rational function
+ *       x + x**3 P(x**2)/Q(x**2)
+ * is employed in the basic interval [0, pi/4].
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * cotdg total loss   x > 1.0e14 (IEEE)     0.0
+ * cotdg singularity  x = 180 k            INFINITY
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double tandg_lossth = 1.0e14;
+
+        XSF_HOST_DEVICE inline double tancot(double xx, int cotflg) {
+            double x;
+            int sign;
+
+            /* make argument positive but save the sign */
+            if (xx < 0) {
+                x = -xx;
+                sign = -1;
+            } else {
+                x = xx;
+                sign = 1;
+            }
+
+            if (x > detail::tandg_lossth) {
+                set_error("tandg", SF_ERROR_NO_RESULT, NULL);
+                return 0.0;
+            }
+
+            /* modulo 180 */
+            x = x - 180.0 * std::floor(x / 180.0);
+            if (cotflg) {
+                if (x <= 90.0) {
+                    x = 90.0 - x;
+                } else {
+                    x = x - 90.0;
+                    sign *= -1;
+                }
+            } else {
+                if (x > 90.0) {
+                    x = 180.0 - x;
+                    sign *= -1;
+                }
+            }
+            if (x == 0.0) {
+                return 0.0;
+            } else if (x == 45.0) {
+                return sign * 1.0;
+            } else if (x == 90.0) {
+                set_error((cotflg ? "cotdg" : "tandg"), SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            }
+            /* x is now transformed into [0, 90) */
+            return sign * std::tan(x * detail::PI180);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double tandg(double x) { return (detail::tancot(x, 0)); }
+
+    XSF_HOST_DEVICE inline double cotdg(double x) { return (detail::tancot(x, 1)); }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h
new file mode 100644
index 0000000000000000000000000000000000000000..47dcdbe6ab3c72e91dcd13f7f432572260ca3c62
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h
@@ -0,0 +1,58 @@
+/* Translated into C++ by SciPy developers in 2024.
+ *
+ * Original author: Josh Wilson, 2020.
+ */
+
+/*
+ * Implement sin(pi * x) and cos(pi * x) for real x. Since the periods
+ * of these functions are integral (and thus representable in double
+ * precision), it's possible to compute them with greater accuracy
+ * than sin(x) and cos(x).
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    /* Compute sin(pi * x). */
+    template 
+    XSF_HOST_DEVICE T sinpi(T x) {
+        T s = 1.0;
+
+        if (x < 0.0) {
+            x = -x;
+            s = -1.0;
+        }
+
+        T r = std::fmod(x, 2.0);
+        if (r < 0.5) {
+            return s * std::sin(M_PI * r);
+        } else if (r > 1.5) {
+            return s * std::sin(M_PI * (r - 2.0));
+        } else {
+            return -s * std::sin(M_PI * (r - 1.0));
+        }
+    }
+
+    /* Compute cos(pi * x) */
+    template 
+    XSF_HOST_DEVICE T cospi(T x) {
+        if (x < 0.0) {
+            x = -x;
+        }
+
+        T r = std::fmod(x, 2.0);
+        if (r == 0.5) {
+            // We don't want to return -0.0
+            return 0.0;
+        }
+        if (r < 1.0) {
+            return -std::sin(M_PI * (r - 0.5));
+        } else {
+            return std::sin(M_PI * (r - 1.5));
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h
new file mode 100644
index 0000000000000000000000000000000000000000..eb045edda2122e206fc866b180c1fbd71670a553
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h
@@ -0,0 +1,186 @@
+/* Translated into C++ by SciPy developers in 2024. */
+
+/*                                                     unity.c
+ *
+ * Relative error approximations for function arguments near
+ * unity.
+ *
+ *    log1p(x) = log(1+x)
+ *    expm1(x) = exp(x) - 1
+ *    cosm1(x) = cos(x) - 1
+ *    lgam1p(x) = lgam(1+x)
+ *
+ */
+
+/* Scipy changes:
+ * - 06-10-2016: added lgam1p
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "polevl.h"
+#include "zeta.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* log1p(x) = log(1 + x)  */
+
+        /* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x)
+         * 1/sqrt(2) <= x < sqrt(2)
+         * Theoretical peak relative error = 2.32e-20
+         */
+
+        constexpr double unity_LP[] = {
+            4.5270000862445199635215E-5, 4.9854102823193375972212E-1, 6.5787325942061044846969E0,
+            2.9911919328553073277375E1,  6.0949667980987787057556E1,  5.7112963590585538103336E1,
+            2.0039553499201281259648E1,
+        };
+
+        constexpr double unity_LQ[] = {
+            /* 1.0000000000000000000000E0, */
+            1.5062909083469192043167E1, 8.3047565967967209469434E1, 2.2176239823732856465394E2,
+            3.0909872225312059774938E2, 2.1642788614495947685003E2, 6.0118660497603843919306E1,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double log1p(double x) {
+        double z;
+
+        z = 1.0 + x;
+        if ((z < M_SQRT1_2) || (z > M_SQRT2))
+            return (std::log(z));
+        z = x * x;
+        z = -0.5 * z + x * (z * polevl(x, detail::unity_LP, 6) / p1evl(x, detail::unity_LQ, 6));
+        return (x + z);
+    }
+
+    /* log(1 + x) - x */
+    XSF_HOST_DEVICE inline double log1pmx(double x) {
+        if (std::abs(x) < 0.5) {
+            uint64_t n;
+            double xfac = x;
+            double term;
+            double res = 0;
+
+            for (n = 2; n < detail::MAXITER; n++) {
+                xfac *= -x;
+                term = xfac / n;
+                res += term;
+                if (std::abs(term) < detail::MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+            return res;
+        } else {
+            return log1p(x) - x;
+        }
+    }
+
+    /* expm1(x) = exp(x) - 1  */
+
+    /*  e^x =  1 + 2x P(x^2)/( Q(x^2) - P(x^2) )
+     * -0.5 <= x <= 0.5
+     */
+
+    namespace detail {
+
+        constexpr double unity_EP[3] = {
+            1.2617719307481059087798E-4,
+            3.0299440770744196129956E-2,
+            9.9999999999999999991025E-1,
+        };
+
+        constexpr double unity_EQ[4] = {
+            3.0019850513866445504159E-6,
+            2.5244834034968410419224E-3,
+            2.2726554820815502876593E-1,
+            2.0000000000000000000897E0,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double expm1(double x) {
+        double r, xx;
+
+        if (!std::isfinite(x)) {
+            if (std::isnan(x)) {
+                return x;
+            } else if (x > 0) {
+                return x;
+            } else {
+                return -1.0;
+            }
+        }
+        if ((x < -0.5) || (x > 0.5))
+            return (std::exp(x) - 1.0);
+        xx = x * x;
+        r = x * polevl(xx, detail::unity_EP, 2);
+        r = r / (polevl(xx, detail::unity_EQ, 3) - r);
+        return (r + r);
+    }
+
+    /* cosm1(x) = cos(x) - 1  */
+
+    namespace detail {
+        constexpr double unity_coscof[7] = {
+            4.7377507964246204691685E-14, -1.1470284843425359765671E-11, 2.0876754287081521758361E-9,
+            -2.7557319214999787979814E-7, 2.4801587301570552304991E-5,   -1.3888888888888872993737E-3,
+            4.1666666666666666609054E-2,
+        };
+
+    }
+
+    XSF_HOST_DEVICE inline double cosm1(double x) {
+        double xx;
+
+        if ((x < -M_PI_4) || (x > M_PI_4))
+            return (std::cos(x) - 1.0);
+        xx = x * x;
+        xx = -0.5 * xx + xx * xx * polevl(xx, detail::unity_coscof, 6);
+        return xx;
+    }
+
+    namespace detail {
+        /* Compute lgam(x + 1) around x = 0 using its Taylor series. */
+        XSF_HOST_DEVICE inline double lgam1p_taylor(double x) {
+            int n;
+            double xfac, coeff, res;
+
+            if (x == 0) {
+                return 0;
+            }
+            res = -SCIPY_EULER * x;
+            xfac = -x;
+            for (n = 2; n < 42; n++) {
+                xfac *= -x;
+                coeff = xsf::cephes::zeta(n, 1) * xfac / n;
+                res += coeff;
+                if (std::abs(coeff) < detail::MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+
+            return res;
+        }
+    } // namespace detail
+
+    /* Compute lgam(x + 1). */
+    XSF_HOST_DEVICE inline double lgam1p(double x) {
+        if (std::abs(x) <= 0.5) {
+            return detail::lgam1p_taylor(x);
+        } else if (std::abs(x - 1) < 0.5) {
+            return std::log(x) + detail::lgam1p_taylor(x - 1);
+        } else {
+            return lgam(x + 1);
+        }
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h
new file mode 100644
index 0000000000000000000000000000000000000000..6f9d68e0bdced0edf70c17cdacf9a676341a908a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h
@@ -0,0 +1,172 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     zeta.c
+ *
+ *     Riemann zeta function of two arguments
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, q, y, zeta();
+ *
+ * y = zeta( x, q );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *
+ *                 inf.
+ *                  -        -x
+ *   zeta(x,q)  =   >   (k+q)
+ *                  -
+ *                 k=0
+ *
+ * where x > 1 and q is not a negative integer or zero.
+ * The Euler-Maclaurin summation formula is used to obtain
+ * the expansion
+ *
+ *                n
+ *                -       -x
+ * zeta(x,q)  =   >  (k+q)
+ *                -
+ *               k=1
+ *
+ *           1-x                 inf.  B   x(x+1)...(x+2j)
+ *      (n+q)           1         -     2j
+ *  +  ---------  -  -------  +   >    --------------------
+ *        x-1              x      -                   x+2j+1
+ *                   2(n+q)      j=1       (2j)! (n+q)
+ *
+ * where the B2j are Bernoulli numbers.  Note that (see zetac.c)
+ * zeta(x,1) = zetac(x) + 1.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *
+ *
+ * REFERENCE:
+ *
+ * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals,
+ * Series, and Products, p. 1073; Academic Press, 1980.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Expansion coefficients
+         * for Euler-Maclaurin summation formula
+         * (2k)! / B2k
+         * where B2k are Bernoulli numbers
+         */
+        constexpr double zeta_A[] = {
+            12.0,
+            -720.0,
+            30240.0,
+            -1209600.0,
+            47900160.0,
+            -1.8924375803183791606e9, /*1.307674368e12/691 */
+            7.47242496e10,
+            -2.950130727918164224e12,  /*1.067062284288e16/3617 */
+            1.1646782814350067249e14,  /*5.109094217170944e18/43867 */
+            -4.5979787224074726105e15, /*8.028576626982912e20/174611 */
+            1.8152105401943546773e17,  /*1.5511210043330985984e23/854513 */
+            -7.1661652561756670113e18  /*1.6938241367317436694528e27/236364091 */
+        };
+
+        /* 30 Nov 86 -- error in third coefficient fixed */
+    } // namespace detail
+
+    XSF_HOST_DEVICE double inline zeta(double x, double q) {
+        int i;
+        double a, b, k, s, t, w;
+
+        if (x == 1.0)
+            goto retinf;
+
+        if (x < 1.0) {
+        domerr:
+            set_error("zeta", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        if (q <= 0.0) {
+            if (q == floor(q)) {
+                set_error("zeta", SF_ERROR_SINGULAR, NULL);
+            retinf:
+                return (std::numeric_limits::infinity());
+            }
+            if (x != std::floor(x))
+                goto domerr; /* because q^-x not defined */
+        }
+
+        /* Asymptotic expansion
+         * https://dlmf.nist.gov/25.11#E43
+         */
+        if (q > 1e8) {
+            return (1 / (x - 1) + 1 / (2 * q)) * std::pow(q, 1 - x);
+        }
+
+        /* Euler-Maclaurin summation formula */
+
+        /* Permit negative q but continue sum until n+q > +9 .
+         * This case should be handled by a reflection formula.
+         * If q<0 and x is an integer, there is a relation to
+         * the polyGamma function.
+         */
+        s = std::pow(q, -x);
+        a = q;
+        i = 0;
+        b = 0.0;
+        while ((i < 9) || (a <= 9.0)) {
+            i += 1;
+            a += 1.0;
+            b = std::pow(a, -x);
+            s += b;
+            if (std::abs(b / s) < detail::MACHEP)
+                goto done;
+        }
+
+        w = a;
+        s += b * w / (x - 1.0);
+        s -= 0.5 * b;
+        a = 1.0;
+        k = 0.0;
+        for (i = 0; i < 12; i++) {
+            a *= x + k;
+            b /= w;
+            t = a * b / detail::zeta_A[i];
+            s = s + t;
+            t = std::abs(t / s);
+            if (t < detail::MACHEP)
+                goto done;
+            k += 1.0;
+            a *= x + k;
+            b /= w;
+            k += 1.0;
+        }
+    done:
+        return (s);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/config.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..5cb40ed1e1e095a8c99414f891a697c263845784
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/config.h
@@ -0,0 +1,304 @@
+#pragma once
+
+// Define math constants if they are not available
+#ifndef M_E
+#define M_E 2.71828182845904523536
+#endif
+
+#ifndef M_LOG2E
+#define M_LOG2E 1.44269504088896340736
+#endif
+
+#ifndef M_LOG10E
+#define M_LOG10E 0.434294481903251827651
+#endif
+
+#ifndef M_LN2
+#define M_LN2 0.693147180559945309417
+#endif
+
+#ifndef M_LN10
+#define M_LN10 2.30258509299404568402
+#endif
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+#ifndef M_PI_2
+#define M_PI_2 1.57079632679489661923
+#endif
+
+#ifndef M_PI_4
+#define M_PI_4 0.785398163397448309616
+#endif
+
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
+
+#ifndef M_2_PI
+#define M_2_PI 0.636619772367581343076
+#endif
+
+#ifndef M_2_SQRTPI
+#define M_2_SQRTPI 1.12837916709551257390
+#endif
+
+#ifndef M_SQRT2
+#define M_SQRT2 1.41421356237309504880
+#endif
+
+#ifndef M_SQRT1_2
+#define M_SQRT1_2 0.707106781186547524401
+#endif
+
+#ifdef __CUDACC__
+#define XSF_HOST_DEVICE __host__ __device__
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// Fallback to global namespace for functions unsupported on NVRTC Jit
+#ifdef _LIBCUDACXX_COMPILER_NVRTC
+#include 
+#endif
+
+namespace std {
+
+XSF_HOST_DEVICE inline double abs(double num) { return cuda::std::abs(num); }
+
+XSF_HOST_DEVICE inline double exp(double num) { return cuda::std::exp(num); }
+
+XSF_HOST_DEVICE inline double log(double num) { return cuda::std::log(num); }
+
+XSF_HOST_DEVICE inline double sqrt(double num) { return cuda::std::sqrt(num); }
+
+XSF_HOST_DEVICE inline bool isinf(double num) { return cuda::std::isinf(num); }
+
+XSF_HOST_DEVICE inline bool isnan(double num) { return cuda::std::isnan(num); }
+
+XSF_HOST_DEVICE inline bool isfinite(double num) { return cuda::std::isfinite(num); }
+
+XSF_HOST_DEVICE inline double pow(double x, double y) { return cuda::std::pow(x, y); }
+
+XSF_HOST_DEVICE inline double sin(double x) { return cuda::std::sin(x); }
+
+XSF_HOST_DEVICE inline double cos(double x) { return cuda::std::cos(x); }
+
+XSF_HOST_DEVICE inline double tan(double x) { return cuda::std::tan(x); }
+
+XSF_HOST_DEVICE inline double atan(double x) { return cuda::std::atan(x); }
+
+XSF_HOST_DEVICE inline double acos(double x) { return cuda::std::acos(x); }
+
+XSF_HOST_DEVICE inline double sinh(double x) { return cuda::std::sinh(x); }
+
+XSF_HOST_DEVICE inline double cosh(double x) { return cuda::std::cosh(x); }
+
+XSF_HOST_DEVICE inline double asinh(double x) { return cuda::std::asinh(x); }
+
+XSF_HOST_DEVICE inline bool signbit(double x) { return cuda::std::signbit(x); }
+
+// Fallback to global namespace for functions unsupported on NVRTC
+#ifndef _LIBCUDACXX_COMPILER_NVRTC
+XSF_HOST_DEVICE inline double ceil(double x) { return cuda::std::ceil(x); }
+XSF_HOST_DEVICE inline double floor(double x) { return cuda::std::floor(x); }
+XSF_HOST_DEVICE inline double round(double x) { return cuda::std::round(x); }
+XSF_HOST_DEVICE inline double trunc(double x) { return cuda::std::trunc(x); }
+XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return cuda::std::fma(x, y, z); }
+XSF_HOST_DEVICE inline double copysign(double x, double y) { return cuda::std::copysign(x, y); }
+XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return cuda::std::modf(value, iptr); }
+XSF_HOST_DEVICE inline double fmax(double x, double y) { return cuda::std::fmax(x, y); }
+XSF_HOST_DEVICE inline double fmin(double x, double y) { return cuda::std::fmin(x, y); }
+XSF_HOST_DEVICE inline double log10(double num) { return cuda::std::log10(num); }
+XSF_HOST_DEVICE inline double log1p(double num) { return cuda::std::log1p(num); }
+XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return cuda::std::frexp(num, exp); }
+XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return cuda::std::ldexp(num, exp); }
+XSF_HOST_DEVICE inline double fmod(double x, double y) { return cuda::std::fmod(x, y); }
+XSF_HOST_DEVICE inline double nextafter(double from, double to) { return cuda::std::nextafter(from, to); }
+#else
+XSF_HOST_DEVICE inline double ceil(double x) { return ::ceil(x); }
+XSF_HOST_DEVICE inline double floor(double x) { return ::floor(x); }
+XSF_HOST_DEVICE inline double round(double x) { return ::round(x); }
+XSF_HOST_DEVICE inline double trunc(double x) { return ::trunc(x); }
+XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return ::fma(x, y, z); }
+XSF_HOST_DEVICE inline double copysign(double x, double y) { return ::copysign(x, y); }
+XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return ::modf(value, iptr); }
+XSF_HOST_DEVICE inline double fmax(double x, double y) { return ::fmax(x, y); }
+XSF_HOST_DEVICE inline double fmin(double x, double y) { return ::fmin(x, y); }
+XSF_HOST_DEVICE inline double log10(double num) { return ::log10(num); }
+XSF_HOST_DEVICE inline double log1p(double num) { return ::log1p(num); }
+XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return ::frexp(num, exp); }
+XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return ::ldexp(num, exp); }
+XSF_HOST_DEVICE inline double fmod(double x, double y) { return ::fmod(x, y); }
+XSF_HOST_DEVICE inline double nextafter(double from, double to) { return ::nextafter(from, to); }
+#endif
+
+template 
+XSF_HOST_DEVICE void swap(T &a, T &b) {
+    cuda::std::swap(a, b);
+}
+
+// Reimplement std::clamp until it's available in CuPy
+template 
+XSF_HOST_DEVICE constexpr T clamp(T &v, T &lo, T &hi) {
+    return v < lo ? lo : (v > hi ? lo : v);
+}
+
+template 
+using numeric_limits = cuda::std::numeric_limits;
+
+// Must use thrust for complex types in order to support CuPy
+template 
+using complex = thrust::complex;
+
+template 
+XSF_HOST_DEVICE T abs(const complex &z) {
+    return thrust::abs(z);
+}
+
+template 
+XSF_HOST_DEVICE complex exp(const complex &z) {
+    return thrust::exp(z);
+}
+
+template 
+XSF_HOST_DEVICE complex log(const complex &z) {
+    return thrust::log(z);
+}
+
+template 
+XSF_HOST_DEVICE T norm(const complex &z) {
+    return thrust::norm(z);
+}
+
+template 
+XSF_HOST_DEVICE complex sqrt(const complex &z) {
+    return thrust::sqrt(z);
+}
+
+template 
+XSF_HOST_DEVICE complex conj(const complex &z) {
+    return thrust::conj(z);
+}
+
+template 
+XSF_HOST_DEVICE complex pow(const complex &x, const complex &y) {
+    return thrust::pow(x, y);
+}
+
+template 
+XSF_HOST_DEVICE complex pow(const complex &x, const T &y) {
+    return thrust::pow(x, y);
+}
+
+// Other types and utilities
+template 
+using is_floating_point = cuda::std::is_floating_point;
+
+template 
+using enable_if = cuda::std::enable_if;
+
+template 
+using decay = cuda::std::decay;
+
+template 
+using invoke_result = cuda::std::invoke_result;
+
+template 
+using pair = cuda::std::pair;
+
+template 
+using tuple = cuda::std::tuple;
+
+using cuda::std::ptrdiff_t;
+using cuda::std::size_t;
+using cuda::std::uint64_t;
+
+#define XSF_ASSERT(a)
+
+} // namespace std
+
+#else
+#define XSF_HOST_DEVICE
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef DEBUG
+#define XSF_ASSERT(a) assert(a)
+#else
+#define XSF_ASSERT(a)
+#endif
+
+namespace xsf {
+
+// basic
+using std::abs;
+
+// exponential
+using std::exp;
+
+// power
+using std::sqrt;
+
+// trigonometric
+using std::cos;
+using std::sin;
+
+// floating-point manipulation
+using std::copysign;
+
+// classification and comparison
+using std::isfinite;
+using std::isinf;
+using std::isnan;
+using std::signbit;
+
+// complex
+using std::imag;
+using std::real;
+
+template 
+struct remove_complex {
+    using type = T;
+};
+
+template 
+struct remove_complex> {
+    using type = T;
+};
+
+template 
+using remove_complex_t = typename remove_complex::type;
+
+template 
+struct complex_type {
+    using type = std::complex;
+};
+
+template 
+using complex_type_t = typename complex_type::type;
+
+template 
+using complex = complex_type_t;
+
+} // namespace xsf
+
+#endif
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..db51362ce03907ee7c86c0995836e6d5d18160c6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h
@@ -0,0 +1,205 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header comment appears below.
+ */
+
+/* An implementation of the digamma function for complex arguments.
+ *
+ * Author: Josh Wilson
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * Sources:
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ *
+ * [2] mpmath (version 0.19), http://mpmath.org
+ */
+
+#pragma once
+
+#include "cephes/psi.h"
+#include "cephes/zeta.h"
+#include "config.h"
+#include "error.h"
+#include "trig.h"
+
+namespace xsf {
+namespace detail {
+    // All of the following were computed with mpmath
+    // Location of the positive root
+    constexpr double digamma_posroot = 1.4616321449683623;
+    // Value of the positive root
+    constexpr double digamma_posrootval = -9.2412655217294275e-17;
+    // Location of the negative root
+    constexpr double digamma_negroot = -0.504083008264455409;
+    // Value of the negative root
+    constexpr double digamma_negrootval = 7.2897639029768949e-17;
+
+    template 
+    XSF_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) {
+        T res = rootval;
+        T coeff = -1.0;
+
+        z = z - root;
+        T term;
+        for (int n = 1; n < 100; n++) {
+            coeff *= -z;
+            term = coeff * cephes::zeta(n + 1, root);
+            res += term;
+            if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) {
+                break;
+            }
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex
+    digamma_forward_recurrence(std::complex z, std::complex psiz, int n) {
+        /* Compute digamma(z + n) using digamma(z) using the recurrence
+         * relation
+         *
+         * digamma(z + 1) = digamma(z) + 1/z.
+         *
+         * See https://dlmf.nist.gov/5.5#E2 */
+        std::complex res = psiz;
+
+        for (int k = 0; k < n; k++) {
+            res += 1.0 / (z + static_cast(k));
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex
+    digamma_backward_recurrence(std::complex z, std::complex psiz, int n) {
+        /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */
+        std::complex res = psiz;
+
+        for (int k = 1; k < n + 1; k++) {
+            res -= 1.0 / (z - static_cast(k));
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex digamma_asymptotic_series(std::complex z) {
+        /* Evaluate digamma using an asymptotic series. See
+         *
+         * https://dlmf.nist.gov/5.11#E2 */
+        double bernoulli2k[] = {0.166666666666666667,   -0.0333333333333333333, 0.0238095238095238095,
+                                -0.0333333333333333333, 0.0757575757575757576,  -0.253113553113553114,
+                                1.16666666666666667,    -7.09215686274509804,   54.9711779448621554,
+                                -529.124242424242424,   6192.12318840579710,    -86580.2531135531136,
+                                1425517.16666666667,    -27298231.0678160920,   601580873.900642368,
+                                -15116315767.0921569};
+        std::complex rzz = 1.0 / z / z;
+        std::complex zfac = 1.0;
+        std::complex term;
+        std::complex res;
+
+        if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) {
+            /* Check for infinity (or nan) and return early.
+             * Result of division by complex infinity is implementation dependent.
+             * and has been observed to vary between C++ stdlib and CUDA stdlib.
+             */
+            return std::log(z);
+        }
+
+        res = std::log(z) - 0.5 / z;
+
+        for (int k = 1; k < 17; k++) {
+            zfac *= rzz;
+            term = -bernoulli2k[k - 1] * zfac / (2 * static_cast(k));
+            res += term;
+            if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) {
+                break;
+            }
+        }
+        return res;
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline double digamma(double z) {
+    /* Wrap Cephes' psi to take advantage of the series expansion around
+     * the smallest negative zero.
+     */
+    if (std::abs(z - detail::digamma_negroot) < 0.3) {
+        return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
+    }
+    return cephes::psi(z);
+}
+
+XSF_HOST_DEVICE inline float digamma(float z) { return static_cast(digamma(static_cast(z))); }
+
+XSF_HOST_DEVICE inline std::complex digamma(std::complex z) {
+    /*
+     * Compute the digamma function for complex arguments. The strategy
+     * is:
+     *
+     * - Around the two zeros closest to the origin (posroot and negroot)
+     * use a Taylor series with precomputed zero order coefficient.
+     * - If close to the origin, use a recurrence relation to step away
+     * from the origin.
+     * - If close to the negative real axis, use the reflection formula
+     * to move to the right halfplane.
+     * - If |z| is large (> 16), use the asymptotic series.
+     * - If |z| is small, use a recurrence relation to make |z| large
+     * enough to use the asymptotic series.
+     */
+    double absz = std::abs(z);
+    std::complex res = 0;
+    /* Use the asymptotic series for z away from the negative real axis
+     * with abs(z) > smallabsz. */
+    int smallabsz = 16;
+    /* Use the reflection principle for z with z.real < 0 that are within
+     * smallimag of the negative real axis.
+     * int smallimag = 6  # unused below except in a comment */
+
+    if (z.real() <= 0.0 && std::ceil(z.real()) == z) {
+        // Poles
+        set_error("digamma", SF_ERROR_SINGULAR, NULL);
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (std::abs(z - detail::digamma_negroot) < 0.3) {
+        // First negative root.
+        return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
+    }
+
+    if (z.real() < 0 and std::abs(z.imag()) < smallabsz) {
+        /* Reflection formula for digamma. See
+         *
+         *https://dlmf.nist.gov/5.5#E4
+         */
+        res = -M_PI * cospi(z) / sinpi(z);
+        z = 1.0 - z;
+        absz = std::abs(z);
+    }
+
+    if (absz < 0.5) {
+        /* Use one step of the recurrence relation to step away from
+         * the pole. */
+        res = -1.0 / z;
+        z += 1.0;
+        absz = std::abs(z);
+    }
+
+    if (std::abs(z - detail::digamma_posroot) < 0.5) {
+        res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval);
+    } else if (absz > smallabsz) {
+        res += detail::digamma_asymptotic_series(z);
+    } else if (z.real() >= 0.0) {
+        double n = std::trunc(smallabsz - absz) + 1;
+        std::complex init = detail::digamma_asymptotic_series(z + n);
+        res += detail::digamma_backward_recurrence(z + n, init, n);
+    } else {
+        // z.real() < 0, absz < smallabsz, and z.imag() > smallimag
+        double n = std::trunc(smallabsz - absz) - 1;
+        std::complex init = detail::digamma_asymptotic_series(z - n);
+        res += detail::digamma_forward_recurrence(z - n, init, n);
+    }
+    return res;
+}
+
+XSF_HOST_DEVICE inline std::complex digamma(std::complex z) {
+    return static_cast>(digamma(static_cast>(z)));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/error.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/error.h
new file mode 100644
index 0000000000000000000000000000000000000000..7221b5e6c4051b82f80dfb360f9fab896be6a6bd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/error.h
@@ -0,0 +1,57 @@
+#pragma once
+
+typedef enum {
+    SF_ERROR_OK = 0,    /* no error */
+    SF_ERROR_SINGULAR,  /* singularity encountered */
+    SF_ERROR_UNDERFLOW, /* floating point underflow */
+    SF_ERROR_OVERFLOW,  /* floating point overflow */
+    SF_ERROR_SLOW,      /* too many iterations required */
+    SF_ERROR_LOSS,      /* loss of precision */
+    SF_ERROR_NO_RESULT, /* no result obtained */
+    SF_ERROR_DOMAIN,    /* out of domain */
+    SF_ERROR_ARG,       /* invalid input parameter */
+    SF_ERROR_OTHER,     /* unclassified error */
+    SF_ERROR_MEMORY,    /* memory allocation failed */
+    SF_ERROR__LAST
+} sf_error_t;
+
+#ifdef __cplusplus
+
+#include "config.h"
+
+namespace xsf {
+
+#ifndef SP_SPECFUN_ERROR
+XSF_HOST_DEVICE inline void set_error(const char *func_name, sf_error_t code, const char *fmt, ...) {
+    // nothing
+}
+#else
+void set_error(const char *func_name, sf_error_t code, const char *fmt, ...);
+#endif
+
+template 
+XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, T &value) {
+    if (code != SF_ERROR_OK) {
+        set_error(name, code, nullptr);
+
+        if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) {
+            value = std::numeric_limits::quiet_NaN();
+        }
+    }
+}
+
+template 
+XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, std::complex &value) {
+    if (code != SF_ERROR_OK) {
+        set_error(name, code, nullptr);
+
+        if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) {
+            value.real(std::numeric_limits::quiet_NaN());
+            value.imag(std::numeric_limits::quiet_NaN());
+        }
+    }
+}
+
+} // namespace xsf
+
+#endif
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h
new file mode 100644
index 0000000000000000000000000000000000000000..b126fb608fae47620431e05cea21ac66e6847e59
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h
@@ -0,0 +1,47 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+/* Evaluate polynomials.
+ *
+ * All of the coefficients are stored in reverse order, i.e. if the
+ * polynomial is
+ *
+ *     u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0,
+ *
+ * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0.
+ *
+ * References
+ * ----------
+ * [1] Knuth, "The Art of Computer Programming, Volume II"
+ */
+
+#pragma once
+
+#include "config.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline std::complex cevalpoly(const double *coeffs, int degree, std::complex z) {
+    /* Evaluate a polynomial with real coefficients at a complex point.
+     *
+     * Uses equation (3) in section 4.6.4 of [1]. Note that it is more
+     * efficient than Horner's method.
+     */
+    double a = coeffs[0];
+    double b = coeffs[1];
+    double r = 2 * z.real();
+    double s = std::norm(z);
+    double tmp;
+
+    for (int j = 2; j < degree + 1; j++) {
+        tmp = b;
+        b = std::fma(-s, a, coeffs[j]);
+        a = std::fma(r, a, tmp);
+    }
+
+    return z * a + b;
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h
new file mode 100644
index 0000000000000000000000000000000000000000..600448aeb7f7a525aef76d4c59c31fa2489bcb1d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h
@@ -0,0 +1,266 @@
+/* The functions exp1, expi below are based on translations of the Fortran code
+ * by Shanjie Zhang and Jianming Jin from the book
+ *
+ *  Shanjie Zhang, Jianming Jin,
+ *  Computation of Special Functions,
+ *  Wiley, 1996,
+ *  ISBN: 0-471-11963-6,
+ *  LC: QA351.C45.
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+#include "cephes/const.h"
+
+
+namespace xsf {
+
+
+XSF_HOST_DEVICE inline double exp1(double x) {
+    // ============================================
+    // Purpose: Compute exponential integral E1(x)
+    // Input :  x  --- Argument of E1(x)
+    // Output:  E1 --- E1(x)  ( x > 0 )
+    // ============================================
+    int k, m;
+    double e1, r, t, t0;
+    constexpr double ga = cephes::detail::SCIPY_EULER;
+
+    if (x == 0.0) {
+	return std::numeric_limits::infinity();
+    }
+    if (x <= 1.0) {
+        e1 = 1.0;
+        r = 1.0;
+        for (k = 1; k < 26; k++) {
+            r = -r*k*x/std::pow(k+1.0, 2);
+            e1 += r;
+            if (std::abs(r) <= std::abs(e1)*1e-15) { break; }
+        }
+        return -ga - std::log(x) + x*e1;
+    }
+    m = 20 + (int)(80.0/x);
+    t0 = 0.0;
+    for (k = m; k > 0; k--) {
+	t0 = k / (1.0 + k / (x+t0));
+    }
+    t = 1.0 / (x + t0);
+    return std::exp(-x)*t;
+}
+
+XSF_HOST_DEVICE inline float exp1(float x) { return exp1(static_cast(x)); }
+
+XSF_HOST_DEVICE inline std::complex exp1(std::complex z) {
+    // ====================================================
+    // Purpose: Compute complex exponential integral E1(z)
+    // Input :  z   --- Argument of E1(z)
+    // Output:  CE1 --- E1(z)
+    // ====================================================
+    constexpr double el = cephes::detail::SCIPY_EULER;
+    int k;
+    std::complex ce1, cr, zc, zd, zdc;
+    double x = z.real();
+    double a0 = std::abs(z);
+    // Continued fraction converges slowly near negative real axis,
+    // so use power series in a wedge around it until radius 40.0
+    double xt = -2.0*std::abs(z.imag());
+
+    if (a0 == 0.0) { return std::numeric_limits::infinity(); }
+    if ((a0 < 5.0) || ((x < xt) && (a0 < 40.0))) {
+        // Power series
+        ce1 = 1.0;
+        cr = 1.0;
+        for (k = 1; k < 501; k++) {
+            cr = -cr*z*static_cast(k / std::pow(k + 1, 2));
+            ce1 += cr;
+            if (std::abs(cr) < std::abs(ce1)*1e-15) { break; }
+        }
+        if ((x <= 0.0) && (z.imag() == 0.0)) {
+            //Careful on the branch cut -- use the sign of the imaginary part
+            // to get the right sign on the factor if pi.
+            ce1 = -el - std::log(-z) + z*ce1 - std::copysign(M_PI, z.imag())*std::complex(0.0, 1.0);
+        } else {
+            ce1 = -el - std::log(z) + z*ce1;
+        }
+    } else {
+        // Continued fraction https://dlmf.nist.gov/6.9
+        //                  1     1     1     2     2     3     3
+        // E1 = exp(-z) * ----- ----- ----- ----- ----- ----- ----- ...
+        //                Z +   1 +   Z +   1 +   Z +   1 +   Z +
+        zc = 0.0;
+        zd = static_cast(1) / z;
+        zdc = zd;
+        zc += zdc;
+        for (k = 1; k < 501; k++) {
+            zd = static_cast(1) / (zd*static_cast(k) + static_cast(1));
+            zdc *= (zd - static_cast(1));
+            zc += zdc;
+
+            zd = static_cast(1) / (zd*static_cast(k) + z);
+            zdc *= (z*zd - static_cast(1));
+            zc += zdc;
+            if ((std::abs(zdc) <= std::abs(zc)*1e-15) && (k > 20)) { break; }
+        }
+        ce1 = std::exp(-z)*zc;
+        if ((x <= 0.0) && (z.imag() == 0.0)) {
+            ce1 -= M_PI*std::complex(0.0, 1.0);
+        }
+    }
+    return ce1;
+}
+
+XSF_HOST_DEVICE inline std::complex exp1(std::complex z) {
+    return static_cast>(exp1(static_cast>(z)));
+}
+
+XSF_HOST_DEVICE inline double expi(double x) {
+    // ============================================
+    // Purpose: Compute exponential integral Ei(x)
+    // Input :  x  --- Argument of Ei(x)
+    // Output:  EI --- Ei(x)
+    // ============================================
+
+    constexpr double ga = cephes::detail::SCIPY_EULER;
+    double ei, r;
+
+    if (x == 0.0) {
+        ei = -std::numeric_limits::infinity();
+    } else if (x < 0) {
+        ei = -exp1(-x);
+    } else if (std::abs(x) <= 40.0) {
+        // Power series around x=0
+        ei = 1.0;
+        r = 1.0;
+
+        for (int k = 1; k <= 100; k++) {
+            r = r * k * x / ((k + 1.0) * (k + 1.0));
+            ei += r;
+            if (std::abs(r / ei) <= 1.0e-15) { break; }
+        }
+        ei = ga + std::log(x) + x * ei;
+    } else {
+        // Asymptotic expansion (the series is not convergent)
+        ei = 1.0;
+        r = 1.0;
+        for (int k = 1; k <= 20; k++) {
+            r = r * k / x;
+            ei += r;
+        }
+        ei = std::exp(x) / x * ei;
+    }
+    return ei;
+}
+
+XSF_HOST_DEVICE inline float expi(float x) { return expi(static_cast(x)); }
+    
+std::complex expi(std::complex z) {
+    // ============================================
+    // Purpose: Compute exponential integral Ei(x)
+    // Input :  x  --- Complex argument of Ei(x)
+    // Output:  EI --- Ei(x)
+    // ============================================
+
+    std::complex cei;
+    cei = - exp1(-z);
+    if (z.imag() > 0.0) {
+        cei += std::complex(0.0, M_PI);
+    } else if (z.imag() < 0.0 ) {
+        cei -= std::complex(0.0, M_PI);
+    } else {
+        if (z.real() > 0.0) {
+            cei += std::complex(0.0, copysign(M_PI, z.imag()));
+        }
+    }
+    return cei;
+}
+
+
+XSF_HOST_DEVICE inline std::complex expi(std::complex z) {
+    return static_cast>(expi(static_cast>(z)));
+}
+
+namespace detail {
+
+    //
+    // Compute a factor of the exponential integral E1.
+    // This is used in scaled_exp1(x) for moderate values of x.
+    //
+    // The function uses the continued fraction expansion given in equation 5.1.22
+    // of Abramowitz & Stegun, "Handbook of Mathematical Functions".
+    // For n=1, this is
+    //
+    //    E1(x) = exp(-x)*C(x)
+    //
+    // where C(x), expressed in the notation used in A&S, is the continued fraction
+    //
+    //            1    1    1    2    2    3    3
+    //    C(x) = ---  ---  ---  ---  ---  ---  ---  ...
+    //           x +  1 +  x +  1 +  x +  1 +  x +
+    //
+    // Here, we pull a factor of 1/z out of C(x), so
+    //
+    //    E1(x) = (exp(-x)/x)*F(x)
+    //
+    // and a bit of algebra gives the continued fraction expansion of F(x) to be
+    //
+    //            1    1    1    2    2    3    3
+    //    F(x) = ---  ---  ---  ---  ---  ---  ---  ...
+    //           1 +  x +  1 +  x +  1 +  x +  1 +
+    //
+    XSF_HOST_DEVICE inline double expint1_factor_cont_frac(double x) {
+        // The number of terms to use in the truncated continued fraction
+        // depends on x.  Larger values of x require fewer terms.
+        int m = 20 + (int) (80.0 / x);
+        double t0 = 0.0;
+        for (int k = m; k > 0; --k) {
+            t0 = k / (x + k / (1 + t0));
+        }
+        return 1 / (1 + t0);
+    }
+
+} // namespace detail
+
+//
+// Scaled version  of the exponential integral E_1(x).
+//
+// Factor E_1(x) as
+//
+//    E_1(x) = exp(-x)/x * F(x)
+//
+// This function computes F(x).
+//
+// F(x) has the properties:
+//  * F(0) = 0
+//  * F is increasing on [0, inf)
+//  * lim_{x->inf} F(x) = 1.
+//
+XSF_HOST_DEVICE inline double scaled_exp1(double x) {
+    if (x < 0) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    if (x == 0) {
+        return 0.0;
+    }
+
+    if (x <= 1) {
+        // For small x, the naive implementation is sufficiently accurate.
+        return x * std::exp(x) * exp1(x);
+    }
+
+    if (x <= 1250) {
+        // For moderate x, use the continued fraction expansion.
+        return detail::expint1_factor_cont_frac(x);
+    }
+
+    // For large x, use the asymptotic expansion.  This is equation 5.1.51
+    // from Abramowitz & Stegun, "Handbook of Mathematical Functions".
+    return 1 + (-1 + (2 + (-6 + (24 - 120 / x) / x) / x) / x) / x;
+}
+
+XSF_HOST_DEVICE inline float scaled_exp1(float x) { return scaled_exp1(static_cast(x)); }
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d4eff7532202380bcd5dbd2978d46d5f613d5eb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h
@@ -0,0 +1,694 @@
+/* Implementation of Gauss's hypergeometric function for complex values.
+ *
+ * This implementation is based on the Fortran implementation by Shanjie Zhang and
+ * Jianming Jin included in specfun.f [1]_.  Computation of Gauss's hypergeometric
+ * function involves handling a patchwork of special cases. By default the Zhang and
+ * Jin implementation has been followed as closely as possible except for situations where
+ * an improvement was obvious. We've attempted to document the reasons behind decisions
+ * made by Zhang and Jin and to document the reasons for deviating from their implementation
+ * when this has been done. References to the NIST Digital Library of Mathematical
+ * Functions [2]_ have been added where they are appropriate. The review paper by
+ * Pearson et al [3]_ is an excellent resource for best practices for numerical
+ * computation of hypergeometric functions. We have followed this review paper
+ * when making improvements to and correcting defects in Zhang and Jin's
+ * implementation. When Pearson et al propose several competing alternatives for a
+ * given case, we've used our best judgment to decide on the method to use.
+ *
+ * Author: Albert Steppi
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * References
+ * ----------
+ * .. [1] S. Zhang and J.M. Jin, "Computation of Special Functions", Wiley 1996
+ * .. [2] NIST Digital Library of Mathematical Functions. http://dlmf.nist.gov/,
+ *        Release 1.1.1 of 2021-03-15. F. W. J. Olver, A. B. Olde Daalhuis,
+ *        D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R. Miller,
+ *        B. V. Saunders, H. S. Cohl, and M. A. McClain, eds.
+ * .. [3] Pearson, J.W., Olver, S. & Porter, M.A.
+ *        "Numerical methods for the computation of the confluent and Gauss
+ *        hypergeometric functions."
+ *        Numer Algor 74, 821-866 (2017). https://doi.org/10.1007/s11075-016-0173-0
+ * .. [4] Raimundas Vidunas, "Degenerate Gauss Hypergeometric Functions",
+ *        Kyushu Journal of Mathematics, 2007, Volume 61, Issue 1, Pages 109-135,
+ * .. [5] López, J.L., Temme, N.M. New series expansions of the Gauss hypergeometric
+ *        function. Adv Comput Math 39, 349-365 (2013).
+ *        https://doi.org/10.1007/s10444-012-9283-y
+ * """
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+#include "tools.h"
+
+#include "binom.h"
+#include "cephes/gamma.h"
+#include "cephes/lanczos.h"
+#include "cephes/poch.h"
+#include "cephes/hyp2f1.h"
+#include "digamma.h"
+
+namespace xsf {
+namespace detail {
+    constexpr double hyp2f1_EPS = 1e-15;
+    /* The original implementation in SciPy from Zhang and Jin used 1500 for the
+     * maximum number of series iterations in some cases and 500 in others.
+     * Through the empirical results on the test cases in
+     * scipy/special/_precompute/hyp2f1_data.py, it was determined that these values
+     * can lead to early termination of series which would have eventually converged
+     * at a reasonable level of accuracy. We've bumped the iteration limit to 3000,
+     * and may adjust it again based on further analysis. */
+    constexpr std::uint64_t hyp2f1_MAXITER = 3000;
+
+    XSF_HOST_DEVICE inline double four_gammas_lanczos(double u, double v, double w, double x) {
+        /* Compute ratio of gamma functions using lanczos approximation.
+         *
+         * Computes gamma(u)*gamma(v)/(gamma(w)*gamma(x))
+         *
+         * It is assumed that x = u + v - w, but it is left to the user to
+         * ensure this.
+         *
+         * The lanczos approximation takes the form
+         *
+         * gamma(x) = factor(x) * lanczos_sum_expg_scaled(x)
+         *
+         * where factor(x) = ((x + lanczos_g - 0.5)/e)**(x - 0.5).
+         *
+         * The formula above is only valid for x >= 0.5, but can be extended to
+         * x < 0.5 with the reflection principle.
+         *
+         * Using the lanczos approximation when computing this ratio of gamma functions
+         * allows factors to be combined analytically to avoid underflow and overflow
+         * and produce a more accurate result. The condition x = u + v - w makes it
+         * possible to cancel the factors in the expression
+         *
+         * factor(u) * factor(v) / (factor(w) * factor(x))
+         *
+         * by taking one factor and absorbing it into the others. Currently, this
+         * implementation takes the factor corresponding to the argument with largest
+         * absolute value and absorbs it into the others.
+         *
+         * Since this is only called internally by four_gammas. It is assumed that
+         * |u| >= |v| and |w| >= |x|.
+         */
+
+        /* The below implementation may incorrectly return finite results
+         * at poles of the gamma function. Handle these cases explicitly. */
+        if ((u == std::trunc(u) && u <= 0) || (v == std::trunc(v) && v <= 0)) {
+            /* Return nan if numerator has pole. Diverges to +- infinity
+             * depending on direction so value is undefined. */
+            return std::numeric_limits::quiet_NaN();
+        }
+        if ((w == std::trunc(w) && w <= 0) || (x == std::trunc(x) && x <= 0)) {
+            // Return 0 if denominator has pole but not numerator.
+            return 0.0;
+        }
+
+        double result = 1.0;
+        double ugh, vgh, wgh, xgh, u_prime, v_prime, w_prime, x_prime;
+
+        if (u >= 0.5) {
+            result *= cephes::lanczos_sum_expg_scaled(u);
+            ugh = u + cephes::lanczos_g - 0.5;
+            u_prime = u;
+        } else {
+            result /= cephes::lanczos_sum_expg_scaled(1 - u) * std::sin(M_PI * u) * M_1_PI;
+            ugh = 0.5 - u + cephes::lanczos_g;
+            u_prime = 1 - u;
+        }
+
+        if (v >= 0.5) {
+            result *= cephes::lanczos_sum_expg_scaled(v);
+            vgh = v + cephes::lanczos_g - 0.5;
+            v_prime = v;
+        } else {
+            result /= cephes::lanczos_sum_expg_scaled(1 - v) * std::sin(M_PI * v) * M_1_PI;
+            vgh = 0.5 - v + cephes::lanczos_g;
+            v_prime = 1 - v;
+        }
+
+        if (w >= 0.5) {
+            result /= cephes::lanczos_sum_expg_scaled(w);
+            wgh = w + cephes::lanczos_g - 0.5;
+            w_prime = w;
+        } else {
+            result *= cephes::lanczos_sum_expg_scaled(1 - w) * std::sin(M_PI * w) * M_1_PI;
+            wgh = 0.5 - w + cephes::lanczos_g;
+            w_prime = 1 - w;
+        }
+
+        if (x >= 0.5) {
+            result /= cephes::lanczos_sum_expg_scaled(x);
+            xgh = x + cephes::lanczos_g - 0.5;
+            x_prime = x;
+        } else {
+            result *= cephes::lanczos_sum_expg_scaled(1 - x) * std::sin(M_PI * x) * M_1_PI;
+            xgh = 0.5 - x + cephes::lanczos_g;
+            x_prime = 1 - x;
+        }
+
+        if (std::abs(u) >= std::abs(w)) {
+            // u has greatest absolute value. Absorb ugh into the others.
+            if (std::abs((v_prime - u_prime) * (v - 0.5)) < 100 * ugh and v > 100) {
+                /* Special case where base is close to 1. Condition taken from
+                 * Boost's beta function implementation. */
+                result *= std::exp((v - 0.5) * std::log1p((v_prime - u_prime) / ugh));
+            } else {
+                result *= std::pow(vgh / ugh, v - 0.5);
+            }
+
+            if (std::abs((u_prime - w_prime) * (w - 0.5)) < 100 * wgh and u > 100) {
+                result *= std::exp((w - 0.5) * std::log1p((u_prime - w_prime) / wgh));
+            } else {
+                result *= std::pow(ugh / wgh, w - 0.5);
+            }
+
+            if (std::abs((u_prime - x_prime) * (x - 0.5)) < 100 * xgh and u > 100) {
+                result *= std::exp((x - 0.5) * std::log1p((u_prime - x_prime) / xgh));
+            } else {
+                result *= std::pow(ugh / xgh, x - 0.5);
+            }
+        } else {
+            // w has greatest absolute value. Absorb wgh into the others.
+            if (std::abs((u_prime - w_prime) * (u - 0.5)) < 100 * wgh and u > 100) {
+                result *= std::exp((u - 0.5) * std::log1p((u_prime - w_prime) / wgh));
+            } else {
+                result *= pow(ugh / wgh, u - 0.5);
+            }
+            if (std::abs((v_prime - w_prime) * (v - 0.5)) < 100 * wgh and v > 100) {
+                result *= std::exp((v - 0.5) * std::log1p((v_prime - w_prime) / wgh));
+            } else {
+                result *= std::pow(vgh / wgh, v - 0.5);
+            }
+            if (std::abs((w_prime - x_prime) * (x - 0.5)) < 100 * xgh and x > 100) {
+                result *= std::exp((x - 0.5) * std::log1p((w_prime - x_prime) / xgh));
+            } else {
+                result *= std::pow(wgh / xgh, x - 0.5);
+            }
+        }
+        // This exhausts all cases because we assume |u| >= |v| and |w| >= |x|.
+
+        return result;
+    }
+
+    XSF_HOST_DEVICE inline double four_gammas(double u, double v, double w, double x) {
+        double result;
+
+        // Without loss of generality, ensure |u| >= |v| and |w| >= |x|.
+        if (std::abs(v) > std::abs(u)) {
+            std::swap(u, v);
+        }
+        if (std::abs(x) > std::abs(w)) {
+            std::swap(x, w);
+        }
+        /* Direct ratio tends to be more accurate for arguments in this range. Range
+         * chosen empirically based on the relevant benchmarks in
+         * scipy/special/_precompute/hyp2f1_data.py */
+        if (std::abs(u) <= 100 && std::abs(v) <= 100 && std::abs(w) <= 100 && std::abs(x) <= 100) {
+            result = cephes::Gamma(u) * cephes::Gamma(v) * (cephes::rgamma(w) * cephes::rgamma(x));
+            if (std::isfinite(result) && result != 0.0) {
+                return result;
+            }
+        }
+        result = four_gammas_lanczos(u, v, w, x);
+        if (std::isfinite(result) && result != 0.0) {
+            return result;
+        }
+        // If overflow or underflow, try again with logs.
+        result = std::exp(cephes::lgam(v) - cephes::lgam(x) + cephes::lgam(u) - cephes::lgam(w));
+        result *= cephes::gammasgn(u) * cephes::gammasgn(w) * cephes::gammasgn(v) * cephes::gammasgn(x);
+        return result;
+    }
+
+    class HypergeometricSeriesGenerator {
+        /* Maclaurin series for hyp2f1.
+         *
+         * Series is convergent for |z| < 1 but is only practical for numerical
+         * computation when |z| < 0.9.
+         */
+      public:
+        XSF_HOST_DEVICE HypergeometricSeriesGenerator(double a, double b, double c, std::complex z)
+            : a_(a), b_(b), c_(c), z_(z), term_(1.0), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex output = term_;
+            term_ = term_ * (a_ + k_) * (b_ + k_) / ((k_ + 1) * (c_ + k_)) * z_;
+            ++k_;
+            return output;
+        }
+
+      private:
+        double a_, b_, c_;
+        std::complex z_, term_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform1Generator {
+        /* 1 -z transformation of standard series.*/
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform1Generator(double a, double b, double c, std::complex z)
+            : factor1_(four_gammas(c, c - a - b, c - a, c - b)),
+              factor2_(four_gammas(c, a + b - c, a, b) * std::pow(1.0 - z, c - a - b)),
+              generator1_(HypergeometricSeriesGenerator(a, b, a + b - c + 1, 1.0 - z)),
+              generator2_(HypergeometricSeriesGenerator(c - a, c - b, c - a - b + 1, 1.0 - z)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            return factor1_ * generator1_() + factor2_ * generator2_();
+        }
+
+      private:
+        std::complex factor1_, factor2_;
+        HypergeometricSeriesGenerator generator1_, generator2_;
+    };
+
+    class Hyp2f1Transform1LimitSeriesGenerator {
+        /* 1 - z transform in limit as c - a - b approaches an integer m. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform1LimitSeriesGenerator(double a, double b, double m, std::complex z)
+            : d1_(xsf::digamma(a)), d2_(xsf::digamma(b)), d3_(xsf::digamma(1 + m)),
+              d4_(xsf::digamma(1.0)), a_(a), b_(b), m_(m), z_(z), log_1_z_(std::log(1.0 - z)),
+              factor_(cephes::rgamma(m + 1)), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term_ = (d1_ + d2_ - d3_ - d4_ + log_1_z_) * factor_;
+            // Use digamma(x + 1) = digamma(x) + 1/x
+            d1_ += 1 / (a_ + k_);       // d1 = digamma(a + k)
+            d2_ += 1 / (b_ + k_);       // d2 = digamma(b + k)
+            d3_ += 1 / (1.0 + m_ + k_); // d3 = digamma(1 + m + k)
+            d4_ += 1 / (1.0 + k_);      // d4 = digamma(1 + k)
+            factor_ *= (a_ + k_) * (b_ + k_) / ((k_ + 1.0) * (m_ + k_ + 1)) * (1.0 - z_);
+            ++k_;
+            return term_;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, m_;
+        std::complex z_, log_1_z_, factor_;
+        int k_;
+    };
+
+    class Hyp2f1Transform2Generator {
+        /* 1/z transformation of standard series.*/
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2Generator(double a, double b, double c, std::complex z)
+            : factor1_(four_gammas(c, b - a, b, c - a) * std::pow(-z, -a)),
+              factor2_(four_gammas(c, a - b, a, c - b) * std::pow(-z, -b)),
+              generator1_(HypergeometricSeriesGenerator(a, a - c + 1, a - b + 1, 1.0 / z)),
+              generator2_(HypergeometricSeriesGenerator(b, b - c + 1, b - a + 1, 1.0 / z)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            return factor1_ * generator1_() + factor2_ * generator2_();
+        }
+
+      private:
+        std::complex factor1_, factor2_;
+        HypergeometricSeriesGenerator generator1_, generator2_;
+    };
+
+    class Hyp2f1Transform2LimitSeriesGenerator {
+        /* 1/z transform in limit as a - b approaches a non-negative integer m. (Can swap a and b to
+         * handle the m a negative integer case. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesGenerator(double a, double b, double c, double m,
+                                                                 std::complex z)
+            : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)),
+              d4_(xsf::digamma(c - a)), a_(a), b_(b), c_(c), m_(m), z_(z), log_neg_z_(std::log(-z)),
+              factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) *
+                      xsf::cephes::rgamma(m + 1)),
+              k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_;
+            // Use digamma(x + 1) = digamma(x) + 1/x
+            d1_ += 1 / (1.0 + k_);         // d1 = digamma(1 + k)
+            d2_ += 1 / (1.0 + m_ + k_);    // d2 = digamma(1 + m + k)
+            d3_ += 1 / (a_ + k_);          // d3 = digamma(a + k)
+            d4_ -= 1 / (c_ - a_ - k_ - 1); // d4 = digamma(c - a - k)
+            factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+            ++k_;
+            return term;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, c_, m_;
+        std::complex z_, log_neg_z_, factor_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform2LimitSeriesCminusAIntGenerator {
+        /* 1/z transform in limit as a - b approaches a non-negative integer m, and c - a approaches
+         * a positive integer n. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesCminusAIntGenerator(double a, double b, double c, double m,
+                                                                           double n, std::complex z)
+            : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)),
+              d4_(xsf::digamma(n)), a_(a), b_(b), c_(c), m_(m), n_(n), z_(z), log_neg_z_(std::log(-z)),
+              factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) *
+                      xsf::cephes::rgamma(m + 1)),
+              k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term;
+            if (k_ < n_) {
+                term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_;
+                // Use digamma(x + 1) = digamma(x) + 1/x
+                d1_ += 1 / (1.0 + k_);    // d1 = digamma(1 + k)
+                d2_ += 1 / (1 + m_ + k_); // d2 = digamma(1 + m + k)
+                d3_ += 1 / (a_ + k_);     // d3 = digamma(a + k)
+                d4_ -= 1 / (n_ - k_ - 1); // d4 = digamma(c - a - k)
+                factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+                ++k_;
+                return term;
+            }
+            if (k_ == n_) {
+                /* When c - a approaches a positive integer and k_ >= c - a = n then
+                 * poch(1 - c + b + m + k) = poch(1 - c + a + k) = approaches zero and
+                 * digamma(c - a - k) approaches a pole. However we can use the limit
+                 * digamma(-n + epsilon) / gamma(-n + epsilon) -> (-1)**(n + 1) * (n+1)! as epsilon -> 0
+                 * to continue the series.
+                 *
+                 * poch(1 - c + b, m + k) = gamma(1 - c + b + m + k)/gamma(1 - c + b)
+                 *
+                 * If a - b is an integer and c - a is an integer, then a and b must both be integers, so assume
+                 * a and b are integers and take the limit as c approaches an integer.
+                 *
+                 * gamma(1 - c + epsilon + a + k)/gamma(1 - c - epsilon + b) =
+                 * (gamma(c + epsilon - b) / gamma(c + epsilon - a - k)) *
+                 * (sin(pi * (c + epsilon - b)) / sin(pi * (c + epsilon - a - k))) (reflection principle)
+                 *
+                 * In the limit as epsilon goes to zero, the ratio of sines will approach
+                 * (-1)**(a - b + k) = (-1)**(m + k)
+                 *
+                 * We may then replace
+                 *
+                 * poch(1 - c - epsilon + b, m + k)*digamma(c + epsilon - a - k)
+                 *
+                 * with
+                 *
+                 * (-1)**(a - b + k)*gamma(c + epsilon - b) * digamma(c + epsilon - a - k) / gamma(c + epsilon - a - k)
+                 *
+                 * and taking the limit epsilon -> 0 gives
+                 *
+                 * (-1)**(a - b + k) * gamma(c - b) * (-1)**(k + a - c + 1)(k + a - c)!
+                 * = (-1)**(c - b - 1)*Gamma(k + a - c + 1)
+                 */
+                factor_ = std::pow(-1, m_ + n_) * xsf::binom(c_ - 1, b_ - 1) *
+                          xsf::cephes::poch(c_ - a_ + 1, m_ - 1) / std::pow(z_, static_cast(k_));
+            }
+            term = factor_;
+            factor_ *= (b_ + m_ + k_) * (k_ + a_ - c_ + 1) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+            ++k_;
+            return term;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, c_, m_, n_;
+        std::complex z_, log_neg_z_, factor_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform2LimitFinitePartGenerator {
+        /* Initial finite sum in limit as a - b approaches a non-negative integer m. The limiting series
+         * for the 1 - z transform also has an initial finite sum, but it is a standard hypergeometric
+         * series. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitFinitePartGenerator(double b, double c, double m,
+                                                                     std::complex z)
+            : b_(b), c_(c), m_(m), z_(z), term_(cephes::Gamma(m) * cephes::rgamma(c - b)), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex output = term_;
+            term_ = term_ * (b_ + k_) * (c_ - b_ - k_ - 1) / ((k_ + 1) * (m_ - k_ - 1)) / z_;
+            ++k_;
+            return output;
+        }
+
+      private:
+        double b_, c_, m_;
+        std::complex z_, term_;
+        std::uint64_t k_;
+    };
+
+    class LopezTemmeSeriesGenerator {
+        /* Lopez-Temme Series for Gaussian hypergeometric function [4].
+         *
+         * Converges for all z with real(z) < 1, including in the regions surrounding
+         * the points exp(+- i*pi/3) that are not covered by any of the standard
+         * transformations.
+         */
+      public:
+        XSF_HOST_DEVICE LopezTemmeSeriesGenerator(double a, double b, double c, std::complex z)
+            : n_(0), a_(a), b_(b), c_(c), phi_previous_(1.0), phi_(1 - 2 * b / c), z_(z), Z_(a * z / (z - 2.0)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            if (n_ == 0) {
+                ++n_;
+                return 1.0;
+            }
+            if (n_ > 1) { // Update phi and Z for n>=2
+                double new_phi = ((n_ - 1) * phi_previous_ - (2.0 * b_ - c_) * phi_) / (c_ + (n_ - 1));
+                phi_previous_ = phi_;
+                phi_ = new_phi;
+                Z_ = Z_ * z_ / (z_ - 2.0) * ((a_ + (n_ - 1)) / n_);
+            }
+            ++n_;
+            return Z_ * phi_;
+        }
+
+      private:
+        std::uint64_t n_;
+        double a_, b_, c_, phi_previous_, phi_;
+        std::complex z_, Z_;
+    };
+
+    XSF_HOST_DEVICE std::complex hyp2f1_transform1_limiting_case(double a, double b, double c, double m,
+                                                                             std::complex z) {
+        /* 1 - z transform in limiting case where c - a - b approaches an integer m. */
+        std::complex result = 0.0;
+        if (m >= 0) {
+            if (m != 0) {
+                auto series_generator = HypergeometricSeriesGenerator(a, b, 1 - m, 1.0 - z);
+                result += four_gammas(m, c, a + m, b + m) * series_eval_fixed_length(series_generator,
+                                                                                     std::complex{0.0, 0.0},
+                                                                                     static_cast(m));
+            }
+            std::complex prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) /
+                                             (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b)) *
+                                             std::pow(1.0 - z, m);
+            auto series_generator = Hyp2f1Transform1LimitSeriesGenerator(a + m, b + m, m, z);
+            result += prefactor * series_eval(series_generator, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        } else {
+            result = four_gammas(-m, c, a, b) * std::pow(1.0 - z, m);
+            auto series_generator1 = HypergeometricSeriesGenerator(a + m, b + m, 1 + m, 1.0 - z);
+            result *= series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0},
+                                               static_cast(-m));
+            double prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) *
+                               (xsf::cephes::rgamma(a + m) * xsf::cephes::rgamma(b + m));
+            auto series_generator2 = Hyp2f1Transform1LimitSeriesGenerator(a, b, -m, z);
+            result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+    }
+
+    XSF_HOST_DEVICE std::complex hyp2f1_transform2_limiting_case(double a, double b, double c, double m,
+                                                                             std::complex z) {
+        /* 1 / z transform in limiting case where a - b approaches a non-negative integer m. Negative integer case
+         * can be handled by swapping a and b. */
+        auto series_generator1 = Hyp2f1Transform2LimitFinitePartGenerator(b, c, m, z);
+        std::complex result = cephes::Gamma(c) * cephes::rgamma(a) * std::pow(-z, -b);
+        result *=
+            series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0}, static_cast(m));
+        std::complex prefactor = cephes::Gamma(c) * (cephes::rgamma(a) * cephes::rgamma(c - b) * std::pow(-z, -a));
+        double n = c - a;
+        if (abs(n - std::round(n)) < hyp2f1_EPS) {
+            auto series_generator2 = Hyp2f1Transform2LimitSeriesCminusAIntGenerator(a, b, c, m, n, z);
+            result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+        auto series_generator2 = Hyp2f1Transform2LimitSeriesGenerator(a, b, c, m, z);
+        result += prefactor *
+                  series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS, hyp2f1_MAXITER, "hyp2f1");
+        return result;
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline std::complex hyp2f1(double a, double b, double c, std::complex z) {
+    /* Special Cases
+     * -----------------------------------------------------------------------
+     * Takes constant value 1 when a = 0 or b = 0, even if c is a non-positive
+     * integer. This follows mpmath. */
+    if (a == 0 || b == 0) {
+        return 1.0;
+    }
+    double z_abs = std::abs(z);
+    // Equals 1 when z i 0, unless c is 0.
+    if (z_abs == 0) {
+        if (c != 0) {
+            return 1.0;
+        } else {
+            // Returning real part NAN and imaginary part 0 follows mpmath.
+            return std::complex{std::numeric_limits::quiet_NaN(), 0};
+        }
+    }
+    bool a_neg_int = a == std::trunc(a) && a < 0;
+    bool b_neg_int = b == std::trunc(b) && b < 0;
+    bool c_non_pos_int = c == std::trunc(c) and c <= 0;
+    /* Diverges when c is a non-positive integer unless a is an integer with
+     * c <= a <= 0 or b is an integer with c <= b <= 0, (or z equals 0 with
+     * c != 0) Cases z = 0, a = 0, or b = 0 have already been handled. We follow
+     * mpmath in handling the degenerate cases where any of a, b, c are
+     * non-positive integers. See [3] for a treatment of degenerate cases. */
+    if (c_non_pos_int && !((a_neg_int && c <= a && a < 0) || (b_neg_int && c <= b && b < 0))) {
+        return std::complex{std::numeric_limits::infinity(), 0};
+    }
+    /* Reduces to a polynomial when a or b is a negative integer.
+     * If a and b are both negative integers, we take care to terminate
+     * the series at a or b of smaller magnitude. This is to ensure proper
+     * handling of situations like a < c < b <= 0, a, b, c all non-positive
+     * integers, where terminating at a would lead to a term of the form 0 / 0. */
+    double max_degree;
+    if (a_neg_int || b_neg_int) {
+        if (a_neg_int && b_neg_int) {
+            max_degree = a > b ? std::abs(a) : std::abs(b);
+        } else if (a_neg_int) {
+            max_degree = std::abs(a);
+        } else {
+            max_degree = std::abs(b);
+        }
+        if (max_degree <= (double) UINT64_MAX) {
+            auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z);
+            return detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 1);
+        } else {
+            set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+            return std::complex{std::numeric_limits::quiet_NaN(),
+                                        std::numeric_limits::quiet_NaN()};
+        }
+    }
+    // Kummer's Theorem for z = -1; c = 1 + a - b (DLMF 15.4.26)
+    if (std::abs(z + 1.0) < detail::hyp2f1_EPS && std::abs(1 + a - b - c) < detail::hyp2f1_EPS && !c_non_pos_int) {
+        return detail::four_gammas(a - b + 1, 0.5 * a + 1, a + 1, 0.5 * a - b + 1);
+    }
+    std::complex result;
+    bool c_minus_a_neg_int = c - a == std::trunc(c - a) && c - a < 0;
+    bool c_minus_b_neg_int = c - b == std::trunc(c - b) && c - b < 0;
+    /* If one of c - a or c - b is a negative integer, reduces to evaluating
+     * a polynomial through an Euler hypergeometric transformation.
+     * (DLMF 15.8.1) */
+    if (c_minus_a_neg_int || c_minus_b_neg_int) {
+        max_degree = c_minus_b_neg_int ? std::abs(c - b) : std::abs(c - a);
+        if (max_degree <= (double) UINT64_MAX) {
+            result = std::pow(1.0 - z, c - a - b);
+            auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z);
+            result *=
+                detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 2);
+            return result;
+        } else {
+            set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+            return std::complex{std::numeric_limits::quiet_NaN(),
+                                        std::numeric_limits::quiet_NaN()};
+        }
+    }
+    /* Diverges as real(z) -> 1 when c <= a + b.
+     * Todo: Actually check for overflow instead of using a fixed tolerance for
+     * all parameter combinations like in the Fortran original. */
+    if (std::abs(1 - z.real()) < detail::hyp2f1_EPS && z.imag() == 0 && c - a - b <= 0 && !c_non_pos_int) {
+        return std::complex{std::numeric_limits::infinity(), 0};
+    }
+    // Gauss's Summation Theorem for z = 1; c - a - b > 0 (DLMF 15.4.20).
+    if (z == 1.0 && c - a - b > 0 && !c_non_pos_int) {
+        return detail::four_gammas(c, c - a - b, c - a, c - b);
+    }
+    /* |z| < 0, z.real() >= 0. Use the Maclaurin Series.
+     * -----------------------------------------------------------------------
+     * Apply Euler Hypergeometric Transformation (DLMF 15.8.1) to reduce
+     * size of a and b if possible. We follow Zhang and Jin's
+     * implementation [1] although there is very likely a better heuristic
+     * to determine when this transformation should be applied. As it
+     * stands, this hurts precision in some cases. */
+    if (z_abs < 0.9 && z.real() >= 0) {
+        if (c - a < a && c - b < b) {
+            result = std::pow(1.0 - z, c - a - b);
+            auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z);
+            result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                          detail::hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+        auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z);
+        return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                   detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* Points near exp(iπ/3), exp(-iπ/3) not handled by any of the standard
+     * transformations. Use series of López and Temme [5]. These regions
+     * were not correctly handled by Zhang and Jin's implementation.
+     * -------------------------------------------------------------------------*/
+    if (0.9 <= z_abs && z_abs < 1.1 && std::abs(1.0 - z) >= 0.9 && z.real() >= 0) {
+        /* This condition for applying Euler Transformation (DLMF 15.8.1)
+         * was determined empirically to work better for this case than that
+         * used in Zhang and Jin's implementation for |z| < 0.9,
+         *  real(z) >= 0. */
+        if ((c - a <= a && c - b < b) || (c - a < a && c - b <= b)) {
+            auto series_generator = detail::LopezTemmeSeriesGenerator(c - a, c - b, c, z);
+            result = std::pow(1.0 - 0.5 * z, a - c); // Lopez-Temme prefactor
+            result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                          detail::hyp2f1_MAXITER, "hyp2f1");
+            return std::pow(1.0 - z, c - a - b) * result; // Euler transform prefactor.
+        }
+        auto series_generator = detail::LopezTemmeSeriesGenerator(a, b, c, z);
+        result = detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                     detail::hyp2f1_MAXITER, "hyp2f1");
+        return std::pow(1.0 - 0.5 * z, -a) * result; // Lopez-Temme prefactor.
+    }
+    /* z/(z - 1) transformation (DLMF 15.8.1). Avoids cancellation issues that
+     * occur with Maclaurin series for real(z) < 0.
+     * -------------------------------------------------------------------------*/
+    if (z_abs < 1.1 && z.real() < 0) {
+        if (0 < b && b < a && a < c) {
+            std::swap(a, b);
+        }
+        auto series_generator = detail::HypergeometricSeriesGenerator(a, c - b, c, z / (z - 1.0));
+        return std::pow(1.0 - z, -a) * detail::series_eval(series_generator, std::complex{0.0, 0.0},
+                                                           detail::hyp2f1_EPS, detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* 1 - z transformation (DLMF 15.8.4). */
+    if (0.9 <= z_abs && z_abs < 1.1) {
+        if (std::abs(c - a - b - std::round(c - a - b)) < detail::hyp2f1_EPS) {
+            // Removable singularity when c - a - b is an integer. Need to use limiting formula.
+            double m = std::round(c - a - b);
+            return detail::hyp2f1_transform1_limiting_case(a, b, c, m, z);
+        }
+        auto series_generator = detail::Hyp2f1Transform1Generator(a, b, c, z);
+        return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                   detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* 1/z transformation (DLMF 15.8.2). */
+    if (std::abs(a - b - std::round(a - b)) < detail::hyp2f1_EPS) {
+        if (b > a) {
+            std::swap(a, b);
+        }
+        double m = std::round(a - b);
+        return detail::hyp2f1_transform2_limiting_case(a, b, c, m, z);
+    }
+    auto series_generator = detail::Hyp2f1Transform2Generator(a, b, c, z);
+    return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                               detail::hyp2f1_MAXITER, "hyp2f1");
+}
+
+XSF_HOST_DEVICE inline std::complex hyp2f1(float a, float b, float c, std::complex x) {
+    return static_cast>(hyp2f1(static_cast(a), static_cast(b),
+                                                   static_cast(c), static_cast>(x)));
+}
+
+XSF_HOST_DEVICE inline double hyp2f1(double a, double b, double c, double x) { return cephes::hyp2f1(a, b, c, x); }
+
+XSF_HOST_DEVICE inline float hyp2f1(float a, float b, float c, float x) {
+    return hyp2f1(static_cast(a), static_cast(b), static_cast(c), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5dc871bd003937a483a39001d796b1bacc26d01
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h
@@ -0,0 +1,173 @@
+// Numerically stable computation of iv(v+1, x) / iv(v, x)
+
+#pragma once
+
+#include "config.h"
+#include "tools.h"
+#include "error.h"
+#include "cephes/dd_real.h"
+
+namespace xsf {
+
+/* Generates the "tail" of Perron's continued fraction for iv(v,x)/iv(v-1,x).
+ *
+ * The Perron continued fraction is studied in [1].  It is given by
+ *
+ *         iv(v, x)      x    -(2v+1)x   -(2v+3)x   -(2v+5)x
+ *   R := --------- = ------ ---------- ---------- ---------- ...
+ *        iv(v-1,x)   x+2v + 2(v+x)+1 + 2(v+x)+2 + 2(v+x)+3 +
+ *
+ * Given a suitable constant c, the continued fraction may be rearranged
+ * into the following form to avoid premature floating point overflow:
+ *
+ *        xc                -(2vc+c)(xc) -(2vc+3c)(xc) -(2vc+5c)(xc)
+ *   R = -----,  fc = 2vc + ------------ ------------- ------------- ...
+ *       xc+fc              2(vc+xc)+c + 2(vc+xc)+2c + 2(vc+xc)+3c +
+ *
+ * This class generates the fractions of fc after 2vc.
+ *
+ * [1] Gautschi, W. and Slavik, J. (1978). "On the computation of modified
+ *     Bessel function ratios." Mathematics of Computation, 32(143):865-875.
+ */
+template 
+struct IvRatioCFTailGenerator {
+
+    XSF_HOST_DEVICE IvRatioCFTailGenerator(T vc, T xc, T c) noexcept {
+        a0_ = -(2*vc-c)*xc;
+        as_ = -2*c*xc;
+        b0_ = 2*(vc+xc);
+        bs_ = c;
+        k_ = 0;
+    }
+
+    XSF_HOST_DEVICE std::pair operator()() noexcept {
+        using std::fma;
+        ++k_;
+        return {fma(static_cast(k_), as_, a0_),
+                fma(static_cast(k_), bs_, b0_)};
+    }
+
+private:
+    T a0_, as_;  // a[k] == a0 + as*k, k >= 1
+    T b0_, bs_;  // b[k] == b0 + bs*k, k >= 1
+    std::uint64_t k_; // current index
+};
+
+// Computes f(v, x) using Perron's continued fraction.
+//
+// T specifies the working type.  This allows the function to perform
+// calculations in a higher precision, such as double-double, even if
+// the return type is hardcoded to be double.
+template 
+XSF_HOST_DEVICE inline std::pair
+_iv_ratio_cf(double v, double x, bool complement) {
+
+    int e;
+    std::frexp(std::fmax(v, x), &e);
+    T c = T(std::ldexp(1, 2-e)); // rescaling multiplier
+    T vc = v * c;
+    T xc = x * c;
+
+    IvRatioCFTailGenerator cf(vc, xc, c);
+    auto [fc, terms] = detail::series_eval_kahan(
+        detail::continued_fraction_series(cf),
+        T(std::numeric_limits::epsilon()),
+        1000,
+        2*vc);
+
+    T ret = (complement ? fc : xc) / (xc + fc);
+    return {static_cast(ret), terms};
+}
+
+XSF_HOST_DEVICE inline double iv_ratio(double v, double x) {
+
+    if (std::isnan(v) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (v < 0.5 || x < 0) {
+        set_error("iv_ratio", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(v) && std::isinf(x)) {
+        // There is not a unique limit as both v and x tends to infinity.
+        set_error("iv_ratio", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        return x; // keep sign of x because iv_ratio is an odd function
+    }
+    if (std::isinf(v)) {
+        return 0.0;
+    }
+    if (std::isinf(x)) {
+        return 1.0;
+    }
+
+    auto [ret, terms] = _iv_ratio_cf(v, x, false);
+    if (terms == 0) { // failed to converge; should not happen
+        set_error("iv_ratio", SF_ERROR_NO_RESULT, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    return ret;
+}
+
+XSF_HOST_DEVICE inline float iv_ratio(float v, float x) {
+    return iv_ratio(static_cast(v), static_cast(x));
+}
+
+XSF_HOST_DEVICE inline double iv_ratio_c(double v, double x) {
+
+    if (std::isnan(v) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (v < 0.5 || x < 0) {
+        set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(v) && std::isinf(x)) {
+        // There is not a unique limit as both v and x tends to infinity.
+        set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        return 1.0;
+    }
+    if (std::isinf(v)) {
+        return 1.0;
+    }
+    if (std::isinf(x)) {
+        return 0.0;
+    }
+
+    if (v >= 1) {
+        // Numerical experiments show that evaluating the Perron c.f.
+        // in double precision is sufficiently accurate if v >= 1.
+        auto [ret, terms] = _iv_ratio_cf(v, x, true);
+        if (terms == 0) { // failed to converge; should not happen
+            set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        return ret;
+    } else if (v > 0.5) {
+        // double-double arithmetic is needed for 0.5 < v < 1 to
+        // achieve relative error on the scale of machine precision.
+        using cephes::detail::double_double;
+        auto [ret, terms] = _iv_ratio_cf(v, x, true);
+        if (terms == 0) { // failed to converge; should not happen
+            set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        return ret;
+    } else {
+        // The previous branch (v > 0.5) also works for v == 0.5, but
+        // the closed-form formula "1 - tanh(x)" is more efficient.
+        double t = std::exp(-2*x);
+        return (2 * t) / (1 + t);
+    }
+}
+
+XSF_HOST_DEVICE inline float iv_ratio_c(float v, float x) {
+    return iv_ratio_c(static_cast(v), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h
new file mode 100644
index 0000000000000000000000000000000000000000..9eb1882eaec464b5e5dcf47f2168f9125996a816
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h
@@ -0,0 +1,150 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of the Lambert W function [1]. Based on MPMath
+ *  Implementation [2], and documentation [3].
+ *
+ * Copyright: Yosef Meller, 2009
+ * Author email: mellerf@netvision.net.il
+ *
+ * Distributed under the same license as SciPy
+ *
+ *
+ * References:
+ * [1] On the Lambert W function, Adv. Comp. Math. 5 (1996) 329-359,
+ *     available online: https://web.archive.org/web/20230123211413/https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
+ * [2] mpmath source code,
+ https://github.com/mpmath/mpmath/blob/c5939823669e1bcce151d89261b802fe0d8978b4/mpmath/functions/functions.py#L435-L461
+ * [3]
+ https://web.archive.org/web/20230504171447/https://mpmath.org/doc/current/functions/powers.html#lambert-w-function
+ *
+
+ * TODO: use a series expansion when extremely close to the branch point
+ * at `-1/e` and make sure that the proper branch is chosen there.
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+#include "evalpoly.h"
+
+namespace xsf {
+constexpr double EXPN1 = 0.36787944117144232159553; // exp(-1)
+constexpr double OMEGA = 0.56714329040978387299997; // W(1, 0)
+
+namespace detail {
+    XSF_HOST_DEVICE inline std::complex lambertw_branchpt(std::complex z) {
+        // Series for W(z, 0) around the branch point; see 4.22 in [1].
+        double coeffs[] = {-1.0 / 3.0, 1.0, -1.0};
+        std::complex p = std::sqrt(2.0 * (M_E * z + 1.0));
+
+        return cevalpoly(coeffs, 2, p);
+    }
+
+    XSF_HOST_DEVICE inline std::complex lambertw_pade0(std::complex z) {
+        // (3, 2) Pade approximation for W(z, 0) around 0.
+        double num[] = {12.85106382978723404255, 12.34042553191489361902, 1.0};
+        double denom[] = {32.53191489361702127660, 14.34042553191489361702, 1.0};
+
+        /* This only gets evaluated close to 0, so we don't need a more
+         * careful algorithm that avoids overflow in the numerator for
+         * large z. */
+        return z * cevalpoly(num, 2, z) / cevalpoly(denom, 2, z);
+    }
+
+    XSF_HOST_DEVICE inline std::complex lambertw_asy(std::complex z, long k) {
+        /* Compute the W function using the first two terms of the
+         * asymptotic series. See 4.20 in [1].
+         */
+        std::complex w = std::log(z) + 2.0 * M_PI * k * std::complex(0, 1);
+        return w - std::log(w);
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, double tol) {
+    double absz;
+    std::complex w;
+    std::complex ew, wew, wewz, wn;
+
+    if (std::isnan(z.real()) || std::isnan(z.imag())) {
+        return z;
+    }
+    if (z.real() == std::numeric_limits::infinity()) {
+        return z + 2.0 * M_PI * k * std::complex(0, 1);
+    }
+    if (z.real() == -std::numeric_limits::infinity()) {
+        return -z + (2.0 * M_PI * k + M_PI) * std::complex(0, 1);
+    }
+    if (z == 0.0) {
+        if (k == 0) {
+            return z;
+        }
+        set_error("lambertw", SF_ERROR_SINGULAR, NULL);
+        return -std::numeric_limits::infinity();
+    }
+    if (z == 1.0 && k == 0) {
+        // Split out this case because the asymptotic series blows up
+        return OMEGA;
+    }
+
+    absz = std::abs(z);
+    // Get an initial guess for Halley's method
+    if (k == 0) {
+        if (std::abs(z + EXPN1) < 0.3) {
+            w = detail::lambertw_branchpt(z);
+        } else if (-1.0 < z.real() && z.real() < 1.5 && std::abs(z.imag()) < 1.0 &&
+                   -2.5 * std::abs(z.imag()) - 0.2 < z.real()) {
+            /* Empirically determined decision boundary where the Pade
+             * approximation is more accurate. */
+            w = detail::lambertw_pade0(z);
+        } else {
+            w = detail::lambertw_asy(z, k);
+        }
+    } else if (k == -1) {
+        if (absz <= EXPN1 && z.imag() == 0.0 && z.real() < 0.0) {
+            w = std::log(-z.real());
+        } else {
+            w = detail::lambertw_asy(z, k);
+        }
+    } else {
+        w = detail::lambertw_asy(z, k);
+    }
+
+    // Halley's method; see 5.9 in [1]
+    if (w.real() >= 0) {
+        // Rearrange the formula to avoid overflow in exp
+        for (int i = 0; i < 100; i++) {
+            ew = std::exp(-w);
+            wewz = w - z * ew;
+            wn = w - wewz / (w + 1.0 - (w + 2.0) * wewz / (2.0 * w + 2.0));
+            if (std::abs(wn - w) <= tol * std::abs(wn)) {
+                return wn;
+            }
+            w = wn;
+        }
+    } else {
+        for (int i = 0; i < 100; i++) {
+            ew = std::exp(w);
+            wew = w * ew;
+            wewz = wew - z;
+            wn = w - wewz / (wew + ew - (w + 2.0) * wewz / (2.0 * w + 2.0));
+            if (std::abs(wn - w) <= tol * std::abs(wn)) {
+                return wn;
+            }
+            w = wn;
+        }
+    }
+
+    set_error("lambertw", SF_ERROR_SLOW, "iteration failed to converge: %g + %gj", z.real(), z.imag());
+    return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+}
+
+XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, float tol) {
+    return static_cast>(
+        lambertw(static_cast>(z), k, static_cast(tol)));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..eaae479b2054177153b8671e7fe3174f1b09f20a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h
@@ -0,0 +1,163 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header comment appears below.
+ */
+
+/* An implementation of the principal branch of the logarithm of
+ * Gamma. Also contains implementations of Gamma and 1/Gamma which are
+ * easily computed from log-Gamma.
+ *
+ * Author: Josh Wilson
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * References
+ * ----------
+ * [1] Hare, "Computing the Principal Branch of log-Gamma",
+ *     Journal of Algorithms, 1997.
+ *
+ * [2] Julia,
+ *     https://github.com/JuliaLang/julia/blob/master/base/special/gamma.jl
+ */
+
+#pragma once
+
+#include "cephes/gamma.h"
+#include "cephes/rgamma.h"
+#include "config.h"
+#include "error.h"
+#include "evalpoly.h"
+#include "trig.h"
+#include "zlog1.h"
+
+namespace xsf {
+
+namespace detail {
+    constexpr double loggamma_SMALLX = 7;
+    constexpr double loggamma_SMALLY = 7;
+    constexpr double loggamma_HLOG2PI = 0.918938533204672742;      // log(2*pi)/2
+    constexpr double loggamma_LOGPI = 1.1447298858494001741434262; // log(pi)
+    constexpr double loggamma_TAYLOR_RADIUS = 0.2;
+
+    XSF_HOST_DEVICE std::complex loggamma_stirling(std::complex z) {
+        /* Stirling series for log-Gamma
+         *
+         * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the
+         * (2*n)th Bernoulli number. See (1.1) in [1].
+         */
+        double coeffs[] = {-2.955065359477124183E-2,  6.4102564102564102564E-3, -1.9175269175269175269E-3,
+                           8.4175084175084175084E-4,  -5.952380952380952381E-4, 7.9365079365079365079E-4,
+                           -2.7777777777777777778E-3, 8.3333333333333333333E-2};
+        std::complex rz = 1.0 / z;
+        std::complex rzz = rz / z;
+
+        return (z - 0.5) * std::log(z) - z + loggamma_HLOG2PI + rz * cevalpoly(coeffs, 7, rzz);
+    }
+
+    XSF_HOST_DEVICE std::complex loggamma_recurrence(std::complex z) {
+        /* Backward recurrence relation.
+         *
+         * See Proposition 2.2 in [1] and the Julia implementation [2].
+         *
+         */
+        int signflips = 0;
+        int sb = 0;
+        std::complex shiftprod = z;
+
+        z += 1.0;
+        int nsb;
+        while (z.real() <= loggamma_SMALLX) {
+            shiftprod *= z;
+            nsb = std::signbit(shiftprod.imag());
+            signflips += nsb != 0 && sb == 0 ? 1 : 0;
+            sb = nsb;
+            z += 1.0;
+        }
+        return loggamma_stirling(z) - std::log(shiftprod) - signflips * 2 * M_PI * std::complex(0, 1);
+    }
+
+    XSF_HOST_DEVICE std::complex loggamma_taylor(std::complex z) {
+        /* Taylor series for log-Gamma around z = 1.
+         *
+         * It is
+         *
+         * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ...
+         *
+         * where gamma is the Euler-Mascheroni constant.
+         */
+
+        double coeffs[] = {
+            -4.3478266053040259361E-2, 4.5454556293204669442E-2, -4.7619070330142227991E-2, 5.000004769810169364E-2,
+            -5.2631679379616660734E-2, 5.5555767627403611102E-2, -5.8823978658684582339E-2, 6.2500955141213040742E-2,
+            -6.6668705882420468033E-2, 7.1432946295361336059E-2, -7.6932516411352191473E-2, 8.3353840546109004025E-2,
+            -9.0954017145829042233E-2, 1.0009945751278180853E-1, -1.1133426586956469049E-1, 1.2550966952474304242E-1,
+            -1.4404989676884611812E-1, 1.6955717699740818995E-1, -2.0738555102867398527E-1, 2.7058080842778454788E-1,
+            -4.0068563438653142847E-1, 8.2246703342411321824E-1, -5.7721566490153286061E-1};
+
+        z -= 1.0;
+        return z * cevalpoly(coeffs, 22, z);
+    }
+} // namespace detail
+
+XSF_HOST_DEVICE inline double loggamma(double x) {
+    if (x < 0.0) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    return cephes::lgam(x);
+}
+
+XSF_HOST_DEVICE inline float loggamma(float x) { return loggamma(static_cast(x)); }
+
+XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) {
+    // Compute the principal branch of log-Gamma
+
+    if (std::isnan(z.real()) || std::isnan(z.imag())) {
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (z.real() <= 0 and z == std::floor(z.real())) {
+        set_error("loggamma", SF_ERROR_SINGULAR, NULL);
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (z.real() > detail::loggamma_SMALLX || std::abs(z.imag()) > detail::loggamma_SMALLY) {
+        return detail::loggamma_stirling(z);
+    }
+    if (std::abs(z - 1.0) < detail::loggamma_TAYLOR_RADIUS) {
+        return detail::loggamma_taylor(z);
+    }
+    if (std::abs(z - 2.0) < detail::loggamma_TAYLOR_RADIUS) {
+        // Recurrence relation and the Taylor series around 1.
+        return detail::zlog1(z - 1.0) + detail::loggamma_taylor(z - 1.0);
+    }
+    if (z.real() < 0.1) {
+        // Reflection formula; see Proposition 3.1 in [1]
+        double tmp = std::copysign(2 * M_PI, z.imag()) * std::floor(0.5 * z.real() + 0.25);
+        return std::complex(detail::loggamma_LOGPI, tmp) - std::log(sinpi(z)) - loggamma(1.0 - z);
+    }
+    if (std::signbit(z.imag()) == 0) {
+        // z.imag() >= 0 but is not -0.0
+        return detail::loggamma_recurrence(z);
+    }
+    return std::conj(detail::loggamma_recurrence(std::conj(z)));
+}
+
+XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) {
+    return static_cast>(loggamma(static_cast>(z)));
+}
+
+XSF_HOST_DEVICE inline double rgamma(double z) { return cephes::rgamma(z); }
+
+XSF_HOST_DEVICE inline float rgamma(float z) { return rgamma(static_cast(z)); }
+
+XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) {
+    // Compute 1/Gamma(z) using loggamma.
+    if (z.real() <= 0 && z == std::floor(z.real())) {
+        // Zeros at 0, -1, -2, ...
+        return 0.0;
+    }
+    return std::exp(-loggamma(z));
+}
+
+XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) {
+    return static_cast>(rgamma(static_cast>(z)));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h
new file mode 100644
index 0000000000000000000000000000000000000000..4d26b64e02aa3f65a97d99160047efd76e7f121d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h
@@ -0,0 +1,200 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of sin/cos/sinh/cosh integrals for complex arguments
+ *
+ * Sources
+ * [1] Fredrik Johansson and others. mpmath: a Python library for
+ *     arbitrary-precision floating-point arithmetic (version 0.19),
+ *     December 2013. http://mpmath.org/.
+ * [2] NIST, "Digital Library of Mathematical Functions",
+ *     https://dlmf.nist.gov/
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+#include "expint.h"
+#include "cephes/const.h"
+#include "cephes/sici.h"
+#include "cephes/shichi.h"
+
+namespace xsf {
+namespace detail {
+    
+    XSF_HOST_DEVICE inline void sici_power_series(int sgn, std::complex z,
+						       std::complex *s, std::complex *c) {
+	/* DLMF 6.6.5 and 6.6.6. If sgn = -1 computes si/ci, and if sgn = 1
+	 * computes shi/chi.
+	 */        
+	std::complex fac = z;
+	*s = fac;
+	*c = 0;
+	std::complex term1, term2;
+	for (int n = 1; n < 100; n++) {
+	    fac *= static_cast(sgn)*z/(2.0*n);
+	    term2 = fac/(2.0*n);
+	    *c += term2;
+	    fac *= z/(2.0*n + 1.0);
+	    term1 = fac/(2.0*n + 1.0);
+	    *s += term1;
+	    constexpr double tol = std::numeric_limits::epsilon();
+	    if (std::abs(term1) < tol*std::abs(*s) && std::abs(term2) < tol*std::abs(*c)) {
+		break;
+	    }
+	}
+    }
+
+}
+
+    
+XSF_HOST_DEVICE inline int sici(std::complex z,
+				    std::complex *si, std::complex *ci) {
+    /* Compute sin/cos integrals at complex arguments. The algorithm
+     * largely follows that of [1].
+     */
+
+    constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
+
+    if (z == std::numeric_limits::infinity()) {
+        *si = M_PI_2;
+        *ci = 0;
+        return 0;
+    }
+    if (z == -std::numeric_limits::infinity()) {
+	*si = -M_PI_2;
+        *ci = {0.0, M_PI};
+        return 0;
+    }
+
+    if (std::abs(z) < 0.8) {
+        // Use the series to avoid cancellation in si
+	detail::sici_power_series(-1, z, si, ci);
+
+        if (z == 0.0) {
+            set_error("sici", SF_ERROR_DOMAIN, NULL);
+            *ci = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()};
+        } else {
+            *ci += EULER + std::log(z);
+	}
+        return 0;
+    }
+    
+    // DLMF 6.5.5/6.5.6 plus DLMF 6.4.4/6.4.6/6.4.7
+    std::complex jz = std::complex(0.0, 1.0) * z;
+    std::complex term1 = expi(jz);
+    std::complex term2 = expi(-jz);
+    *si = std::complex(0.0, -0.5)*(term1 - term2);
+    *ci = 0.5*(term1 + term2);
+    if (z.real() == 0) {
+        if (z.imag() > 0) {
+            *ci += std::complex(0.0, M_PI_2);
+	} else if (z.imag() < 0) {
+            *ci -= std::complex(0.0, M_PI_2);
+	}
+    } else if (z.real() > 0) {
+        *si -= M_PI_2;
+    } else {
+        *si += M_PI_2;
+        if (z.imag() >= 0) {
+            *ci += std::complex(0.0, M_PI);
+        } else {
+            *ci -= std::complex(0.0, M_PI);
+	}
+    }
+    return 0;
+}
+
+XSF_HOST_DEVICE inline int sici(std::complex z,
+				    std::complex *si_f, std::complex *ci_f) {
+    std::complex si;
+    std::complex ci;
+    int res = sici(z, &si, &ci);
+    *si_f = si;
+    *ci_f = ci;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int shichi(std::complex z,
+				       std::complex *shi, std::complex *chi) {
+    /* Compute sinh/cosh integrals at complex arguments. The algorithm
+     * largely follows that of [1].
+     */
+    constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
+    if (z == std::numeric_limits::infinity()) {
+        *shi = std::numeric_limits::infinity();
+        *chi = std::numeric_limits::infinity();
+        return 0;
+    }
+    if (z == -std::numeric_limits::infinity()) {
+        *shi = -std::numeric_limits::infinity();
+        *chi = std::numeric_limits::infinity();
+        return 0;
+    }
+    if (std::abs(z) < 0.8) {
+        // Use the series to avoid cancellation in shi
+	detail::sici_power_series(1, z, shi, chi);
+        if (z == 0.0) {
+            set_error("shichi", SF_ERROR_DOMAIN, NULL);
+            *chi = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()};
+        } else {
+            *chi += EULER + std::log(z);
+	}
+	return 0;
+    }
+
+    std::complex term1 = expi(z);
+    std::complex term2 = expi(-z);
+    *shi = 0.5*(term1 - term2);
+    *chi = 0.5*(term1 + term2);
+    if (z.imag() > 0) {
+        *shi -= std::complex(0.0, 0.5*M_PI);
+        *chi += std::complex(0.0, 0.5*M_PI);
+    } else if (z.imag() < 0) {
+        *shi += std::complex(0.0, 0.5*M_PI);
+        *chi -= std::complex(0.0, 0.5*M_PI);
+    } else if (z.real() < 0) {
+        *chi += std::complex(0.0, M_PI);
+    }
+    return 0;
+}
+
+XSF_HOST_DEVICE inline int shichi(std::complex z,
+				    std::complex *shi_f, std::complex *chi_f) {
+    std::complex shi;
+    std::complex chi;
+    int res = shichi(z, &shi, &chi);
+    *shi_f = shi;
+    *chi_f = chi;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
+    return cephes::sici(x, si, ci);
+}
+
+XSF_HOST_DEVICE inline int shichi(double x, double *shi, double *chi) {
+    return cephes::shichi(x, shi, chi);
+}
+
+XSF_HOST_DEVICE inline int sici(float x, float *si_f, float *ci_f) {
+    double si;
+    double ci;
+    int res = cephes::sici(x, &si, &ci);
+    *si_f = si;
+    *ci_f = ci;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int shichi(float x, float *shi_f, float *chi_f) {
+    double shi;
+    double chi;
+    int res = cephes::shichi(x, &shi, &chi);
+    *shi_f = shi;
+    *chi_f = chi;
+    return res;
+}
+}
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h
new file mode 100644
index 0000000000000000000000000000000000000000..e349f6a5fb4f45b4718cb746dd7b0b2c1fd23ddd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h
@@ -0,0 +1,427 @@
+/* Building blocks for implementing special functions */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+namespace xsf {
+namespace detail {
+
+    /* Result type of a "generator", a callable object that produces a value
+     * each time it is called.
+     */
+    template 
+    using generator_result_t = typename std::decay::type>::type;
+
+    /* Used to deduce the type of the numerator/denominator of a fraction. */
+    template 
+    struct pair_traits;
+
+    template 
+    struct pair_traits> {
+        using value_type = T;
+    };
+
+    template 
+    using pair_value_t = typename pair_traits::value_type;
+
+    /* Used to extract the "value type" of a complex type. */
+    template 
+    struct real_type {
+        using type = T;
+    };
+
+    template 
+    struct real_type> {
+        using type = T;
+    };
+
+    template 
+    using real_type_t = typename real_type::type;
+
+    // Return NaN, handling both real and complex types.
+    template 
+    XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    template 
+    XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() {
+        using V = typename T::value_type;
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+
+    // Series evaluators.
+    template >
+    XSF_HOST_DEVICE T
+    series_eval(Generator &g, T init_val, real_type_t tol, std::uint64_t max_terms, const char *func_name) {
+        /* Sum an infinite series to a given precision.
+         *
+         * g : a generator of terms for the series.
+         *
+         * init_val : A starting value that terms are added to. This argument determines the
+         *     type of the result.
+         *
+         * tol : relative tolerance for stopping criterion.
+         *
+         * max_terms : The maximum number of terms to add before giving up and declaring
+         *     non-convergence.
+         *
+         * func_name : The name of the function within SciPy where this call to series_eval
+         *     will ultimately be used. This is needed to pass to set_error in case
+         *     of non-convergence.
+         */
+        T result = init_val;
+        T term;
+        for (std::uint64_t i = 0; i < max_terms; ++i) {
+            term = g();
+            result += term;
+            if (std::abs(term) < std::abs(result) * tol) {
+                return result;
+            }
+        }
+        // Exceeded max terms without converging. Return NaN.
+        set_error(func_name, SF_ERROR_NO_RESULT, NULL);
+        return maybe_complex_NaN();
+    }
+
+    template >
+    XSF_HOST_DEVICE T series_eval_fixed_length(Generator &g, T init_val, std::uint64_t num_terms) {
+        /* Sum a fixed number of terms from a series.
+         *
+         * g : a generator of terms for the series.
+         *
+         * init_val : A starting value that terms are added to. This argument determines the
+         *     type of the result.
+         *
+         * max_terms : The number of terms from the series to sum.
+         *
+         */
+        T result = init_val;
+        for (std::uint64_t i = 0; i < num_terms; ++i) {
+            result += g();
+        }
+        return result;
+    }
+
+    /* Performs one step of Kahan summation. */
+    template 
+    XSF_HOST_DEVICE void kahan_step(T &sum, T &comp, T x) {
+        T y = x - comp;
+        T t = sum + y;
+        comp = (t - sum) - y;
+        sum = t;
+    }
+
+    /* Evaluates an infinite series using Kahan summation.
+     *
+     * Denote the series by
+     *
+     *   S = a[0] + a[1] + a[2] + ...
+     *
+     * And for n = 0, 1, 2, ..., denote its n-th partial sum by
+     *
+     *   S[n] = a[0] + a[1] + ... + a[n]
+     *
+     * This function computes S[0], S[1], ... until a[n] is sufficiently
+     * small or if the maximum number of terms have been evaluated.
+     *
+     * Parameters
+     * ----------
+     *   g
+     *       Reference to generator that yields the sequence of values a[1],
+     *       a[2], a[3], ...
+     *
+     *   tol
+     *       Relative tolerance for convergence.  Specifically, stop iteration
+     *       as soon as `abs(a[n]) <= tol * abs(S[n])` for some n >= 1.
+     *
+     *   max_terms
+     *       Maximum number of terms after a[0] to evaluate.  It should be set
+     *       large enough such that the convergence criterion is guaranteed
+     *       to have been satisfied within that many terms if there is no
+     *       rounding error.
+     *
+     *   init_val
+     *       a[0].  Default is zero.  The type of this parameter (T) is used
+     *       for intermediary computations as well as the result.
+     *
+     * Return Value
+     * ------------
+     * If the convergence criterion is satisfied by some `n <= max_terms`,
+     * returns `(S[n], n)`.  Otherwise, returns `(S[max_terms], 0)`.
+     */
+    template >
+    XSF_HOST_DEVICE std::pair
+    series_eval_kahan(Generator &&g, real_type_t tol, std::uint64_t max_terms, T init_val = T(0)) {
+
+        using std::abs;
+        T sum = init_val;
+        T comp = T(0);
+        for (std::uint64_t i = 0; i < max_terms; ++i) {
+            T term = g();
+            kahan_step(sum, comp, term);
+            if (abs(term) <= tol * abs(sum)) {
+                return {sum, i + 1};
+            }
+        }
+        return {sum, 0};
+    }
+
+    /* Generator that yields the difference of successive convergents of a
+     * continued fraction.
+     *
+     * Let f[n] denote the n-th convergent of a continued fraction:
+     *
+     *                 a[1]   a[2]       a[n]
+     *   f[n] = b[0] + ------ ------ ... ----
+     *                 b[1] + b[2] +     b[n]
+     *
+     * with f[0] = b[0].  This generator yields the sequence of values
+     * f[1]-f[0], f[2]-f[1], f[3]-f[2], ...
+     *
+     * Constructor Arguments
+     * ---------------------
+     *   cf
+     *       Reference to generator that yields the terms of the continued
+     *       fraction as (numerator, denominator) pairs, starting from
+     *       (a[1], b[1]).
+     *
+     *       `cf` must outlive the ContinuedFractionSeriesGenerator object.
+     *
+     *       The constructed object always eagerly retrieves the next term
+     *       of the continued fraction.  Specifically, (a[1], b[1]) is
+     *       retrieved upon construction, and (a[n], b[n]) is retrieved after
+     *       (n-1) calls of `()`.
+     *
+     * Type Arguments
+     * --------------
+     *   T
+     *       Type in which computations are performed and results are turned.
+     *
+     * Remarks
+     * -------
+     * The series is computed using the recurrence relation described in [1].
+     * Let v[n], n >= 1 denote the terms of the series.  Then
+     *
+     *   v[1] = a[1] / b[1]
+     *   v[n] = v[n-1] * r[n-1], n >= 2
+     *
+     * where
+     *
+     *                              -(a[n] + a[n] * r[n-1])
+     *   r[1] = 0,  r[n] = ------------------------------------------, n >= 2
+     *                      (a[n] + a[n] * r[n-1]) + (b[n] * b[n-1])
+     *
+     * No error checking is performed.  The caller must ensure that all terms
+     * are finite and that intermediary computations do not trigger floating
+     * point exceptions such as overflow.
+     *
+     * The numerical stability of this method depends on the characteristics
+     * of the continued fraction being evaluated.
+     *
+     * Reference
+     * ---------
+     * [1] Gautschi, W. (1967). “Computational Aspects of Three-Term
+     *     Recurrence Relations.” SIAM Review, 9(1):24-82.
+     */
+    template >>
+    class ContinuedFractionSeriesGenerator {
+
+      public:
+        XSF_HOST_DEVICE explicit ContinuedFractionSeriesGenerator(Generator &cf) : cf_(cf) { init(); }
+
+        XSF_HOST_DEVICE T operator()() {
+            T v = v_;
+            advance();
+            return v;
+        }
+
+      private:
+        XSF_HOST_DEVICE void init() {
+            auto [num, denom] = cf_();
+            T a = num;
+            T b = denom;
+            r_ = T(0);
+            v_ = a / b;
+            b_ = b;
+        }
+
+        XSF_HOST_DEVICE void advance() {
+            auto [num, denom] = cf_();
+            T a = num;
+            T b = denom;
+            T p = a + a * r_;
+            T q = p + b * b_;
+            r_ = -p / q;
+            v_ = v_ * r_;
+            b_ = b;
+        }
+
+        Generator &cf_; // reference to continued fraction generator
+        T v_;           // v[n] == f[n] - f[n-1], n >= 1
+        T r_;           // r[1] = 0, r[n] = v[n]/v[n-1], n >= 2
+        T b_;           // last denominator, i.e. b[n-1]
+    };
+
+    /* Converts a continued fraction into a series whose terms are the
+     * difference of its successive convergents.
+     *
+     * See ContinuedFractionSeriesGenerator for details.
+     */
+    template >>
+    XSF_HOST_DEVICE ContinuedFractionSeriesGenerator continued_fraction_series(Generator &cf) {
+        return ContinuedFractionSeriesGenerator(cf);
+    }
+
+    /* Find initial bracket for a bracketing scalar root finder. A valid bracket is a pair of points a < b for
+     * which the signs of f(a) and f(b) differ. If f(x0) = 0, where x0 is the initial guess, this bracket finder
+     * will return the bracket (x0, x0). It is expected that the rootfinder will check if the bracket
+     * endpoints are roots.
+     *
+     * This is a private function intended specifically for the situation where
+     * the goal is to invert a CDF function F for a parametrized family of distributions with respect to one
+     * parameter, when the other parameters are known, and where F is monotonic with respect to the unknown parameter.
+     */
+    template 
+    XSF_HOST_DEVICE inline std::tuple bracket_root_for_cdf_inversion(
+        Function func, double x0, double xmin, double xmax, double step0_left,
+        double step0_right, double factor_left, double factor_right, bool increasing, std::uint64_t maxiter
+    ) {
+        double y0 = func(x0);
+
+        if (y0 == 0) {
+            // Initial guess is correct.
+            return {x0, x0, y0, y0, 0};
+        }
+
+        double y0_sgn = std::signbit(y0);
+
+        bool search_left;
+        /* The frontier is the new leading endpoint of the expanding bracket. The
+         * interior endpoint trails behind the frontier. In each step, the old frontier
+         * endpoint becomes the new interior endpoint. */
+        double interior, frontier, y_interior, y_frontier, y_interior_sgn, y_frontier_sgn, boundary, factor;
+        if ((increasing && y0 < 0) || (!increasing && y0 > 0)) {
+            /* If func is increasing  and func(x_right) < 0 or if func is decreasing and
+             *  f(y_right) > 0, we should expand the bracket to the right. */
+            interior = x0, y_interior = y0;
+            frontier = x0 + step0_right;
+            y_interior_sgn = y0_sgn;
+            search_left = false;
+            boundary = xmax;
+            factor = factor_right;
+        } else {
+            /* Otherwise we move and expand the bracket to the left. */
+            interior = x0, y_interior = y0;
+            frontier = x0 + step0_left;
+            y_interior_sgn = y0_sgn;
+            search_left = true;
+            boundary = xmin;
+            factor = factor_left;
+        }
+
+        bool reached_boundary = false;
+        for (std::uint64_t i = 0; i < maxiter; i++) {
+            y_frontier = func(frontier);
+            y_frontier_sgn = std::signbit(y_frontier);
+            if (y_frontier_sgn != y_interior_sgn || (y_frontier == 0.0)) {
+                /* Stopping condition, func evaluated at endpoints of bracket has opposing signs,
+                 * meeting requirement for bracketing root finder. (Or endpoint has reached a
+                 * zero.) */
+                if (search_left) {
+                    /* Ensure we return an interval (a, b) with a < b. */
+                    std::swap(interior, frontier);
+                    std::swap(y_interior, y_frontier);
+                }
+		return {interior, frontier, y_interior, y_frontier, 0};
+            }
+            if (reached_boundary) {
+                /* We've reached a boundary point without finding a root . */
+                return {
+                    std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+                    std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+                    search_left ? 1 : 2
+                };
+            }
+            double step = (frontier - interior) * factor;
+            interior = frontier;
+            y_interior = y_frontier;
+            y_interior_sgn = y_frontier_sgn;
+            frontier += step;
+            if ((search_left && frontier <= boundary) || (!search_left && frontier >= boundary)) {
+                /* If the frontier has reached the boundary, set a flag so the algorithm will know
+                 * not to search beyond this point. */
+                frontier = boundary;
+                reached_boundary = true;
+            }
+        }
+        /* Failed to converge within maxiter iterations. If maxiter is sufficiently high and
+         * factor_left and factor_right are set appropriately, this should only happen due to
+         * a bug in this function. Limiting the number of iterations is a defensive programming measure. */
+	return {
+            std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+            std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), 3
+        };
+    }
+
+    /* Find root of a scalar function using Chandrupatla's algorithm */
+    template 
+    XSF_HOST_DEVICE inline std::pair find_root_chandrupatla(
+        Function func, double x1, double x2, double f1, double f2, double rtol,
+        double atol, std::uint64_t maxiter
+    ) {
+        if (f1 == 0) {
+            return {x1, 0};
+        }
+        if (f2 == 0) {
+            return {x2, 0};
+        }
+        double t = 0.5, x3, f3;
+        for (uint64_t i = 0; i < maxiter; i++) {
+            double x = x1 + t * (x2 - x1);
+            double f = func(x);
+            if (std::signbit(f) == std::signbit(f1)) {
+                x3 = x1;
+                x1 = x;
+                f3 = f1;
+                f1 = f;
+            } else {
+                x3 = x2;
+                x2 = x1;
+                x1 = x;
+                f3 = f2;
+                f2 = f1;
+                f1 = f;
+            }
+            double xm, fm;
+            if (std::abs(f2) < std::abs(f1)) {
+                xm = x2;
+                fm = f2;
+            } else {
+                xm = x1;
+                fm = f1;
+            }
+            double tol = 2.0 * rtol * std::abs(xm) + 0.5 * atol;
+            double tl = tol / std::abs(x2 - x1);
+            if (tl > 0.5 || fm == 0) {
+                return {xm, 0};
+            }
+            double xi = (x1 - x2) / (x3 - x2);
+            double phi = (f1 - f2) / (f3 - f2);
+            double fl = 1.0 - std::sqrt(1.0 - xi);
+            double fh = std::sqrt(xi);
+
+            if ((fl < phi) && (phi < fh)) {
+                t = (f1 / (f2 - f1)) * (f3 / (f2 - f3)) + (f1 / (f3 - f1)) * (f2 / (f3 - f2)) * ((x3 - x1) / (x2 - x1));
+            } else {
+                t = 0.5;
+            }
+            t = std::fmin(std::fmax(t, tl), 1.0 - tl);
+        }
+        return {std::numeric_limits::quiet_NaN(), 1};
+    }
+
+} // namespace detail
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0221e00bbe358519c1586eb539310a5be6cddd1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h
@@ -0,0 +1,164 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+/* Implement sin(pi*z) and cos(pi*z) for complex z. Since the periods
+ * of these functions are integral (and thus better representable in
+ * floating point), it's possible to compute them with greater accuracy
+ * than sin(z), cos(z).
+ */
+
+#pragma once
+
+#include "cephes/sindg.h"
+#include "cephes/tandg.h"
+#include "cephes/trig.h"
+#include "cephes/unity.h"
+#include "config.h"
+#include "evalpoly.h"
+
+namespace xsf {
+
+template 
+XSF_HOST_DEVICE T sinpi(T x) {
+    return cephes::sinpi(x);
+}
+
+template 
+XSF_HOST_DEVICE std::complex sinpi(std::complex z) {
+    T x = z.real();
+    T piy = M_PI * z.imag();
+    T abspiy = std::abs(piy);
+    T sinpix = cephes::sinpi(x);
+    T cospix = cephes::cospi(x);
+
+    if (abspiy < 700) {
+        return {sinpix * std::cosh(piy), cospix * std::sinh(piy)};
+    }
+
+    /* Have to be careful--sinh/cosh could overflow while cos/sin are small.
+     * At this large of values
+     *
+     * cosh(y) ~ exp(y)/2
+     * sinh(y) ~ sgn(y)*exp(y)/2
+     *
+     * so we can compute exp(y/2), scale by the right factor of sin/cos
+     * and then multiply by exp(y/2) to avoid overflow. */
+    T exphpiy = std::exp(abspiy / 2);
+    T coshfac;
+    T sinhfac;
+    if (exphpiy == std::numeric_limits::infinity()) {
+        if (sinpix == 0.0) {
+            // Preserve the sign of zero.
+            coshfac = std::copysign(0.0, sinpix);
+        } else {
+            coshfac = std::copysign(std::numeric_limits::infinity(), sinpix);
+        }
+        if (cospix == 0.0) {
+            // Preserve the sign of zero.
+            sinhfac = std::copysign(0.0, cospix);
+        } else {
+            sinhfac = std::copysign(std::numeric_limits::infinity(), cospix);
+        }
+        return {coshfac, sinhfac};
+    }
+
+    coshfac = 0.5 * sinpix * exphpiy;
+    sinhfac = 0.5 * cospix * exphpiy;
+    return {coshfac * exphpiy, sinhfac * exphpiy};
+}
+
+template 
+XSF_HOST_DEVICE T cospi(T x) {
+    return cephes::cospi(x);
+}
+
+template 
+XSF_HOST_DEVICE std::complex cospi(std::complex z) {
+    T x = z.real();
+    T piy = M_PI * z.imag();
+    T abspiy = std::abs(piy);
+    T sinpix = cephes::sinpi(x);
+    T cospix = cephes::cospi(x);
+
+    if (abspiy < 700) {
+        return {cospix * std::cosh(piy), -sinpix * std::sinh(piy)};
+    }
+
+    // See csinpi(z) for an idea of what's going on here.
+    T exphpiy = std::exp(abspiy / 2);
+    T coshfac;
+    T sinhfac;
+    if (exphpiy == std::numeric_limits::infinity()) {
+        if (sinpix == 0.0) {
+            // Preserve the sign of zero.
+            coshfac = std::copysign(0.0, cospix);
+        } else {
+            coshfac = std::copysign(std::numeric_limits::infinity(), cospix);
+        }
+        if (cospix == 0.0) {
+            // Preserve the sign of zero.
+            sinhfac = std::copysign(0.0, sinpix);
+        } else {
+            sinhfac = std::copysign(std::numeric_limits::infinity(), sinpix);
+        }
+        return {coshfac, sinhfac};
+    }
+
+    coshfac = 0.5 * cospix * exphpiy;
+    sinhfac = 0.5 * sinpix * exphpiy;
+    return {coshfac * exphpiy, sinhfac * exphpiy};
+}
+
+template 
+XSF_HOST_DEVICE T sindg(T x) {
+    return cephes::sindg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float sindg(float x) {
+    return sindg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T cosdg(T x) {
+    return cephes::cosdg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float cosdg(float x) {
+    return cosdg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T tandg(T x) {
+    return cephes::tandg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float tandg(float x) {
+    return tandg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T cotdg(T x) {
+    return cephes::cotdg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float cotdg(float x) {
+    return cotdg(static_cast(x));
+}
+
+inline double radian(double d, double m, double s) { return cephes::radian(d, m, s); }
+
+inline float radian(float d, float m, float s) {
+    return radian(static_cast(d), static_cast(m), static_cast(s));
+}
+
+inline double cosm1(double x) { return cephes::cosm1(x); }
+
+inline float cosm1(float x) { return cosm1(static_cast(x)); }
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h
new file mode 100644
index 0000000000000000000000000000000000000000..77cf165a0fc303a2ee425dff7083889908dcf887
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h
@@ -0,0 +1,843 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of Wright's generalized Bessel function Phi, see
+ * https://dlmf.nist.gov/10.46.E1
+ *
+ * Copyright: Christian Lorentzen
+ *
+ * Distributed under the same license as SciPy
+ *
+ *
+ * Implementation Overview:
+ *
+ * First, different functions are implemented valid for certain domains of the
+ * three arguments.
+ * Finally they are put together in wright_bessel. See the docstring of
+ * that function for more details.
+ */
+
+#pragma once
+
+#include "cephes/lanczos.h"
+#include "cephes/polevl.h"
+#include "cephes/rgamma.h"
+#include "config.h"
+#include "digamma.h"
+#include "error.h"
+
+namespace xsf {
+
+namespace detail {
+    // rgamma_zero: smallest value x for which rgamma(x) == 0 as x gets large
+    constexpr double rgamma_zero = 178.47241115886637;
+
+    XSF_HOST_DEVICE inline double exp_rgamma(double x, double y) {
+        /* Compute exp(x) / gamma(y) = exp(x) * rgamma(y).
+         *
+         * This helper function avoids overflow by using the lanczos
+         * approximation of the gamma function.
+         */
+        return std::exp(x + (1 - std::log(y + cephes::lanczos_g - 0.5)) * (y - 0.5)) /
+               cephes::lanczos_sum_expg_scaled(y);
+    }
+
+    XSF_HOST_DEVICE inline double wb_series(double a, double b, double x, unsigned int nstart, unsigned int nstop) {
+        /* 1. Taylor series expansion in x=0 for x <= 1.
+         *
+         * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b)
+         *
+         * Note that every term, and therefore also Phi(a, b, x) is
+         * monotone decreasing with increasing a or b.
+         */
+        double xk_k = std::pow(x, nstart) * cephes::rgamma(nstart + 1); // x^k/k!
+        double res = xk_k * cephes::rgamma(nstart * a + b);
+        // term k=nstart+1, +2, +3, ...
+        if (nstop > nstart) {
+            // series expansion until term k such that a*k+b <= rgamma_zero
+            unsigned int k_max = std::floor((rgamma_zero - b) / a);
+            if (nstop > k_max) {
+                nstop = k_max;
+            }
+            for (unsigned int k = nstart + 1; k < nstop; k++) {
+                xk_k *= x / k;
+                res += xk_k * cephes::rgamma(a * k + b);
+            }
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_large_a(double a, double b, double x, int n) {
+        /* 2. Taylor series expansion in x=0, for large a.
+         *
+         * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b)
+         *
+         * Use Stirling's formula to find k=k_max, the maximum term.
+         * Then use n terms of Taylor series around k_max.
+         */
+        int k_max = static_cast(std::pow(std::pow(a, -a) * x, 1.0 / (1 + a)));
+
+        int nstart = k_max - n / 2;
+        if (nstart < 0) {
+            nstart = 0;
+        }
+
+        double res = 0;
+        double lnx = std::log(x);
+        // For numerical stability, we factor out the maximum term exp(..) with k=k_max
+        // but only if it is larger than 0.
+        double max_exponent = std::fmax(0, k_max * lnx - cephes::lgam(k_max + 1) - cephes::lgam(a * k_max + b));
+        for (int k = nstart; k < nstart + n; k++) {
+            res += std::exp(k * lnx - cephes::lgam(k + 1) - cephes::lgam(a * k + b) - max_exponent);
+        }
+
+        if (!log_wb) {
+            res *= std::exp(max_exponent);
+        } else {
+            // logarithm of Wright's function
+            res = max_exponent + std::log(res);
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_small_a(double a, double b, double x, int order) {
+        /* 3. Taylor series in a=0 up to order 5, for tiny a and not too large x
+         *
+         * Phi(a, b, x) = exp(x)/Gamma(b)
+                          * (1 - a*x * Psi(b) + a^2/2*x*(1+x) * (Psi(b)^2 - Psi'(b)
+                             + ... )
+                          + O(a^6))
+         *
+         * where Psi is the digamma function.
+         *
+         * Parameter order takes effect only when b > 1e-3 and 2 <= order <= 5,
+         * otherwise it defaults to 2, or if b <= 1e-3, to 5. The lower order is,
+         * the fewer polygamma functions have to be computed.
+         *
+         * Call: python _precompute/wright_bessel.py 1
+         *
+         * For small b, i.e. b <= 1e-3, cancellation of poles of digamma(b)/Gamma(b)
+         * and polygamma needs to be carried out => series expansion in a=0 to order 5
+         * and in b=0 to order 4.
+         * Call: python _precompute/wright_bessel.py 2
+         */
+        double A[6]; // coefficients of a^k  (1, -x * Psi(b), ...)
+        double B[6]; // powers of b^k/k! or terms in polygamma functions
+        constexpr double C[5] = {  // coefficients of a^k1 * b^k2
+            1.0000000000000000,   // C[0]
+            1.1544313298030657,   // C[1]
+            -3.9352684291215233,  // C[2]
+            -1.0080632408182857,  // C[3]
+            19.984633365874979,   // C[4]
+        };
+        double X[6] = {  // polynomials in x;
+            1,  // X[0]
+            x,  // X[1]
+            x * (x + 1),  // X[2]
+            x * (x * (x + 3) + 1),  // X[3]
+            x * (x * (x * (x + 6) + 7) + 1),  // X[4]
+            x * (x * (x * (x * (x + 10) + 25) + 15) + 1),  // X[5]
+        };
+        double res;
+
+        if (b <= 1E-3) {
+            /* Series expansion of both a and b up to order 5:
+             * M_PI = pi
+             * M_EG = Euler Gamma aka Euler Mascheroni constant
+             * M_Z3 = zeta(3)
+             * C[0] = 1
+             * C[1] = 2*M_EG
+             * C[2] = 3*M_EG^2 - M_PI^2/2
+             * C[3] = 4*M_EG^3 - 2*M_EG*M_PI^2 + 8*M_Z3
+             * C[4] = 5*M_EG^4 - 5*M_EG^2*M_PI^2 + 40*M_EG*M_Z3 + M_PI^4/12
+             */
+            B[0] = 1.;
+            for (int k = 1; k < 5; k++) {
+                B[k] = b / k * B[k - 1];
+            }
+            // Note that polevl assumes inverse ordering => A[5] = 0th term
+            A[5] = cephes::rgamma(b);
+            A[4] = X[1]        * (C[0] + C[1] * b + C[2] * B[2] + C[3] * B[3] + C[4] * B[4]);
+            A[3] = X[2] / 2.   * (C[1] + C[2] * b + C[3] * B[2] + C[4] * B[3]);
+            A[2] = X[3] / 6.   * (C[2] + C[3] * b + C[4] * B[2]);
+            A[1] = X[4] / 24.  * (C[3] + C[4] * b);
+            A[0] = X[5] / 120. * C[4];
+            // res = exp(x) * (A[5] + A[4] * a + A[3] * a^2 + A[2] * a^3 + ...)
+            if (!log_wb) {
+                res = exp(x) * cephes::polevl(a, A, 5);
+            } else {
+                // logarithm of Wright's function
+                res = x + std::log(cephes::polevl(a, A, 5));
+            }
+        } else {
+            /* Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)
+             * A[n] = a^n/n!
+             * But here, we repurpose A[n] = X[n] * B[n] / n!
+             * Note that polevl assumes inverse ordering => A[order] = 0th term */
+            double dg = digamma(b);
+            // pg1 = polygamma(1, b)
+            double pg1 = cephes::zeta(2, b);
+            if (order <= 2) {
+                res = 1 + a * x * (-dg + 0.5 * a * (1 + x) * (dg * dg - pg1));
+            } else {
+                if (order > 5) {
+                    order = 5;
+                }
+                // pg2 = polygamma(2, b)
+                double pg2 = -2 * cephes::zeta(3, b);
+                B[0] = 1;
+                B[1] = -dg;
+                B[2] = dg * dg - pg1;
+                B[3] = (-dg * dg + 3 * pg1) * dg - pg2;
+                A[order] = 1;
+                A[order - 1] = X[1] * B[1];
+                A[order - 2] = X[2] * B[2] / 2.;
+                A[order - 3] = X[3] * B[3] / 6.;
+                if (order >= 4) {
+                    // double pg3 = polygamma(3, b)
+                    double pg3 = 6 * cephes::zeta(4, b);
+                    B[4] = ((dg * dg - 6 * pg1) * dg + 4 * pg2) * dg + 3 * pg1 * pg1 - pg3;
+                    A[order - 4] = X[4] * B[4] / 24.;
+                    if (order >= 5) {
+                        // pg4 = polygamma(4, b)
+                        double pg4 = -24 * cephes::zeta(5, b);
+                        B[5] =
+                            ((((-dg * dg + 10 * pg1) * dg - 10 * pg2) * dg - 15 * pg1 * pg1 + 5 * pg3) * dg +
+                             10 * pg1 * pg2 - pg4);
+                        A[order - 5] = X[5] * B[5] / 120.;
+                    }
+                }
+                res = cephes::polevl(a, A, order);
+            }
+            // res *= exp(x) * rgamma(b)
+            if (!log_wb) {
+                res *= exp_rgamma(x, b);
+            } else {
+                // logarithm of Wright's function
+                res = x - cephes::lgam(b) + std::log(res);
+            }
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_asymptotic(double a, double b, double x) {
+        /* 4. Asymptotic expansion for large x up to order 8
+         *
+         * Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
+         *
+         * with Z = (a*x)^(1/(1+a)).
+         * Call: python _precompute/wright_bessel.py 3
+         */
+        double A[15];  // powers of a
+        double B[17];  // powers of b
+        double Ap1[9]; // powers of (1+a)
+        double C[9];   // coefficients of asymptotic series a_k
+
+        A[0] = 1.;
+        B[0] = 1.;
+        Ap1[0] = 1.;
+        for (int k = 1; k < 15; k++) {
+            A[k] = A[k - 1] * a;
+        }
+        for (int k = 1; k < 17; k++) {
+            B[k] = B[k - 1] * b;
+        }
+        for (int k = 1; k < 9; k++) {
+            Ap1[k] = Ap1[k - 1] * (1 + a);
+        }
+
+        C[0] = 1. / std::sqrt(2. * M_PI * Ap1[1]);
+
+        C[1] = C[0] / (24 * Ap1[1]);
+        C[1] *= (2 * a + 1) * (2 + a) - 12 * b * (1 + a - b);
+
+        C[2] = C[0] / (1152 * Ap1[2]);
+        C[2] *=
+            (144 * B[4] - 96 * B[3] * (5 * a + 1) + 24 * B[2] * (20 * A[2] + 5 * a - 4) -
+             24 * b * Ap1[1] * (6 * A[2] - 7 * a - 2) + (a + 2) * (2 * a + 1) * (2 * A[2] - 19 * a + 2));
+
+        C[3] = C[0] / (414720 * Ap1[3]);
+        C[3] *=
+            (8640 * B[6] - 8640 * B[5] * (7 * a - 1) + 10800 * B[4] * (14 * A[2] - 7 * a - 2) -
+             1440 * B[3] * (112 * A[3] - 147 * A[2] - 63 * a + 8) +
+             180 * B[2] * (364 * A[4] - 1288 * A[3] - 567 * A[2] + 392 * a + 76) -
+             180 * b * Ap1[1] * (20 * A[4] - 516 * A[3] + 417 * A[2] + 172 * a - 12) -
+             (a + 2) * (2 * a + 1) * (556 * A[4] + 1628 * A[3] - 9093 * A[2] + 1628 * a + 556));
+
+        C[4] = C[0] / (39813120 * Ap1[4]);
+        C[4] *=
+            (103680 * B[8] - 414720 * B[7] * (3 * a - 1) + 725760 * B[6] * a * (8 * a - 7) -
+             48384 * B[5] * (274 * A[3] - 489 * A[2] + 39 * a + 26) +
+             30240 * B[4] * (500 * A[4] - 1740 * A[3] + 495 * A[2] + 340 * a - 12) -
+             2880 * B[3] * (2588 * A[5] - 19780 * A[4] + 14453 * A[3] + 9697 * A[2] - 1892 * a - 404) +
+             48 * B[2] *
+                 (11488 * A[6] - 547836 * A[5] + 1007484 * A[4] + 593353 * A[3] - 411276 * A[2] - 114396 * a + 4288) +
+             48 * b * Ap1[1] *
+                 (7784 * A[6] + 48180 * A[5] - 491202 * A[4] + 336347 * A[3] + 163734 * A[2] - 28908 * a - 5560) -
+             (a + 2) * (2 * a + 1) *
+                 (4568 * A[6] - 226668 * A[5] - 465702 * A[4] + 2013479 * A[3] - 465702 * A[2] - 226668 * a + 4568));
+
+        C[5] = C[0] / (6688604160. * Ap1[5]);
+        C[5] *=
+            (1741824 * B[10] - 2903040 * B[9] * (11 * a - 5) + 2177280 * B[8] * (110 * A[2] - 121 * a + 14) -
+             580608 * B[7] * (1628 * A[3] - 3333 * A[2] + 1023 * a + 52) +
+             169344 * B[6] * (12364 * A[4] - 43648 * A[3] + 26763 * A[2] + 1232 * a - 788) -
+             24192 * B[5] * (104852 * A[5] - 646624 * A[4] + 721391 * A[3] - 16841 * A[2] - 74096 * a + 148) +
+             2016 * B[4] *
+                 (710248 * A[6] - 8878716 * A[5] + 17928834 * A[4] - 3333407 * A[3] - 4339566 * A[2] + 287364 * a +
+                  89128) -
+             1344 * B[3] *
+                 (87824 * A[7] - 7150220 * A[6] + 29202756 * A[5] - 15113527 * A[4] - 14223011 * A[3] + 3462492 * A[2] +
+                  1137092 * a - 18896) -
+             84 * B[2] *
+                 (1690480 * A[8] + 14139136 * A[7] - 232575464 * A[6] + 296712592 * A[5] + 215856619 * A[4] -
+                  152181392 * A[3] - 47718440 * A[2] + 5813632 * a + 943216) +
+             84 * b * Ap1[1] *
+                 (82224 * A[8] - 5628896 * A[7] - 26466520 * A[6] + 168779208 * A[5] - 104808005 * A[4] -
+                  56259736 * A[3] + 15879912 * A[2] + 4020640 * a - 63952) +
+             (a + 2) * (2 * a + 1) *
+                 (2622064 * A[8] + 12598624 * A[7] - 167685080 * A[6] - 302008904 * A[5] + 1115235367. * A[4] -
+                  302008904 * A[3] - 167685080 * A[2] + 12598624 * a + 2622064));
+
+        C[6] = C[0] / (4815794995200. * Ap1[6]);
+        C[6] *=
+            (104509440 * B[12] - 209018880 * B[11] * (13 * a - 7) + 574801920 * B[10] * (52 * A[2] - 65 * a + 12) -
+             63866880 * B[9] * (2834 * A[3] - 6279 * A[2] + 2769 * a - 134) +
+             23950080 * B[8] * (27404 * A[4] - 98228 * A[3] + 78663 * A[2] - 10868 * a - 1012) -
+             13685760 * B[7] * (105612 * A[5] - 599196 * A[4] + 791843 * A[3] - 224913 * A[2] - 27612 * a + 4540) +
+             2661120 * B[6] *
+                 (693680 * A[6] - 6473532 * A[5] + 13736424 * A[4] - 7047469 * A[3] - 723840 * A[2] + 471588 * a + 7376
+                 ) -
+             2661120 * B[5] *
+                 (432536 * A[7] - 7850804 * A[6] + 27531114 * A[5] - 24234457 * A[4] - 703001 * A[3] + 3633474 * A[2] -
+                  36244 * a - 45128) +
+             166320 * B[4] *
+                 (548912 * A[8] - 75660832 * A[7] + 502902712 * A[6] - 764807992 * A[5] + 91248287 * A[4] +
+                  217811464 * A[3] - 20365384 * A[2] - 9776416 * a + 37936) +
+             10080 * B[3] *
+                 (18759728 * A[9] + 165932208 * A[8] - 4710418440. * A[7] + 13686052536. * A[6] - 5456818809. * A[5] -
+                  6834514245. * A[4] + 1919299512. * A[3] + 752176152 * A[2] - 45661200 * a - 8616848) -
+             360 * B[2] *
+                 (32743360 * A[10] - 3381871792. * A[9] - 21488827776. * A[8] + 200389923864. * A[7] -
+                  198708005340. * A[6] - 171633799779. * A[5] + 123124874028. * A[4] + 40072774872. * A[3] -
+                  9137993280. * A[2] - 1895843248. * a + 18929728) -
+             360 * b * Ap1[1] *
+                 (57685408 * A[10] + 406929456 * A[9] - 6125375760. * A[8] - 27094918920. * A[7] +
+                  128752249410. * A[6] - 74866710561. * A[5] - 42917416470. * A[4] + 16256951352. * A[3] +
+                  4375268400. * A[2] - 316500688 * a - 47197152) +
+             (a + 2) * (2 * a + 1) *
+                 (167898208 * A[10] - 22774946512. * A[9] - 88280004528. * A[8] + 611863976472. * A[7] +
+                  1041430242126. * A[6] - 3446851131657. * A[5] + 1041430242126. * A[4] + 611863976472. * A[3] -
+                  88280004528. * A[2] - 22774946512. * a + 167898208));
+
+        C[7] = C[0] / (115579079884800. * Ap1[7]);
+        C[7] *=
+            (179159040 * B[14] - 1254113280. * B[13] * (5 * a - 3) + 1358622720. * B[12] * (70 * A[2] - 95 * a + 22) -
+             905748480 * B[11] * (904 * A[3] - 2109 * A[2] + 1119 * a - 112) +
+             1245404160. * B[10] * (3532 * A[4] - 12824 * A[3] + 11829 * A[2] - 2824 * a + 44) -
+             59304960 * B[9] * (256820 * A[5] - 1397680 * A[4] + 2025545 * A[3] - 869495 * A[2] + 52000 * a + 8788) +
+             14826240 * B[8] *
+                 (2274536 * A[6] - 18601572 * A[5] + 40698318 * A[4] - 28230079 * A[3] + 3916398 * A[2] + 832668 * a -
+                  65176) -
+             59304960 * B[7] *
+                 (760224 * A[7] - 9849164 * A[6] + 32495784 * A[5] - 34813869 * A[4] + 9175207 * A[3] + 1898688 * A[2] -
+                  469788 * a - 13184) +
+             25945920 * B[6] *
+                 (1167504 * A[8] - 28779840 * A[7] + 149752856 * A[6] - 246026112 * A[5] + 111944073 * A[4] +
+                  18341600 * A[3] - 12131496 * A[2] - 274368 * a + 102800) -
+             157248 * B[5] *
+                 (12341872 * A[9] - 3122991216. * A[8] + 29900054232. * A[7] - 78024816720. * A[6] +
+                  58914656739. * A[5] + 4637150811. * A[4] - 11523402480. * A[3] + 236218968 * A[2] + 337923216 * a +
+                  1592048) -
+             28080 * B[4] *
+                 (265154912 * A[10] + 2276098704. * A[9] - 105569461008. * A[8] + 496560666360. * A[7] -
+                  627891462858. * A[6] + 41935358025. * A[5] + 203913875814. * A[4] - 23984801544. * A[3] -
+                  13869306000. * A[2] + 372786832 * a + 103532640) +
+             1440 * B[3] *
+                 (310292864 * A[11] - 55169117872. * A[10] - 358957020112. * A[9] + 5714152556088. * A[8] -
+                  13241597459352. * A[7] + 4220720097141. * A[6] + 6845418090249. * A[5] - 2129559215808. * A[4] -
+                  909225098472. * A[3] + 107518582576. * A[2] + 25619444368. * a - 113832704) +
+             12 * B[2] *
+                 (135319651136. * A[12] + 1119107842176. * A[11] - 22193518174320. * A[10] - 133421793595520. * A[9] +
+                  860103051087996. * A[8] - 703353374803080. * A[7] - 704240127687381. * A[6] +
+                  513111704637960. * A[5] + 166909061348316. * A[4] - 57671564069120. * A[3] - 12453426246000. * A[2] +
+                  695901207936. * a + 93786157376.) -
+             12 * b * Ap1[1] *
+                 (4365353408. * A[12] - 720248637504. * A[11] - 4222331152560. * A[10] + 29413934270560. * A[9] +
+                  132123980710980. * A[8] - 511247376962820. * A[7] + 283403639131779. * A[6] +
+                  170415792320940. * A[5] - 79274388426588. * A[4] - 21009953050400. * A[3] + 3284035340880. * A[2] +
+                  589294339776. * a - 3693760576.) -
+             (a + 2) * (2 * a + 1) *
+                 (34221025984. * A[12] + 226022948160. * A[11] - 5067505612464. * A[10] - 18868361443936. * A[9] +
+                  86215425028308. * A[8] + 143500920544692. * A[7] - 437682618704613. * A[6] + 143500920544692. * A[5] +
+                  86215425028308. * A[4] - 18868361443936. * A[3] - 5067505612464. * A[2] + 226022948160. * a +
+                  34221025984.));
+
+        C[8] = C[0] / (22191183337881600. * Ap1[8]);
+        C[8] *=
+            (2149908480. * B[16] - 5733089280. * B[15] * (17 * a - 11) +
+             7166361600. * B[14] * (272 * A[2] - 391 * a + 104) -
+             3344302080. * B[13] * (6766 * A[3] - 16371 * A[2] + 9741 * a - 1306) +
+             1811496960. * B[12] * (93092 * A[4] - 341564 * A[3] + 344199 * A[2] - 104924 * a + 6308) -
+             517570560 * B[11] *
+                 (1626220 * A[5] - 8641508 * A[4] + 13274773 * A[3] - 6952303 * A[2] + 1007420 * a + 5564) +
+             284663808 * B[10] *
+                 (9979136 * A[6] - 75766892 * A[5] + 169256148 * A[4] - 136824959 * A[3] + 35714348 * A[2] -
+                  463692 * a - 293664) -
+             1423319040. * B[9] *
+                 (4466648 * A[7] - 49231116 * A[6] + 157507414 * A[5] - 187114257 * A[4] + 78372295 * A[3] -
+                  4470082 * A[2] - 1913996 * a + 82424) +
+             266872320 * B[8] *
+                 (33133136 * A[8] - 564264544 * A[7] + 2618606424. * A[6] - 4491310104. * A[5] + 2853943765. * A[4] -
+                  374694552 * A[3] - 135365288 * A[2] + 17623968 * a + 696912) -
+             2156544 * B[7] *
+                 (2914256144. * A[9] - 93491712432. * A[8] + 664876176984. * A[7] - 1661362937880. * A[6] +
+                  1563719627313. * A[5] - 382840842843. * A[4] - 115399415640. * A[3] + 34565562936. * A[2] +
+                  1609337232. * a - 217321904) +
+             179712 * B[6] *
+                 (1266018560. * A[10] - 789261834512. * A[9] + 10186841596896. * A[8] - 38877799073352. * A[7] +
+                  54334425968952. * A[6] - 22529574889533. * A[5] - 5132942328000. * A[4] + 3438377465592. * A[3] +
+                  84287641248. * A[2] - 72493479440. * a - 807415936) +
+             13824 * B[5] *
+                 (156356794976. * A[11] + 1180898077328. * A[10] - 90615270907936. * A[9] + 609258947056248. * A[8] -
+                  1312655191366722. * A[7] + 885900509321745. * A[6] + 112162151855265. * A[5] -
+                  212803071513258. * A[4] + 6805217831352. * A[3] + 10051742651296. * A[2] - 55035924848. * a -
+                  52946379296.) -
+             576 * B[4] *
+                 (143943926464. * A[12] - 60115486481856. * A[11] - 376366989757200. * A[10] +
+                  9534223075576160. * A[9] - 35603777465262396. * A[8] + 39375990156664980. * A[7] -
+                  868175004137259. * A[6] - 14279180718355020. * A[5] + 1985747535239364. * A[4] +
+                  1264001337603680. * A[3] - 75972792514320. * A[2] - 23855850572736. * a - 4996648256.) -
+             384 * B[3] *
+                 (2038525473856. * A[13] + 16057322146112. * A[12] - 502133360559024. * A[11] -
+                  2985686417468080. * A[10] + 32418922182093292. * A[9] - 63665380623022452. * A[8] +
+                  16481208821092575. * A[7] + 34161547357596099. * A[6] - 11490298497454932. * A[5] -
+                  5117272758337156. * A[4] + 933703210750480. * A[3] + 234855186762000. * A[2] - 7860524600000. * a -
+                  1226607567040.) +
+             96 * B[2] *
+                 (324439754752. * A[14] - 77231415197120. * A[13] - 539102931841856. * A[12] +
+                  4618258299956336. * A[11] + 28588485529469792. * A[10] - 141383982651179428. * A[9] +
+                  98783147840417772. * A[8] + 112831723492305801. * A[7] - 83329761150975036. * A[6] -
+                  26553582937192900. * A[5] + 12469117738765952. * A[4] + 2587165396642160. * A[3] -
+                  340406368038080. * A[2] - 53659641606080. * a + 219671272960.) +
+             96 * b * Ap1[1] *
+                 (1026630779520. * A[14] + 8781958472768. * A[13] - 210659786204384. * A[12] -
+                  1222283505284208. * A[11] + 5064251967491416. * A[10] + 24013052207628140. * A[9] -
+                  79710880160087370. * A[8] + 42596558293213227. * A[7] + 26570293386695790. * A[6] -
+                  14407831324576884. * A[5] - 3617322833922440. * A[4] + 950664948554384. * A[3] +
+                  172358006894496. * A[2] - 7430887938496. * a - 889746675584.) -
+             (a + 2) * (2 * a + 1) *
+                 (573840801152. * A[14] - 156998277198784. * A[13] - 898376974770592. * A[12] +
+                  8622589006459984. * A[11] + 32874204024803560. * A[10] - 111492707520083828. * A[9] -
+                  184768503480287646. * A[8] + 528612016938984183. * A[7] - 184768503480287646. * A[6] -
+                  111492707520083828. * A[5] + 32874204024803560. * A[4] + 8622589006459984. * A[3] -
+                  898376974770592. * A[2] - 156998277198784. * a + 573840801152.));
+
+        double Z = std::pow(a * x, 1 / Ap1[1]);
+        double Zp = 1.;
+        double res = C[0];
+        for (int k = 1; k < 9; k++) {
+            Zp /= Z;
+            res += (k % 2 == 0 ? 1 : -1) * C[k] * Zp;
+        }
+        if (!log_wb) {
+            res *= std::pow(Z, 0.5 - b) * std::exp(Ap1[1] / a * Z);
+        } else {
+            // logarithm of Wright's function
+            res = std::log(Z) * (0.5 - b) + Ap1[1] / a * Z + std::log(res);
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline double wb_Kmod(double exp_term, double eps, double a, double b, double x, double r) {
+        /* Compute integrand Kmod(eps, a, b, x, r) for Gauss-Laguerre quadrature.
+         *
+         * K(a, b, x, r+eps) = exp(-r-eps) * Kmod(eps, a, b, x, r)
+         * 
+         * Kmod(eps, a, b, x, r) = exp(x * (r+eps)^(-a) * cos(pi*a)) * (r+eps)^(-b)
+         *                       * sin(x * (r+eps)^(-a) * sin(pi*a) + pi * b)
+         * 
+         * Note that we additionally factor out exp(exp_term) which helps with large
+         * terms in the exponent of exp(...)
+         */
+        double x_r_a = x * std::pow(r + eps, -a);
+        return std::exp(x_r_a * cephes::cospi(a) + exp_term) * std::pow(r + eps, -b) *
+               std::sin(x_r_a * cephes::sinpi(a) + M_PI * b);
+    }
+
+    XSF_HOST_DEVICE inline double wb_P(double exp_term, double eps, double a, double b, double x, double phi) {
+        /* Compute integrand P for Gauss-Legendre quadrature.
+         *
+         * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi))
+         *                      * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi)
+         *                            + (1-b)*phi)
+         * 
+         * Note that we additionally factor out exp(exp_term) which helps with large
+         * terms in the exponent of exp(...)
+         */
+        double x_eps_a = x * std::pow(eps, -a);
+        return std::exp(eps * std::cos(phi) + x_eps_a * std::cos(a * phi) + exp_term) *
+               std::cos(eps * std::sin(phi) - x_eps_a * std::sin(a * phi) + (1 - b) * phi);
+    }
+
+    /* roots of laguerre polynomial of order 50
+     * scipy.special.roots_laguerre(50)[0] or
+     * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[0] */
+    constexpr double wb_x_laguerre[] = {
+        0.02863051833937908, 0.1508829356769337, 0.3709487815348964, 0.6890906998810479, 1.105625023539913,
+        1.620961751102501,   2.23561037591518,   2.950183366641835,  3.765399774405782,  4.682089387559285,
+        5.70119757478489,    6.823790909794551,  8.051063669390792,  9.384345308258407,  10.82510903154915,
+        12.37498160875746,   14.03575459982991,  15.80939719784467,  17.69807093335025,  19.70414653546156,
+        21.83022330657825,   24.0791514444115,   26.45405784125298,  28.95837601193738,  31.59588095662286,
+        34.37072996309045,   37.28751061055049,  40.35129757358607,  43.56772026999502,  46.94304399160304,
+        50.48426796312992,   54.19924488016862,  58.09682801724853,  62.18705417568891,  66.48137387844482,
+        70.99294482661949,   75.73701154772731,  80.73140480247769,  85.99721113646323,  91.55969041253388,
+        97.44956561485056,   103.7048912366923,  110.3738588076403,  117.5191982031112,  125.2254701334734,
+        133.6120279227287,   142.8583254892541,  153.2603719726036,  165.3856433166825,  180.6983437092145
+    };
+    /* weights for laguerre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[1] */
+    constexpr double wb_w_laguerre[] = {
+        0.07140472613518988,   0.1471486069645884,    0.1856716275748313,    0.1843853825273539,
+        0.1542011686063556,    0.1116853699022688,    0.07105288549019586,   0.04002027691150833,
+        0.02005062308007171,   0.008960851203646281,  0.00357811241531566,   0.00127761715678905,
+        0.0004080302449837189, 0.0001165288322309724, 2.974170493694165e-5,  6.777842526542028e-6,
+        1.37747950317136e-6,   2.492886181720092e-7,  4.010354350427827e-8,  5.723331748141425e-9,
+        7.229434249182665e-10, 8.061710142281779e-11, 7.913393099943723e-12, 6.81573661767678e-13,
+        5.13242671658949e-14,  3.365624762437814e-15, 1.913476326965035e-16, 9.385589781827253e-18,
+        3.950069964503411e-19, 1.417749517827512e-20, 4.309970276292175e-22, 1.101257519845548e-23,
+        2.344617755608987e-25, 4.11854415463823e-27,  5.902246763596448e-29, 6.812008916553065e-31,
+        6.237449498812102e-33, 4.452440579683377e-35, 2.426862352250487e-37, 9.852971481049686e-40,
+        2.891078872318428e-42, 5.906162708112361e-45, 8.01287459750397e-48,  6.789575424396417e-51,
+        3.308173010849252e-54, 8.250964876440456e-58, 8.848728128298018e-62, 3.064894889844417e-66,
+        1.988708229330752e-71, 6.049567152238783e-78
+    };
+    /* roots of legendre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_legendre(50, 16)[0] */
+    constexpr double wb_x_legendre[] = {
+        -0.998866404420071,  -0.9940319694320907, -0.9853540840480059, -0.9728643851066921,  -0.9566109552428079,
+        -0.9366566189448779, -0.9130785566557919, -0.885967979523613,  -0.8554297694299461,  -0.8215820708593359,
+        -0.7845558329003993, -0.7444943022260685, -0.7015524687068223, -0.6558964656854394,  -0.6077029271849502,
+        -0.5571583045146501, -0.5044581449074642, -0.4498063349740388, -0.3934143118975651,  -0.3355002454194374,
+        -0.276288193779532,  -0.2160072368760418, -0.1548905899981459, -0.09317470156008614, -0.03109833832718888,
+        0.03109833832718888, 0.09317470156008614, 0.1548905899981459,  0.2160072368760418,   0.276288193779532,
+        0.3355002454194374,  0.3934143118975651,  0.4498063349740388,  0.5044581449074642,   0.5571583045146501,
+        0.6077029271849502,  0.6558964656854394,  0.7015524687068223,  0.7444943022260685,   0.7845558329003993,
+        0.8215820708593359,  0.8554297694299461,  0.885967979523613,   0.9130785566557919,   0.9366566189448779,
+        0.9566109552428079,  0.9728643851066921,  0.9853540840480059,  0.9940319694320907,   0.998866404420071
+    };
+    /* weights for legendre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_legendre(50, 16)[1] */
+    constexpr double wb_w_legendre[] = {
+        0.002908622553155141, 0.006759799195745401, 0.01059054838365097, 0.01438082276148557,  0.01811556071348939,
+        0.02178024317012479,  0.02536067357001239,  0.0288429935805352,  0.03221372822357802,  0.03545983561514615,
+        0.03856875661258768,  0.0415284630901477,   0.04432750433880328, 0.04695505130394843,  0.04940093844946632,
+        0.05165570306958114,  0.05371062188899625,  0.05555774480621252, 0.05718992564772838,  0.05860084981322245,
+        0.05978505870426546,  0.06073797084177022,  0.06145589959031666, 0.06193606742068324,  0.06217661665534726,
+        0.06217661665534726,  0.06193606742068324,  0.06145589959031666, 0.06073797084177022,  0.05978505870426546,
+        0.05860084981322245,  0.05718992564772838,  0.05555774480621252, 0.05371062188899625,  0.05165570306958114,
+        0.04940093844946632,  0.04695505130394843,  0.04432750433880328, 0.0415284630901477,   0.03856875661258768,
+        0.03545983561514615,  0.03221372822357802,  0.0288429935805352,  0.02536067357001239,  0.02178024317012479,
+        0.01811556071348939,  0.01438082276148557,  0.01059054838365097, 0.006759799195745401, 0.002908622553155141
+    };
+    /* Fitted parameters for optimal choice of eps
+     * Call: python _precompute/wright_bessel.py 4 */
+    constexpr double wb_A[] = {0.41037, 0.30833, 6.9952, 18.382, -2.8566, 2.1122};
+
+    template
+    XSF_HOST_DEVICE inline double wright_bessel_integral(double a, double b, double x) {
+        /* 5. Integral representation
+         *
+         * K(a, b, x, r) = exp(-r + x * r^(-a) * cos(pi*a)) * r^(-b)
+         *               * sin(x * r^(-a) * sin(pi*a) + pi * b)
+         * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi))
+         *                      * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi)
+         *                        + (1-b)*phi)
+         *
+         * Phi(a, b, x) = 1/pi * int_eps^inf K(a, b, x, r) * dr
+         *              + eps^(1-b)/pi * int_0^pi P(eps, a, b, x, phi) * dphi
+         *
+         * for any eps > 0.
+         *
+         * Note that P has a misprint in Luchko (2008) Eq. 9, the cos(phi(beta-1)) at
+         * the end of the first line should be removed and the −sin(phi(beta−1)) at
+         * the end of the second line should read +(1-b)*phi.
+         * This integral representation introduced the free parameter eps (from the
+         * radius of complex contour integration). We try to choose eps such that
+         * the integrand behaves smoothly. Note that this is quite diffrent from how
+         * Luchko (2008) deals with eps: he is either looking for the limit eps -> 0
+         * or he sets (silently) eps=1. But having the freedom to set eps is much more
+         * powerful for numerical evaluation.
+         *
+         * As K has a leading exp(-r), we factor this out and apply Gauss-Laguerre
+         * quadrature rule:
+         *
+         * int_0^inf K(a, b, x, r+eps) dr = exp(-eps) int_0^inf exp(-r) Kmod(.., r) dr
+         *
+         * Note the shift r -> r+eps to have integation from 0 to infinity.
+         * The integral over P is done via a Gauss-Legendre quadrature rule.
+         *
+         * Note: Hardest argument range is large z, large b and small eps.
+         */
+
+        /* We use the free choice of eps to make the integral better behaved.
+         * 1. Concern is oscillatory behaviour of P. Therefore, we'd like to
+         *    make the change in the argument of cosine small, i.e. make arc length
+         *    int_0^phi sqrt(1 + f'(phi)^2) dphi small, with
+         *    f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a*phi) + (1-b)*phi
+         *    Proxy, make |f'(phi)| small.
+         * 2. Concern is int_0 K ~ int_0 (r+eps)^(-b) .. dr
+         *    This is difficult as r -> 0  for large b. It behaves better for larger
+         *    values of eps.
+         */
+
+        // Minimize oscillatory behavoir of P
+        double eps =
+            (wb_A[0] * b * std::exp(-0.5 * a) +
+             std::exp(
+                 wb_A[1] + 1 / (1 + a) * std::log(x) - wb_A[2] * std::exp(-wb_A[3] * a) +
+                 wb_A[4] / (1 + std::exp(wb_A[5] * a))
+             ));
+
+        if (a >= 4 && x >= 100) {
+            eps += 1; // This part is hard to fit
+        }
+
+        // Large b
+        if (b >= 8) {
+            /* Make P small compared to K by setting eps large enough.
+             * int K ~ exp(-eps) and int P ~ eps^(1-b) */
+            eps = std::fmax(eps, std::pow(b, -b / (1. - b)) + 0.1 * b);
+        }
+
+        // safeguard, higher better for larger a, lower better for tiny a.
+        eps = std::fmin(eps, 150.);
+        eps = std::fmax(eps, 3.); // 3 seems to be a pretty good choice in general.
+
+        // We factor out exp(-exp_term) from wb_Kmod and wb_P to avoid overflow of
+        // exp(..).
+        double exp_term = 0;
+        // From the exponent of K:
+        double r = wb_x_laguerre[50-1];  // largest value of x used in wb_Kmod
+        double x_r_a = x * std::pow(r + eps, -a);
+        exp_term = std::fmax(exp_term, x_r_a * cephes::cospi(a));
+        // From the exponent of P:
+        double x_eps_a = x * std::pow(eps, -a);
+        // phi = 0  =>  cos(phi) = cos(a * phi) = 1
+        exp_term = std::fmax(exp_term, eps + x_eps_a);
+        // phi = pi  => cos(phi) = -1
+        exp_term = std::fmax(exp_term, -eps + x_eps_a * cephes::cospi(a));
+
+        double res1 = 0;
+        double res2 = 0;
+
+        double y;
+        for (int k = 0; k < 50; k++) {
+            res1 += wb_w_laguerre[k] * wb_Kmod(-exp_term, eps, a, b, x, wb_x_laguerre[k]);
+            // y = (b-a)*(x+1)/2.0 + a  for integration from a=0 to b=pi
+            y = M_PI * (wb_x_legendre[k] + 1) / 2.0;
+            res2 += wb_w_legendre[k] * wb_P(-exp_term, eps, a, b, x, y);
+        }
+        res1 *= std::exp(-eps);
+        // (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1)
+        res2 *= M_PI / 2.0;
+        res2 *= std::pow(eps, 1 - b);
+
+        if (!log_wb) {
+            // Remember the factored out exp_term from wb_Kmod and wb_P
+            return std::exp(exp_term) / M_PI * (res1 + res2);
+        } else {
+            // logarithm of Wright's function
+            return exp_term + std::log((res1 + res2) / M_PI);
+        }
+    }
+} // namespace detail
+
+template
+XSF_HOST_DEVICE inline double wright_bessel_t(double a, double b, double x) {
+    /* Compute Wright's generalized Bessel function for scalar arguments.
+     *
+     * According to [1], it is an entire function defined as
+     *
+     * .. math:: \Phi(a, b; x) = \sum_{k=0}^\infty \frac{x^k}{k! \Gamma(a k + b)}
+     *
+     * So far, only non-negative values of rho=a, beta=b and z=x are implemented.
+     * There are 5 different approaches depending on the ranges of the arguments:
+     *
+     * 1. Taylor series expansion in x=0 [1], for x <= 1.
+     *    Involves gamma funtions in each term.
+     * 2. Taylor series expansion in x=0 [2], for large a.
+     * 3. Taylor series in a=0, for tiny a and not too large x.
+     * 4. Asymptotic expansion for large x [3, 4].
+     *    Suitable for large x while still small a and b.
+     * 5. Integral representation [5], in principle for all arguments.
+     *
+     * References
+     * ----------
+     * [1] https://dlmf.nist.gov/10.46.E1
+     * [2] P. K. Dunn, G. K. Smyth (2005), Series evaluation of Tweedie exponential
+     *     dispersion model densities. Statistics and Computing 15 (2005): 267-280.
+     * [3] E. M. Wright (1935), The asymptotic expansion of the generalized Bessel
+     *     function. Proc. London Math. Soc. (2) 38, pp. 257-270.
+     *     https://doi.org/10.1112/plms/s2-38.1.257
+     * [4] R. B. Paris (2017), The asymptotics of the generalised Bessel function,
+     *     Mathematica Aeterna, Vol. 7, 2017, no. 4, 381 - 406,
+     *     https://arxiv.org/abs/1711.03006
+     * [5] Y. F. Luchko (2008), Algorithms for Evaluation of the Wright Function for
+     *     the Real Arguments' Values, Fractional Calculus and Applied Analysis 11(1)
+     *     http://sci-gems.math.bas.bg/jspui/bitstream/10525/1298/1/fcaa-vol11-num1-2008-57p-75p.pdf
+     */
+    if (std::isnan(a) || std::isnan(b) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (a < 0 || b < 0 || x < 0) {
+        set_error("wright_bessel", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(x)) {
+        if (std::isinf(a) || std::isinf(b)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+        return std::numeric_limits::infinity();
+    }
+    if (std::isinf(a) || std::isinf(b)) {
+        return std::numeric_limits::quiet_NaN(); // or 0
+    }
+    if (a >= detail::rgamma_zero || b >= detail::rgamma_zero) {
+        set_error("wright_bessel", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0) {
+        // return rgamma(b)
+        if (!log_wb) {
+            return cephes::rgamma(b);
+        } else {
+            // logarithm of Wright's function
+            return -cephes::lgam(b);
+        }
+    }
+    if (a == 0) {
+        // return exp(x) * rgamma(b)
+        if (!log_wb) {
+            return detail::exp_rgamma(x, b);
+        } else {
+            // logarithm of Wright's function
+            return x - cephes::lgam(b);
+        }
+    }
+
+    constexpr double exp_inf = 709.78271289338403;
+    int order;
+    if ((a <= 1e-3 && b <= 50 && x <= 9) || (a <= 1e-4 && b <= 70 && x <= 100) ||
+        (a <= 1e-5 && b <= 170 && (x < exp_inf || (log_wb && x <= 1e3)))) {
+        /* Taylor Series expansion in a=0 to order=order => precision <= 1e-11
+         * If beta is also small => precision <= 1e-11.
+         * max order = 5 */
+        if (a <= 1e-5) {
+            if (x <= 1) {
+                order = 2;
+            } else if (x <= 10) {
+                order = 3;
+            } else if (x <= 100) {
+                order = 4;
+            } else { // x < exp_inf
+                order = 5;
+            }
+        } else if (a <= 1e-4) {
+            if (x <= 1e-2) {
+                order = 2;
+            } else if (x <= 1) {
+                order = 3;
+            } else if (x <= 10) {
+                order = 4;
+            } else { // x <= 100
+                order = 5;
+            }
+        } else { // a <= 1e-3
+            if (x <= 1e-5) {
+                order = 2;
+            } else if (x <= 1e-1) {
+                order = 3;
+            } else if (x <= 1) {
+                order = 4;
+            } else { // x <= 9
+                order = 5;
+            }
+        }
+
+        return detail::wb_small_a(a, b, x, order);
+    }
+
+    if (x <= 1) {
+        // 18 term Taylor Series => error mostly smaller 5e-14
+        double res = detail::wb_series(a, b, x, 0, 18);
+        if (log_wb) res = std::log(res);
+        return res;
+    }
+    if (x <= 2) {
+        // 20 term Taylor Series => error mostly smaller 1e-12 to 1e-13
+        double res = detail::wb_series(a, b, x, 0, 20);
+        if (log_wb) res = std::log(res);
+        return res;
+    }
+    if (a >= 5) {
+        /* Taylor series around the approximate maximum term.
+         * Set number of terms=order. */
+        if (a >= 10) {
+            if (x <= 1e11) {
+                order = 6;
+            } else {
+                order = static_cast(std::fmin(std::log10(x) - 5 + b / 10, 30));
+            }
+        } else {
+            if (x <= 1e4) {
+                order = 6;
+            } else if (x <= 1e8) {
+                order = static_cast(2 * std::log10(x));
+            } else if (x <= 1e10) {
+                order = static_cast(4 * std::log10(x) - 16);
+            } else {
+                order = static_cast(std::fmin(6 * std::log10(x) - 36, 100));
+            }
+        }
+        return detail::wb_large_a(a, b, x, order);
+    }
+    if (std::pow(a * x, 1 / (1. + a)) >= 14 + b * b / (2 * (1 + a))) {
+        /* Asymptotic expansion in Z = (a*x)^(1/(1+a)) up to 8th term 1/Z^8.
+         * For 1/Z^k, the highest term in b is b^(2*k) * a0 / (2^k k! (1+a)^k).
+         * As a0 is a common factor to all orders, this explains a bit the
+         * domain of good convergence set above.
+         * => precision ~ 1e-11 but can go down to ~1e-8 or 1e-7
+         * Note: We ensured a <= 5 as this is a bad approximation for large a. */
+        return detail::wb_asymptotic(a, b, x);
+    }
+    if (0.5 <= a && a <= 1.8 && 100 <= b && 1e5 <= x) {
+        // This is a very hard domain. This condition is placed after wb_asymptotic.
+        // TODO: Explore ways to cover this domain.
+        return std::numeric_limits::quiet_NaN();
+    }
+    return detail::wright_bessel_integral(a, b, x);
+}
+
+
+XSF_HOST_DEVICE inline double wright_bessel(double a, double b, double x) {
+    return wright_bessel_t(a, b, x);
+}
+
+XSF_HOST_DEVICE inline float wright_bessel(float a, float b, float x) {
+    return wright_bessel(static_cast(a), static_cast(b), static_cast(x));
+}
+
+XSF_HOST_DEVICE inline double log_wright_bessel(double a, double b, double x) {
+    return wright_bessel_t(a, b, x);
+}
+
+XSF_HOST_DEVICE inline float log_wright_bessel(float a, float b, float x) {
+    return log_wright_bessel(static_cast(a), static_cast(b), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h b/venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h
new file mode 100644
index 0000000000000000000000000000000000000000..64e83ca390a094b85380ff69c24ba2cdead33d7f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h
@@ -0,0 +1,35 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+#pragma once
+
+#include "config.h"
+
+namespace xsf {
+namespace detail {
+
+    XSF_HOST_DEVICE inline std::complex zlog1(std::complex z) {
+        /* Compute log, paying special attention to accuracy around 1. We
+         * implement this ourselves because some systems (most notably the
+         * Travis CI machines) are weak in this regime. */
+        std::complex coeff = -1.0;
+        std::complex res = 0.0;
+
+        if (std::abs(z - 1.0) > 0.1) {
+            return std::log(z);
+        }
+
+        z -= 1.0;
+        for (int n = 1; n < 17; n++) {
+            coeff *= -z;
+            res += coeff / static_cast(n);
+            if (std::abs(res / coeff) < std::numeric_limits::epsilon()) {
+                break;
+            }
+        }
+        return res;
+    }
+} // namespace detail
+} // namespace xsf